diff options
274 files changed, 4920 insertions, 4034 deletions
diff --git a/configure b/configure index 59aa6ece6b2..135bdcd3782 100755 --- a/configure +++ b/configure @@ -418,7 +418,7 @@ opt ccache 0 "invoke gcc/clang via ccache to reuse object files between builds" opt local-rust 0 "use an installed rustc rather than downloading a snapshot" opt inject-std-version 1 "inject the current compiler version of libstd into programs" opt llvm-static-stdcpp 0 "statically link to libstdc++ for LLVM" -opt rpath 1 "build rpaths into rustc itself" +opt rpath 0 "build rpaths into rustc itself" opt nightly 0 "build nightly packages" opt verify-install 1 "verify installed binaries work" opt jemalloc 1 "build liballoc with jemalloc" diff --git a/man/rustc.1 b/man/rustc.1 index df65cf7bb37..2484960cac6 100644 --- a/man/rustc.1 +++ b/man/rustc.1 @@ -138,8 +138,8 @@ A space-separated list of arguments to pass through to LLVM. If specified, the compiler will save more files (.bc, .o, .no-opt.bc) generated throughout compilation in the output directory. .TP -\fBno-rpath\fR -If specified, then the rpath value for dynamic libraries will not be set in +\fBrpath\fR +If specified, then the rpath value for dynamic libraries will be set in either dynamic library or executable outputs. .TP \fBno-prepopulate-passes\fR diff --git a/mk/main.mk b/mk/main.mk index c01410a591b..7400b39c968 100644 --- a/mk/main.mk +++ b/mk/main.mk @@ -122,8 +122,8 @@ endif ifdef TRACE CFG_RUSTC_FLAGS += -Z trace endif -ifdef CFG_DISABLE_RPATH -CFG_RUSTC_FLAGS += -C no-rpath +ifdef CFG_ENABLE_RPATH +CFG_RUSTC_FLAGS += -C rpath endif # The executables crated during this compilation process have no need to include diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 9eac38e4cd5..4de66d8746f 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -187,7 +187,7 @@ pub fn log_config(config: &Config) { opt_str(&config.filter .as_ref() .map(|re| { - re.to_str().into_string() + re.to_string().into_string() })))); logv(c, format!("runtool: {}", opt_str(&config.runtool))); logv(c, format!("host-rustcflags: {}", diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index 8e79f58c608..7681792bdf5 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -31,7 +31,7 @@ pub fn load_errors(re: &Regex, testfile: &Path) -> Vec<ExpectedError> { fn parse_expected(line_num: uint, line: &str, re: &Regex) -> Option<ExpectedError> { re.captures(line).and_then(|caps| { let adjusts = caps.name("adjusts").len(); - let kind = caps.name("kind").to_ascii().to_lower().into_str(); + let kind = caps.name("kind").to_ascii().to_lower().into_string(); let msg = caps.name("msg").trim().to_string(); debug!("line={} kind={} msg={}", line_num, kind, msg); diff --git a/src/compiletest/util.rs b/src/compiletest/util.rs index c6e02606f74..369e6b0af64 100644 --- a/src/compiletest/util.rs +++ b/src/compiletest/util.rs @@ -41,7 +41,7 @@ pub fn make_new_path(path: &str) -> String { Some(curr) => { format!("{}{}{}", path, path_div(), curr) } - None => path.to_str() + None => path.to_string() } } diff --git a/src/doc/guide-tasks.md b/src/doc/guide-tasks.md index 9021b761954..6ef273e7a1a 100644 --- a/src/doc/guide-tasks.md +++ b/src/doc/guide-tasks.md @@ -465,7 +465,7 @@ fn stringifier(channel: &DuplexStream<String, uint>) { let mut value: uint; loop { value = channel.recv(); - channel.send(value.to_str()); + channel.send(value.to_string()); if value == 0 { break; } } } @@ -478,7 +478,7 @@ send strings (the first type parameter) and receive `uint` messages (the second type parameter). The body itself simply loops, reading from the channel and then sending its response back. The actual response itself is simply the stringified version of the received value, -`uint::to_str(value)`. +`uint::to_string(value)`. Here is the code for the parent task: @@ -492,7 +492,7 @@ use std::comm::duplex; # let mut value: uint; # loop { # value = channel.recv(); -# channel.send(value.to_str()); +# channel.send(value.to_string()); # if value == 0u { break; } # } # } diff --git a/src/doc/guide.md b/src/doc/guide.md index d2e5d1dbd62..7136a7bafb0 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -940,19 +940,332 @@ fn foo(x: int) -> int { There are some additional ways to define functions, but they involve features that we haven't learned about yet, so let's just leave it at that for now. + ## Comments -return +Now that we have some functions, it's a good idea to learn about comments. +Comments are notes that you leave to other programmers to help explain things +about your code. The compiler mostly ignores them. + +Rust has two kinds of comments that you should care about: **line comment**s +and **doc comment**s. + +```{rust} +// Line comments are anything after '//' and extend to the end of the line. + +let x = 5i; // this is also a line comment. + +// If you have a long explanation for something, you can put line comments next +// to each other. Put a space between the // and your comment so that it's +// more readable. +``` + +The other kind of comment is a doc comment. Doc comments use `///` instead of +`//`, and support Markdown notation inside: -comments +```{rust} +/// `hello` is a function that prints a greeting that is personalized based on +/// the name given. +/// +/// # Arguments +/// +/// * `name` - The name of the person you'd like to greet. +/// +/// # Example +/// +/// ```rust +/// let name = "Steve"; +/// hello(name); // prints "Hello, Steve!" +/// ``` +fn hello(name: &str) { + println!("Hello, {}!", name); +} +``` + +When writing doc comments, adding sections for any arguments, return values, +and providing some examples of usage is very, very helpful. + +You can use the `rustdoc` tool to generate HTML documentation from these doc +comments. We will talk more about `rustdoc` when we get to modules, as +generally, you want to export documentation for a full module. ## Compound Data Types -Tuples +Rust, like many programming languages, has a number of different data types +that are built-in. You've already done some simple work with integers and +strings, but next, let's talk about some more complicated ways of storing data. + +### Tuples + +The first compound data type we're going to talk about are called **tuple**s. +Tuples are an ordered list of a fixed size. Like this: + +```rust +let x = (1i, "hello"); +``` + +The parenthesis and commas form this two-length tuple. Here's the same code, but +with the type annotated: + +```rust +let x: (int, &str) = (1, "hello"); +``` + +As you can see, the type of a tuple looks just like the tuple, but with each +position having a type name rather than the value. Careful readers will also +note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple. +You haven't seen `&str` as a type before, and we'll discuss the details of +strings later. In systems programming languages, strings are a bit more complex +than in other languages. For now, just read `&str` as "a string slice," and +we'll learn more soon. + +You can access the fields in a tuple through a **destructuring let**. Here's +an example: + +```rust +let (x, y, z) = (1i, 2i, 3i); + +println!("x is {}", x); +``` + +Remember before when I said the left hand side of a `let` statement was more +powerful than just assigning a binding? Here we are. We can put a pattern on +the left hand side of the `let`, and if it matches up to the right hand side, +we can assign multiple bindings at once. In this case, `let` 'destructures,' +or 'breaks up,' the tuple, and assigns the bits to three bindings. + +This pattern is very powerful, and we'll see it repeated more later. + +The last thing to say about tuples is that they are only equivalent if +the arity, types, and values are all identical. + +```rust +let x = (1i, 2i, 3i); +let y = (2i, 3i, 4i); + +if x == y { + println!("yes"); +} else { + println!("no"); +} +``` + +This will print `no`, as the values aren't equal. + +One other use of tuples is to return multiple values from a function: + +```rust +fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) } + +fn main() { + let (x, y) = next_two(5i); + println!("x, y = {}, {}", x, y); +} +``` + +Even though Rust functions can only return one value, a tuple _is_ one value, +that happens to be made up of two. You can also see in this example how you +can destructure a pattern returned by a function, as well. + +Tuples are a very simple data structure, and so are not often what you want. +Let's move on to their bigger sibling, structs. + +### Structs + +A struct is another form of a 'record type,' just like a tuple. There's a +difference: structs give each element that they contain a name, called a +'field' or a 'member.' Check it out: + +```rust +struct Point { + x: int, + y: int, +} + +fn main() { + let origin = Point { x: 0i, y: 0i }; + + println!("The origin is at ({}, {})", origin.x, origin.y); +} +``` + +There's a lot going on here, so let's break it down. We declare a struct with +the `struct` keyword, and then with a name. By convention, structs begin with a +capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`. + +We can create an instance of our struct via `let`, as usual, but we use a `key: +value` style syntax to set each field. The order doesn't need to be the same as +in the original declaration. + +Finally, because fields have names, we can access the field through dot +notation: `origin.x`. + +The values in structs are immutable, like other bindings in Rust. However, you +can use `mut` to make them mutable: + +```rust +struct Point { + x: int, + y: int, +} + +fn main() { + let mut point = Point { x: 0i, y: 0i }; + + point.x = 5; + + println!("The point is at ({}, {})", point.x, point.y); +} +``` + +This will print `The point is at (5, 0)`. + +### Tuple Structs and Newtypes + +Rust has another data type that's like a hybrid between a tuple and a struct, +called a **tuple struct**. Tuple structs do have a name, but their fields +don't: + + +``` +struct Color(int, int, int); +struct Point(int, int, int); +``` + +These two will not be equal, even if they have the same values: + +```{rust,ignore} +let black = Color(0, 0, 0); +let origin = Point(0, 0, 0); +``` + +It is almost always better to use a struct than a tuple struct. We would write +`Color` and `Point` like this instead: + +```rust +struct Color { + red: int, + blue: int, + green: int, +} + +struct Point { + x: int, + y: int, + z: int, +} +``` + +Now, we have actual names, rather than positions. Good names are important, +and with a struct, we have actual names. + +There _is_ one case when a tuple struct is very useful, though, and that's a +tuple struct with only one element. We call this a 'newtype,' because it lets +you create a new type that's a synonym for another one: + +``` +struct Inches(int); +struct Centimeters(int); + +let length = Inches(10); + +let Inches(integer_length) = length; +println!("length is {} inches", integer_length); +``` -Structs +As you can see here, you can extract the inner integer type through a +destructuring `let`. + +### Enums + +Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful +feature of Rust, and are used throughout the standard library. Enums look +like this: + +``` +enum Ordering { + Less, + Equal, + Greater, +} +``` + +This is an enum that is provided by the Rust standard library. An `Ordering` +can only be _one_ of `Less`, `Equal`, or `Greater` at any given time. Here's +an example: + +```rust +let x = 5i; +let y = 10i; + +let ordering = x.cmp(&y); + +if ordering == Less { + println!("less"); +} else if ordering == Greater { + println!("greater"); +} else if ordering == Equal { + println!("equal"); +} +``` + +`cmp` is a function that compares two things, and returns an `Ordering`. The +call looks a little bit strange: rather than `cmp(x, y)`, we say `x.cmp(&y)`. +We haven't covered methods and references yet, so it should look a little bit +foreign. Right now, just pretend it says `cmp(x, y)`, and we'll get to those +details soon. + +The `ordering` variable has the type `Ordering`, and so contains one of the +three values. We can then do a bunch of `if`/`else` comparisons to check +which one it is. + +However, repeated `if`/`else` comparisons get quite tedious. Rust has a feature +that not only makes them nicer to read, but also makes sure that you never +miss a case. Before we get to that, though, let's talk about another kind of +enum: one with values. + +This enum has two variants, one of which has a value.: + +``` +enum OptionalInt { + Value(int), + Missing +} + +fn main() { + let x = Value(5); + let y = Missing; + + match x { + Value(n) => println!("x is {:d}", n), + Missing => println!("x is missing!"), + } + + match y { + Value(n) => println!("y is {:d}", n), + Missing => println!("y is missing!"), + } +} +``` + +This enum represents an `int` that we may or may not have. In the `Missing` +case, we have no value, but in the `Value` case, we do. This enum is specific +to `int`s, though. We can make it usable by any type, but we haven't quite +gotten there yet! + +You can have any number of values in an enum: + +``` +enum OptionalColor { + Color(int, int, int), + Missing +} +``` -Enums +Enums with values are quite useful, but as I mentioned, they're even more +useful when they're generic across types. But before we get to generics, let's +talk about how to fix this big `if`/`else` statements we've been writing. We'll +do that with `match`. ## Match diff --git a/src/doc/po/ja/complement-cheatsheet.md.po b/src/doc/po/ja/complement-cheatsheet.md.po index 3b7bb2e740d..b429f3020a7 100644 --- a/src/doc/po/ja/complement-cheatsheet.md.po +++ b/src/doc/po/ja/complement-cheatsheet.md.po @@ -23,7 +23,7 @@ msgstr "" #| "[tarball]: http://static.rust-lang.org/dist/rust-nightly.tar.gz [win-exe]: " #| "http://static.rust-lang.org/dist/rust-nightly-install.exe" msgid "" -"Use [`ToStr`](http://static.rust-lang.org/doc/master/std/to_str/trait.ToStr." +"Use [`ToString`](http://static.rust-lang.org/doc/master/std/to_str/trait.ToString." "html)." msgstr "" "[tarball]: http://static.rust-lang.org/dist/rust-nightly.tar.gz\n" @@ -34,7 +34,7 @@ msgstr "" #, fuzzy #| msgid "" #| "~~~~ let x: f64 = 4.0; let y: uint = x as uint; assert!(y == 4u); ~~~~" -msgid "~~~ let x: int = 42; let y: String = x.to_str(); ~~~" +msgid "~~~ let x: int = 42; let y: String = x.to_string(); ~~~" msgstr "" "~~~~\n" "let x: f64 = 4.0;\n" diff --git a/src/doc/po/ja/rust.md.po b/src/doc/po/ja/rust.md.po index f0aef7accb6..a28a62d01c2 100644 --- a/src/doc/po/ja/rust.md.po +++ b/src/doc/po/ja/rust.md.po @@ -1656,7 +1656,7 @@ msgstr "" #| msgid "~~~~ {.ignore} // main.rs extern crate world; fn main() { println(~\"hello \" + world::explore()); } ~~~~" msgid "" "impl Printable for int {\n" -" fn to_string(&self) -> String { self.to_str() }\n" +" fn to_string(&self) -> String { self.to_string() }\n" "}\n" msgstr "" "~~~~ {.ignore}\n" diff --git a/src/doc/po/ja/tutorial.md.po b/src/doc/po/ja/tutorial.md.po index 68c32ae9704..597cf5b7ac5 100644 --- a/src/doc/po/ja/tutorial.md.po +++ b/src/doc/po/ja/tutorial.md.po @@ -4410,9 +4410,9 @@ msgstr "" #. type: Plain text #: src/doc/tutorial.md:2528 -msgid "#[deriving(Rand, ToStr)] enum ABC { A, B, C } ~~~" +msgid "#[deriving(Rand, ToString)] enum ABC { A, B, C } ~~~" msgstr "" -"#[deriving(Rand, ToStr)]\n" +"#[deriving(Rand, ToString)]\n" "enum ABC { A, B, C }\n" "~~~" @@ -4422,15 +4422,15 @@ msgstr "" #| msgid "" #| "The full list of derivable traits is `Eq`, `TotalEq`, `Ord`, `TotalOrd`, " #| "`Encodable` `Decodable`, `Clone`, `DeepClone`, `Hash`, `Rand`, " -#| "`Zero`, and `ToStr`." +#| "`Zero`, and `ToString`." msgid "" "The full list of derivable traits is `Eq`, `TotalEq`, `Ord`, `TotalOrd`, " "`Encodable` `Decodable`, `Clone`, `DeepClone`, `Hash`, `Rand`, " -"`Default`, `Zero`, and `ToStr`." +"`Default`, `Zero`, and `ToString`." msgstr "" "実装を自動的に導出可能なトレイトは、 `Eq`, `TotalEq`, `Ord`, `TotalOrd`, " "`Encodable` `Decodable`, `Clone`, `DeepClone`, `Hash`, `Rand`, `Zero`, " -"および `ToStr` です。." +"および `ToString` です。." #. type: Plain text #: src/doc/tutorial.md:2534 diff --git a/src/doc/rust.md b/src/doc/rust.md index f09214d1a6f..9d5a6fa42a8 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -3671,15 +3671,15 @@ An example of an object type: ~~~~ trait Printable { - fn to_string(&self) -> String; + fn stringify(&self) -> String; } impl Printable for int { - fn to_string(&self) -> String { self.to_str() } + fn stringify(&self) -> String { self.to_string() } } fn print(a: Box<Printable>) { - println!("{}", a.to_string()); + println!("{}", a.stringify()); } fn main() { diff --git a/src/etc/vim/syntax/rust.vim b/src/etc/vim/syntax/rust.vim index 6285eb6895d..86df9cba4cd 100644 --- a/src/etc/vim/syntax/rust.vim +++ b/src/etc/vim/syntax/rust.vim @@ -100,7 +100,7 @@ syn keyword rustTrait RawPtr syn keyword rustTrait Buffer Writer Reader Seek syn keyword rustTrait Str StrVector StrSlice OwnedStr syn keyword rustTrait IntoMaybeOwned StrAllocating -syn keyword rustTrait ToStr IntoStr +syn keyword rustTrait ToString IntoStr syn keyword rustTrait Tuple1 Tuple2 Tuple3 Tuple4 syn keyword rustTrait Tuple5 Tuple6 Tuple7 Tuple8 syn keyword rustTrait Tuple9 Tuple10 Tuple11 Tuple12 diff --git a/src/libcollections/bitv.rs b/src/libcollections/bitv.rs index f01b1cf9815..905c27ee82c 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bitv.rs @@ -60,17 +60,17 @@ enum BitvVariant { Big(BigBitv), Small(SmallBitv) } /// bv.set(3, true); /// bv.set(5, true); /// bv.set(7, true); -/// println!("{}", bv.to_str()); +/// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// /// // flip all values in bitvector, producing non-primes less than 10 /// bv.negate(); -/// println!("{}", bv.to_str()); +/// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// /// // reset bitvector to empty /// bv.clear(); -/// println!("{}", bv.to_str()); +/// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// ``` pub struct Bitv { @@ -996,10 +996,10 @@ mod tests { #[test] fn test_to_str() { let zerolen = Bitv::new(); - assert_eq!(zerolen.to_str().as_slice(), ""); + assert_eq!(zerolen.to_string().as_slice(), ""); let eightbits = Bitv::with_capacity(8u, false); - assert_eq!(eightbits.to_str().as_slice(), "00000000") + assert_eq!(eightbits.to_string().as_slice(), "00000000") } #[test] @@ -1022,7 +1022,7 @@ mod tests { let mut b = bitv::Bitv::with_capacity(2, false); b.set(0, true); b.set(1, false); - assert_eq!(b.to_str().as_slice(), "10"); + assert_eq!(b.to_string().as_slice(), "10"); } #[test] @@ -1333,7 +1333,7 @@ mod tests { fn test_from_bytes() { let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); let str = format!("{}{}{}", "10110110", "00000000", "11111111"); - assert_eq!(bitv.to_str().as_slice(), str.as_slice()); + assert_eq!(bitv.to_string().as_slice(), str.as_slice()); } #[test] @@ -1352,7 +1352,7 @@ mod tests { fn test_from_bools() { let bools = vec![true, false, true, true]; let bitv: Bitv = bools.iter().map(|n| *n).collect(); - assert_eq!(bitv.to_str().as_slice(), "1011"); + assert_eq!(bitv.to_string().as_slice(), "1011"); } #[test] @@ -1787,7 +1787,7 @@ mod tests { s.insert(10); s.insert(50); s.insert(2); - assert_eq!("{1, 2, 10, 50}".to_string(), s.to_str()); + assert_eq!("{1, 2, 10, 50}".to_string(), s.to_string()); } fn rng() -> rand::IsaacRng { diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index 92abfaad348..2d138b1a189 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -787,7 +787,6 @@ mod test_btree { fn insert_test_one() { let b = BTree::new(1i, "abc".to_string(), 2); let is_insert = b.insert(2i, "xyz".to_string()); - //println!("{}", is_insert.clone().to_str()); assert!(is_insert.root.is_leaf()); } @@ -798,7 +797,7 @@ mod test_btree { let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string()); let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3)); let b = BTree::new_with_node_len(n, 3, 2); - //println!("{}", b.clone().insert(4, "ddd".to_string()).to_str()); + //println!("{}", b.clone().insert(4, "ddd".to_string()).to_string()); assert!(b.insert(4, "ddd".to_string()).root.is_leaf()); } @@ -810,7 +809,7 @@ mod test_btree { let leaf_elt_4 = LeafElt::new(4i, "ddd".to_string()); let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4)); let b = BTree::new_with_node_len(n, 3, 2); - //println!("{}", b.clone().insert(5, "eee".to_string()).to_str()); + //println!("{}", b.clone().insert(5, "eee".to_string()).to_string()); assert!(!b.insert(5, "eee".to_string()).root.is_leaf()); } @@ -827,7 +826,7 @@ mod test_btree { b = b.clone().insert(7, "ggg".to_string()); b = b.clone().insert(8, "hhh".to_string()); b = b.clone().insert(0, "omg".to_string()); - //println!("{}", b.clone().to_str()); + //println!("{}", b.clone().to_string()); assert!(!b.root.is_leaf()); } @@ -905,11 +904,11 @@ mod test_btree { assert!(&b2.cmp(&b) == &Greater) } - //Tests the BTree's to_str() method. + //Tests the BTree's to_string() method. #[test] fn btree_tostr_test() { let b = BTree::new(1i, "abc".to_string(), 2); - assert_eq!(b.to_str(), "Key: 1, value: abc;".to_string()) + assert_eq!(b.to_string(), "Key: 1, value: abc;".to_string()) } } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 4114c8cb1c4..ed2d6738876 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -1041,12 +1041,12 @@ mod tests { #[test] fn test_show() { let list: DList<int> = range(0i, 10).collect(); - assert!(list.to_str().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); + assert!(list.to_string().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); let list: DList<&str> = vec!["just", "one", "test", "more"].iter() .map(|&s| s) .collect(); - assert!(list.to_str().as_slice() == "[just, one, test, more]"); + assert!(list.to_string().as_slice() == "[just, one, test, more]"); } #[cfg(test)] diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/smallintmap.rs index 14e41f3fef9..ca62b1235d5 100644 --- a/src/libcollections/smallintmap.rs +++ b/src/libcollections/smallintmap.rs @@ -491,7 +491,7 @@ mod test_map { map.insert(1, 2i); map.insert(3, 4i); - let map_str = map.to_str(); + let map_str = map.to_string(); let map_str = map_str.as_slice(); assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); assert_eq!(format!("{}", empty), "{}".to_string()); diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index ddba4b34e3a..63c95fa25cb 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -657,7 +657,7 @@ impl<'a> StrAllocating for MaybeOwned<'a> { #[inline] fn into_string(self) -> String { match self { - Slice(s) => s.to_string(), + Slice(s) => String::from_str(s), Owned(s) => s } } @@ -673,7 +673,7 @@ impl<'a> Clone for MaybeOwned<'a> { fn clone(&self) -> MaybeOwned<'a> { match *self { Slice(s) => Slice(s), - Owned(ref s) => Owned(s.to_string()) + Owned(ref s) => Owned(String::from_str(s.as_slice())) } } } @@ -762,7 +762,7 @@ pub mod raw { let a = vec![65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8]; let b = a.as_ptr(); let c = from_buf_len(b, 3u); - assert_eq!(c, "AAA".to_string()); + assert_eq!(c, String::from_str("AAA")); } } } @@ -776,12 +776,6 @@ pub trait StrAllocating: Str { /// Convert `self` into a `String`, not making a copy if possible. fn into_string(self) -> String; - /// Convert `self` into a `String`. - #[inline] - fn to_string(&self) -> String { - String::from_str(self.as_slice()) - } - #[allow(missing_doc)] #[deprecated = "replaced by .into_string()"] fn into_owned(self) -> String { @@ -933,7 +927,7 @@ pub trait StrAllocating: Str { impl<'a> StrAllocating for &'a str { #[inline] fn into_string(self) -> String { - self.to_string() + String::from_str(self) } } @@ -963,11 +957,19 @@ impl OwnedStr for String { #[cfg(test)] mod tests { - use std::prelude::*; use std::iter::AdditiveIterator; use std::default::Default; + use std::char::Char; + use std::clone::Clone; + use std::cmp::{Equal, Greater, Less, Ord, Eq, PartialOrd, PartialEq, Equiv}; + use std::result::{Ok, Err}; + use std::option::{Some, None}; + use std::ptr::RawPtr; + use std::iter::{Iterator, DoubleEndedIterator}; + use Collection; - use str::*; + use super::*; + use std::slice::{Vector, ImmutableVector}; use string::String; use vec::Vec; @@ -1028,17 +1030,17 @@ mod tests { #[test] fn test_collect() { - let empty = "".to_string(); + let empty = String::from_str(""); let s: String = empty.as_slice().chars().collect(); assert_eq!(empty, s); - let data = "ประเทศไทย中".to_string(); + let data = String::from_str("ประเทศไทย中"); let s: String = data.as_slice().chars().collect(); assert_eq!(data, s); } #[test] fn test_into_bytes() { - let data = "asdf".to_string(); + let data = String::from_str("asdf"); let buf = data.into_bytes(); assert_eq!(b"asdf", buf.as_slice()); } @@ -1055,7 +1057,7 @@ mod tests { assert!(data.slice(2u, 4u).find_str("ab").is_none()); let string = "ประเทศไทย中华Việt Nam"; - let mut data = string.to_string(); + let mut data = String::from_str(string); data.push_str(string); assert!(data.as_slice().find_str("ไท华").is_none()); assert_eq!(data.as_slice().slice(0u, 43u).find_str(""), Some(0u)); @@ -1092,11 +1094,13 @@ mod tests { fn t(v: &[String], s: &str) { assert_eq!(v.concat().as_slice(), s); } - t(["you".to_string(), "know".to_string(), "I'm".to_string(), - "no".to_string(), "good".to_string()], "youknowI'mnogood"); + t([String::from_str("you"), String::from_str("know"), + String::from_str("I'm"), + String::from_str("no"), String::from_str("good")], + "youknowI'mnogood"); let v: &[String] = []; t(v, ""); - t(["hi".to_string()], "hi"); + t([String::from_str("hi")], "hi"); } #[test] @@ -1104,12 +1108,13 @@ mod tests { fn t(v: &[String], sep: &str, s: &str) { assert_eq!(v.connect(sep).as_slice(), s); } - t(["you".to_string(), "know".to_string(), "I'm".to_string(), - "no".to_string(), "good".to_string()], + t([String::from_str("you"), String::from_str("know"), + String::from_str("I'm"), + String::from_str("no"), String::from_str("good")], " ", "you know I'm no good"); let v: &[String] = []; t(v, " ", ""); - t(["hi".to_string()], " ", "hi"); + t([String::from_str("hi")], " ", "hi"); } #[test] @@ -1136,11 +1141,11 @@ mod tests { #[test] fn test_repeat() { - assert_eq!("x".repeat(4), "xxxx".to_string()); - assert_eq!("hi".repeat(4), "hihihihi".to_string()); - assert_eq!("ไท华".repeat(3), "ไท华ไท华ไท华".to_string()); - assert_eq!("".repeat(4), "".to_string()); - assert_eq!("hi".repeat(0), "".to_string()); + assert_eq!("x".repeat(4), String::from_str("xxxx")); + assert_eq!("hi".repeat(4), String::from_str("hihihihi")); + assert_eq!("ไท华".repeat(3), String::from_str("ไท华ไท华ไท华")); + assert_eq!("".repeat(4), String::from_str("")); + assert_eq!("hi".repeat(0), String::from_str("")); } #[test] @@ -1168,9 +1173,9 @@ mod tests { } let letters = a_million_letter_a(); assert!(half_a_million_letter_a() == - unsafe {raw::slice_bytes(letters.as_slice(), + unsafe {String::from_str(raw::slice_bytes(letters.as_slice(), 0u, - 500000)}.to_string()); + 500000))}); } #[test] @@ -1204,13 +1209,13 @@ mod tests { #[test] fn test_replace() { let a = "a"; - assert_eq!("".replace(a, "b"), "".to_string()); - assert_eq!("a".replace(a, "b"), "b".to_string()); - assert_eq!("ab".replace(a, "b"), "bb".to_string()); + assert_eq!("".replace(a, "b"), String::from_str("")); + assert_eq!("a".replace(a, "b"), String::from_str("b")); + assert_eq!("ab".replace(a, "b"), String::from_str("bb")); let test = "test"; assert!(" test test ".replace(test, "toast") == - " toast toast ".to_string()); - assert_eq!(" test test ".replace(test, ""), " ".to_string()); + String::from_str(" toast toast ")); + assert_eq!(" test test ".replace(test, ""), String::from_str(" ")); } #[test] @@ -1285,7 +1290,7 @@ mod tests { } let letters = a_million_letter_x(); assert!(half_a_million_letter_x() == - letters.as_slice().slice(0u, 3u * 500000u).to_string()); + String::from_str(letters.as_slice().slice(0u, 3u * 500000u))); } #[test] @@ -1513,7 +1518,7 @@ mod tests { let a = vec![65, 65, 65, 65, 65, 65, 65, 0]; let b = a.as_ptr(); let c = raw::from_c_str(b); - assert_eq!(c, "AAAAAAA".to_string()); + assert_eq!(c, String::from_str("AAAAAAA")); } } @@ -1535,7 +1540,7 @@ mod tests { fn test_as_bytes_fail() { // Don't double free. (I'm not sure if this exercises the // original problem code path anymore.) - let s = "".to_string(); + let s = String::from_str(""); let _bytes = s.as_bytes(); fail!(); } @@ -1578,10 +1583,10 @@ mod tests { #[test] fn vec_str_conversions() { - let s1: String = "All mimsy were the borogoves".to_string(); + let s1: String = String::from_str("All mimsy were the borogoves"); let v: Vec<u8> = Vec::from_slice(s1.as_bytes()); - let s2: String = from_utf8(v.as_slice()).unwrap().to_string(); + let s2: String = String::from_str(from_utf8(v.as_slice()).unwrap()); let mut i: uint = 0u; let n1: uint = s1.len(); let n2: uint = v.len(); @@ -1624,13 +1629,13 @@ mod tests { #[test] fn test_utf16() { let pairs = - [("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n".to_string(), + [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16, 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16, 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf30_u16, 0x000a_u16]), - ("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n".to_string(), + (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), vec![0xd801_u16, 0xdc12_u16, 0xd801_u16, 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16, 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16, @@ -1638,7 +1643,7 @@ mod tests { 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16, 0x000a_u16]), - ("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n".to_string(), + (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16, 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16, @@ -1647,7 +1652,7 @@ mod tests { 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]), - ("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n".to_string(), + (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"), vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16, 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16, 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16, @@ -1660,7 +1665,7 @@ mod tests { 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16, 0x000a_u16 ]), // Issue #12318, even-numbered non-BMP planes - ("\U00020000".to_string(), + (String::from_str("\U00020000"), vec![0xD840, 0xDC00])]; for p in pairs.iter() { @@ -1698,16 +1703,16 @@ mod tests { fn test_utf16_lossy() { // completely positive cases tested above. // lead + eof - assert_eq!(from_utf16_lossy([0xD800]), "\uFFFD".to_string()); + assert_eq!(from_utf16_lossy([0xD800]), String::from_str("\uFFFD")); // lead + lead - assert_eq!(from_utf16_lossy([0xD800, 0xD800]), "\uFFFD\uFFFD".to_string()); + assert_eq!(from_utf16_lossy([0xD800, 0xD800]), String::from_str("\uFFFD\uFFFD")); // isolated trail - assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), "a\uFFFD".to_string()); + assert_eq!(from_utf16_lossy([0x0061, 0xDC00]), String::from_str("a\uFFFD")); // general assert_eq!(from_utf16_lossy([0xD800, 0xd801, 0xdc8b, 0xD800]), - "\uFFFD𐒋\uFFFD".to_string()); + String::from_str("\uFFFD𐒋\uFFFD")); } #[test] @@ -1752,27 +1757,29 @@ mod tests { #[test] fn test_escape_unicode() { - assert_eq!("abc".escape_unicode(), "\\x61\\x62\\x63".to_string()); - assert_eq!("a c".escape_unicode(), "\\x61\\x20\\x63".to_string()); - assert_eq!("\r\n\t".escape_unicode(), "\\x0d\\x0a\\x09".to_string()); - assert_eq!("'\"\\".escape_unicode(), "\\x27\\x22\\x5c".to_string()); - assert_eq!("\x00\x01\xfe\xff".escape_unicode(), "\\x00\\x01\\xfe\\xff".to_string()); - assert_eq!("\u0100\uffff".escape_unicode(), "\\u0100\\uffff".to_string()); - assert_eq!("\U00010000\U0010ffff".escape_unicode(), "\\U00010000\\U0010ffff".to_string()); - assert_eq!("ab\ufb00".escape_unicode(), "\\x61\\x62\\ufb00".to_string()); - assert_eq!("\U0001d4ea\r".escape_unicode(), "\\U0001d4ea\\x0d".to_string()); + assert_eq!("abc".escape_unicode(), String::from_str("\\x61\\x62\\x63")); + assert_eq!("a c".escape_unicode(), String::from_str("\\x61\\x20\\x63")); + assert_eq!("\r\n\t".escape_unicode(), String::from_str("\\x0d\\x0a\\x09")); + assert_eq!("'\"\\".escape_unicode(), String::from_str("\\x27\\x22\\x5c")); + assert_eq!("\x00\x01\xfe\xff".escape_unicode(), String::from_str("\\x00\\x01\\xfe\\xff")); + assert_eq!("\u0100\uffff".escape_unicode(), String::from_str("\\u0100\\uffff")); + assert_eq!("\U00010000\U0010ffff".escape_unicode(), + String::from_str("\\U00010000\\U0010ffff")); + assert_eq!("ab\ufb00".escape_unicode(), String::from_str("\\x61\\x62\\ufb00")); + assert_eq!("\U0001d4ea\r".escape_unicode(), String::from_str("\\U0001d4ea\\x0d")); } #[test] fn test_escape_default() { - assert_eq!("abc".escape_default(), "abc".to_string()); - assert_eq!("a c".escape_default(), "a c".to_string()); - assert_eq!("\r\n\t".escape_default(), "\\r\\n\\t".to_string()); - assert_eq!("'\"\\".escape_default(), "\\'\\\"\\\\".to_string()); - assert_eq!("\u0100\uffff".escape_default(), "\\u0100\\uffff".to_string()); - assert_eq!("\U00010000\U0010ffff".escape_default(), "\\U00010000\\U0010ffff".to_string()); - assert_eq!("ab\ufb00".escape_default(), "ab\\ufb00".to_string()); - assert_eq!("\U0001d4ea\r".escape_default(), "\\U0001d4ea\\r".to_string()); + assert_eq!("abc".escape_default(), String::from_str("abc")); + assert_eq!("a c".escape_default(), String::from_str("a c")); + assert_eq!("\r\n\t".escape_default(), String::from_str("\\r\\n\\t")); + assert_eq!("'\"\\".escape_default(), String::from_str("\\'\\\"\\\\")); + assert_eq!("\u0100\uffff".escape_default(), String::from_str("\\u0100\\uffff")); + assert_eq!("\U00010000\U0010ffff".escape_default(), + String::from_str("\\U00010000\\U0010ffff")); + assert_eq!("ab\ufb00".escape_default(), String::from_str("ab\\ufb00")); + assert_eq!("\U0001d4ea\r".escape_default(), String::from_str("\\U0001d4ea\\r")); } #[test] @@ -2013,30 +2020,39 @@ mod tests { #[test] fn test_nfd_chars() { - assert_eq!("abc".nfd_chars().collect::<String>(), "abc".to_string()); - assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<String>(), "d\u0307\u01c4".to_string()); - assert_eq!("\u2026".nfd_chars().collect::<String>(), "\u2026".to_string()); - assert_eq!("\u2126".nfd_chars().collect::<String>(), "\u03a9".to_string()); - assert_eq!("\u1e0b\u0323".nfd_chars().collect::<String>(), "d\u0323\u0307".to_string()); - assert_eq!("\u1e0d\u0307".nfd_chars().collect::<String>(), "d\u0323\u0307".to_string()); - assert_eq!("a\u0301".nfd_chars().collect::<String>(), "a\u0301".to_string()); - assert_eq!("\u0301a".nfd_chars().collect::<String>(), "\u0301a".to_string()); - assert_eq!("\ud4db".nfd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_string()); - assert_eq!("\uac1c".nfd_chars().collect::<String>(), "\u1100\u1162".to_string()); + assert_eq!("abc".nfd_chars().collect::<String>(), String::from_str("abc")); + assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<String>(), + String::from_str("d\u0307\u01c4")); + assert_eq!("\u2026".nfd_chars().collect::<String>(), String::from_str("\u2026")); + assert_eq!("\u2126".nfd_chars().collect::<String>(), String::from_str("\u03a9")); + assert_eq!("\u1e0b\u0323".nfd_chars().collect::<String>(), + String::from_str("d\u0323\u0307")); + assert_eq!("\u1e0d\u0307".nfd_chars().collect::<String>(), + String::from_str("d\u0323\u0307")); + assert_eq!("a\u0301".nfd_chars().collect::<String>(), String::from_str("a\u0301")); + assert_eq!("\u0301a".nfd_chars().collect::<String>(), String::from_str("\u0301a")); + assert_eq!("\ud4db".nfd_chars().collect::<String>(), + String::from_str("\u1111\u1171\u11b6")); + assert_eq!("\uac1c".nfd_chars().collect::<String>(), String::from_str("\u1100\u1162")); } #[test] fn test_nfkd_chars() { - assert_eq!("abc".nfkd_chars().collect::<String>(), "abc".to_string()); - assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<String>(), "d\u0307DZ\u030c".to_string()); - assert_eq!("\u2026".nfkd_chars().collect::<String>(), "...".to_string()); - assert_eq!("\u2126".nfkd_chars().collect::<String>(), "\u03a9".to_string()); - assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_string()); - assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_string()); - assert_eq!("a\u0301".nfkd_chars().collect::<String>(), "a\u0301".to_string()); - assert_eq!("\u0301a".nfkd_chars().collect::<String>(), "\u0301a".to_string()); - assert_eq!("\ud4db".nfkd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_string()); - assert_eq!("\uac1c".nfkd_chars().collect::<String>(), "\u1100\u1162".to_string()); + assert_eq!("abc".nfkd_chars().collect::<String>(), String::from_str("abc")); + assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<String>(), + String::from_str("d\u0307DZ\u030c")); + assert_eq!("\u2026".nfkd_chars().collect::<String>(), String::from_str("...")); + assert_eq!("\u2126".nfkd_chars().collect::<String>(), String::from_str("\u03a9")); + assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<String>(), + String::from_str("d\u0323\u0307")); + assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<String>(), + String::from_str("d\u0323\u0307")); + assert_eq!("a\u0301".nfkd_chars().collect::<String>(), String::from_str("a\u0301")); + assert_eq!("\u0301a".nfkd_chars().collect::<String>(), + String::from_str("\u0301a")); + assert_eq!("\ud4db".nfkd_chars().collect::<String>(), +String::from_str("\u1111\u1171\u11b6")); + assert_eq!("\uac1c".nfkd_chars().collect::<String>(), String::from_str("\u1100\u1162")); } #[test] @@ -2090,10 +2106,10 @@ mod tests { v.iter().map(|x| x.len()).sum() } - let s = "01234".to_string(); + let s = String::from_str("01234"); assert_eq!(5, sum_len(["012", "", "34"])); - assert_eq!(5, sum_len(["01".to_string(), "2".to_string(), - "34".to_string(), "".to_string()])); + assert_eq!(5, sum_len([String::from_str("01"), String::from_str("2"), + String::from_str("34"), String::from_str("")])); assert_eq!(5, sum_len([s.as_slice()])); } @@ -2112,10 +2128,10 @@ mod tests { #[test] fn test_str_from_utf8_owned() { let xs = Vec::from_slice(b"hello"); - assert_eq!(from_utf8_owned(xs), Ok("hello".to_string())); + assert_eq!(from_utf8_owned(xs), Ok(String::from_str("hello"))); let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes()); - assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_string())); + assert_eq!(from_utf8_owned(xs), Ok(String::from_str("ศไทย中华Việt Nam"))); let xs = Vec::from_slice(b"hello\xFF"); assert_eq!(from_utf8_owned(xs), @@ -2131,34 +2147,30 @@ mod tests { assert_eq!(from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam")); let xs = b"Hello\xC2 There\xFF Goodbye"; - assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD There\uFFFD Goodbye".to_string())); + assert_eq!(from_utf8_lossy(xs), Owned(String::from_str("Hello\uFFFD There\uFFFD Goodbye"))); let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye"; - assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD\uFFFD There\uFFFD Goodbye".to_string())); + assert_eq!(from_utf8_lossy(xs), + Owned(String::from_str("Hello\uFFFD\uFFFD There\uFFFD Goodbye"))); let xs = b"\xF5foo\xF5\x80bar"; - assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFD\uFFFDbar".to_string())); + assert_eq!(from_utf8_lossy(xs), Owned(String::from_str("\uFFFDfoo\uFFFD\uFFFDbar"))); let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz"; - assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFDbaz".to_string())); + assert_eq!(from_utf8_lossy(xs), Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFDbaz"))); let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz"; - assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz".to_string())); + assert_eq!(from_utf8_lossy(xs), + Owned(String::from_str("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz"))); let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar"; - assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFD\uFFFD\ - foo\U00010000bar".to_string())); + assert_eq!(from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFD\uFFFD\ + foo\U00010000bar"))); // surrogates let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar"; - assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFDfoo\ - \uFFFD\uFFFD\uFFFDbar".to_string())); - } - - #[test] - fn test_from_str() { - let owned: Option<::std::string::String> = from_str("string"); - assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string")); + assert_eq!(from_utf8_lossy(xs), Owned(String::from_str("\uFFFD\uFFFD\uFFFDfoo\ + \uFFFD\uFFFD\uFFFDbar"))); } #[test] @@ -2166,18 +2178,18 @@ mod tests { let s = Slice("abcde"); assert_eq!(s.len(), 5); assert_eq!(s.as_slice(), "abcde"); - assert_eq!(s.to_str().as_slice(), "abcde"); + assert_eq!(String::from_str(s.as_slice()).as_slice(), "abcde"); assert_eq!(format!("{}", s).as_slice(), "abcde"); - assert!(s.lt(&Owned("bcdef".to_string()))); + assert!(s.lt(&Owned(String::from_str("bcdef")))); assert_eq!(Slice(""), Default::default()); - let o = Owned("abcde".to_string()); + let o = Owned(String::from_str("abcde")); assert_eq!(o.len(), 5); assert_eq!(o.as_slice(), "abcde"); - assert_eq!(o.to_str().as_slice(), "abcde"); + assert_eq!(String::from_str(o.as_slice()).as_slice(), "abcde"); assert_eq!(format!("{}", o).as_slice(), "abcde"); assert!(o.lt(&Slice("bcdef"))); - assert_eq!(Owned("".to_string()), Default::default()); + assert_eq!(Owned(String::from_str("")), Default::default()); assert!(s.cmp(&o) == Equal); assert!(s.equiv(&o)); @@ -2192,31 +2204,33 @@ mod tests { assert!(s.is_slice()); assert!(!s.is_owned()); - let o = Owned("abcde".to_string()); + let o = Owned(String::from_str("abcde")); assert!(!o.is_slice()); assert!(o.is_owned()); } #[test] fn test_maybe_owned_clone() { - assert_eq!(Owned("abcde".to_string()), Slice("abcde").clone()); - assert_eq!(Owned("abcde".to_string()), Owned("abcde".to_string()).clone()); + assert_eq!(Owned(String::from_str("abcde")), Slice("abcde").clone()); + assert_eq!(Owned(String::from_str("abcde")), Owned(String::from_str("abcde")).clone()); assert_eq!(Slice("abcde"), Slice("abcde").clone()); - assert_eq!(Slice("abcde"), Owned("abcde".to_string()).clone()); + assert_eq!(Slice("abcde"), Owned(String::from_str("abcde")).clone()); } #[test] fn test_maybe_owned_into_string() { - assert_eq!(Slice("abcde").into_string(), "abcde".to_string()); - assert_eq!(Owned("abcde".to_string()).into_string(), "abcde".to_string()); + assert_eq!(Slice("abcde").into_string(), String::from_str("abcde")); + assert_eq!(Owned(String::from_str("abcde")).into_string(), + String::from_str("abcde")); } #[test] fn test_into_maybe_owned() { assert_eq!("abcde".into_maybe_owned(), Slice("abcde")); - assert_eq!(("abcde".to_string()).into_maybe_owned(), Slice("abcde")); - assert_eq!("abcde".into_maybe_owned(), Owned("abcde".to_string())); - assert_eq!(("abcde".to_string()).into_maybe_owned(), Owned("abcde".to_string())); + assert_eq!((String::from_str("abcde")).into_maybe_owned(), Slice("abcde")); + assert_eq!("abcde".into_maybe_owned(), Owned(String::from_str("abcde"))); + assert_eq!((String::from_str("abcde")).into_maybe_owned(), + Owned(String::from_str("abcde"))); } } @@ -2224,7 +2238,10 @@ mod tests { mod bench { use test::Bencher; use super::*; - use std::prelude::*; + use vec::Vec; + use std::iter::{Iterator, DoubleEndedIterator}; + use std::collections::Collection; + use std::slice::Vector; #[bench] fn char_iterator(b: &mut Bencher) { diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index e1467d957d7..74b9465f2a5 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -354,7 +354,7 @@ impl<'a, S: Str> Equiv<S> for String { impl<S: Str> Add<S, String> for String { fn add(&self, other: &S) -> String { - let mut s = self.to_string(); + let mut s = String::from_str(self.as_slice()); s.push_str(other.as_slice()); return s; } @@ -369,6 +369,12 @@ mod tests { use str::{Str, StrSlice}; use super::String; + #[test] + fn test_from_str() { + let owned: Option<::std::string::String> = from_str("string"); + assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string")); + } + #[bench] fn bench_with_capacity(b: &mut Bencher) { b.iter(|| { diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs index becceffe6d0..c1d782991b4 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/treemap.rs @@ -185,7 +185,7 @@ impl<K: Ord, V> TreeMap<K, V> { macro_rules! bound_setup { // initialiser of the iterator to manipulate - ($iter:expr, + ($iter:expr, $k:expr, // whether we are looking for the lower or upper bound. $is_lower_bound:expr) => { { @@ -193,7 +193,7 @@ macro_rules! bound_setup { loop { if !iter.node.is_null() { let node_k = unsafe {&(*iter.node).key}; - match k.cmp(node_k) { + match $k.cmp(node_k) { Less => iter.traverse_left(), Greater => iter.traverse_right(), Equal => { @@ -230,13 +230,13 @@ impl<K: Ord, V> TreeMap<K, V> { /// Return a lazy iterator to the first key-value pair whose key is not less than `k` /// If all keys in map are less than `k` an empty iterator is returned. pub fn lower_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> { - bound_setup!(self.iter_for_traversal(), true) + bound_setup!(self.iter_for_traversal(), k, true) } /// Return a lazy iterator to the first key-value pair whose key is greater than `k` /// If all keys in map are not greater than `k` an empty iterator is returned. pub fn upper_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> { - bound_setup!(self.iter_for_traversal(), false) + bound_setup!(self.iter_for_traversal(), k, false) } /// Get a lazy iterator that should be initialized using @@ -256,7 +256,7 @@ impl<K: Ord, V> TreeMap<K, V> { /// If all keys in map are less than `k` an empty iterator is /// returned. pub fn mut_lower_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> { - bound_setup!(self.mut_iter_for_traversal(), true) + bound_setup!(self.mut_iter_for_traversal(), k, true) } /// Return a lazy iterator to the first key-value pair (with the @@ -265,7 +265,7 @@ impl<K: Ord, V> TreeMap<K, V> { /// If all keys in map are not greater than `k` an empty iterator /// is returned. pub fn mut_upper_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> { - bound_setup!(self.mut_iter_for_traversal(), false) + bound_setup!(self.mut_iter_for_traversal(), k, false) } } diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index f326195be16..ef5b51fd00b 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -70,7 +70,7 @@ static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u; /** * Converts a number to its string representation as a byte vector. * This is meant to be a common base implementation for all numeric string - * conversion functions like `to_str()` or `to_str_radix()`. + * conversion functions like `to_string()` or `to_str_radix()`. * * # Arguments * - `num` - The number to convert. Accepts any number that diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 1fae362471d..3230873883e 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -769,16 +769,16 @@ pub trait ToPrimitive { } macro_rules! impl_to_primitive_int_to_int( - ($SrcT:ty, $DstT:ty) => ( + ($SrcT:ty, $DstT:ty, $slf:expr) => ( { if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some(*self as $DstT) + Some($slf as $DstT) } else { - let n = *self as i64; + let n = $slf as i64; let min_value: $DstT = Bounded::min_value(); let max_value: $DstT = Bounded::max_value(); if min_value as i64 <= n && n <= max_value as i64 { - Some(*self as $DstT) + Some($slf as $DstT) } else { None } @@ -788,12 +788,12 @@ macro_rules! impl_to_primitive_int_to_int( ) macro_rules! impl_to_primitive_int_to_uint( - ($SrcT:ty, $DstT:ty) => ( + ($SrcT:ty, $DstT:ty, $slf:expr) => ( { let zero: $SrcT = Zero::zero(); let max_value: $DstT = Bounded::max_value(); - if zero <= *self && *self as u64 <= max_value as u64 { - Some(*self as $DstT) + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) } else { None } @@ -805,26 +805,26 @@ macro_rules! impl_to_primitive_int( ($T:ty) => ( impl ToPrimitive for $T { #[inline] - fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int) } + fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) } #[inline] - fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8) } + fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) } #[inline] - fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16) } + fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) } #[inline] - fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32) } + fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) } #[inline] - fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64) } + fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) } #[inline] - fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint) } + fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) } #[inline] - fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8) } + fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) } #[inline] - fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16) } + fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) } #[inline] - fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32) } + fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) } #[inline] - fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64) } + fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) } #[inline] fn to_f32(&self) -> Option<f32> { Some(*self as f32) } @@ -841,11 +841,11 @@ impl_to_primitive_int!(i32) impl_to_primitive_int!(i64) macro_rules! impl_to_primitive_uint_to_int( - ($DstT:ty) => ( + ($DstT:ty, $slf:expr) => ( { let max_value: $DstT = Bounded::max_value(); - if *self as u64 <= max_value as u64 { - Some(*self as $DstT) + if $slf as u64 <= max_value as u64 { + Some($slf as $DstT) } else { None } @@ -854,15 +854,15 @@ macro_rules! impl_to_primitive_uint_to_int( ) macro_rules! impl_to_primitive_uint_to_uint( - ($SrcT:ty, $DstT:ty) => ( + ($SrcT:ty, $DstT:ty, $slf:expr) => ( { if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some(*self as $DstT) + Some($slf as $DstT) } else { let zero: $SrcT = Zero::zero(); let max_value: $DstT = Bounded::max_value(); - if zero <= *self && *self as u64 <= max_value as u64 { - Some(*self as $DstT) + if zero <= $slf && $slf as u64 <= max_value as u64 { + Some($slf as $DstT) } else { None } @@ -875,26 +875,26 @@ macro_rules! impl_to_primitive_uint( ($T:ty) => ( impl ToPrimitive for $T { #[inline] - fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int) } + fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) } #[inline] - fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8) } + fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) } #[inline] - fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16) } + fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) } #[inline] - fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32) } + fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) } #[inline] - fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64) } + fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) } #[inline] - fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint) } + fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) } #[inline] - fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8) } + fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) } #[inline] - fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16) } + fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) } #[inline] - fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32) } + fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) } #[inline] - fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64) } + fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) } #[inline] fn to_f32(&self) -> Option<f32> { Some(*self as f32) } @@ -911,14 +911,14 @@ impl_to_primitive_uint!(u32) impl_to_primitive_uint!(u64) macro_rules! impl_to_primitive_float_to_float( - ($SrcT:ty, $DstT:ty) => ( + ($SrcT:ty, $DstT:ty, $slf:expr) => ( if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some(*self as $DstT) + Some($slf as $DstT) } else { - let n = *self as f64; + let n = $slf as f64; let max_value: $SrcT = Bounded::max_value(); if -max_value as f64 <= n && n <= max_value as f64 { - Some(*self as $DstT) + Some($slf as $DstT) } else { None } @@ -952,9 +952,9 @@ macro_rules! impl_to_primitive_float( fn to_u64(&self) -> Option<u64> { Some(*self as u64) } #[inline] - fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32) } + fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) } #[inline] - fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64) } + fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) } } ) ) @@ -1104,38 +1104,38 @@ pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> { } macro_rules! impl_from_primitive( - ($T:ty, $to_ty:expr) => ( + ($T:ty, $to_ty:ident) => ( impl FromPrimitive for $T { - #[inline] fn from_int(n: int) -> Option<$T> { $to_ty } - #[inline] fn from_i8(n: i8) -> Option<$T> { $to_ty } - #[inline] fn from_i16(n: i16) -> Option<$T> { $to_ty } - #[inline] fn from_i32(n: i32) -> Option<$T> { $to_ty } - #[inline] fn from_i64(n: i64) -> Option<$T> { $to_ty } - - #[inline] fn from_uint(n: uint) -> Option<$T> { $to_ty } - #[inline] fn from_u8(n: u8) -> Option<$T> { $to_ty } - #[inline] fn from_u16(n: u16) -> Option<$T> { $to_ty } - #[inline] fn from_u32(n: u32) -> Option<$T> { $to_ty } - #[inline] fn from_u64(n: u64) -> Option<$T> { $to_ty } - - #[inline] fn from_f32(n: f32) -> Option<$T> { $to_ty } - #[inline] fn from_f64(n: f64) -> Option<$T> { $to_ty } + #[inline] fn from_int(n: int) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_uint(n: uint) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } } ) ) -impl_from_primitive!(int, n.to_int()) -impl_from_primitive!(i8, n.to_i8()) -impl_from_primitive!(i16, n.to_i16()) -impl_from_primitive!(i32, n.to_i32()) -impl_from_primitive!(i64, n.to_i64()) -impl_from_primitive!(uint, n.to_uint()) -impl_from_primitive!(u8, n.to_u8()) -impl_from_primitive!(u16, n.to_u16()) -impl_from_primitive!(u32, n.to_u32()) -impl_from_primitive!(u64, n.to_u64()) -impl_from_primitive!(f32, n.to_f32()) -impl_from_primitive!(f64, n.to_f64()) +impl_from_primitive!(int, to_int) +impl_from_primitive!(i8, to_i8) +impl_from_primitive!(i16, to_i16) +impl_from_primitive!(i32, to_i32) +impl_from_primitive!(i64, to_i64) +impl_from_primitive!(uint, to_uint) +impl_from_primitive!(u8, to_u8) +impl_from_primitive!(u16, to_u16) +impl_from_primitive!(u32, to_u32) +impl_from_primitive!(u64, to_u64) +impl_from_primitive!(f32, to_f32) +impl_from_primitive!(f64, to_f64) /// Cast from one machine scalar to another. /// diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 94df7a5a6c2..f94d5a5e4b5 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -1764,7 +1764,9 @@ impl<'a> StrSlice<'a> for &'a str { #[inline] fn slice(&self, begin: uint, end: uint) -> &'a str { - assert!(self.is_char_boundary(begin) && self.is_char_boundary(end)); + assert!(self.is_char_boundary(begin) && self.is_char_boundary(end), + "index {} and/or {} in `{}` do not lie on character boundary", begin, + end, *self); unsafe { raw::slice_bytes(*self, begin, end) } } @@ -1775,7 +1777,8 @@ impl<'a> StrSlice<'a> for &'a str { #[inline] fn slice_to(&self, end: uint) -> &'a str { - assert!(self.is_char_boundary(end)); + assert!(self.is_char_boundary(end), "index {} in `{}` does not lie on \ + a character boundary", end, *self); unsafe { raw::slice_bytes(*self, 0, end) } } diff --git a/src/libcoretest/char.rs b/src/libcoretest/char.rs index 852edd90b0f..5393c207344 100644 --- a/src/libcoretest/char.rs +++ b/src/libcoretest/char.rs @@ -168,12 +168,6 @@ fn test_escape_unicode() { } #[test] -fn test_to_str() { - let s = 't'.to_str(); - assert_eq!(s.as_slice(), "t"); -} - -#[test] fn test_encode_utf8() { fn check(input: char, expect: &[u8]) { let mut buf = [0u8, ..4]; diff --git a/src/libdebug/fmt.rs b/src/libdebug/fmt.rs index 4087cb95271..0b04a07ea88 100644 --- a/src/libdebug/fmt.rs +++ b/src/libdebug/fmt.rs @@ -45,7 +45,7 @@ impl<T> Poly for T { // If we have a specified width for formatting, then we have to make // this allocation of a new string _ => { - let s = repr::repr_to_str(self); + let s = repr::repr_to_string(self); f.pad(s.as_slice()) } } diff --git a/src/libdebug/repr.rs b/src/libdebug/repr.rs index 133353ec3d7..3e541929dbf 100644 --- a/src/libdebug/repr.rs +++ b/src/libdebug/repr.rs @@ -73,7 +73,7 @@ int_repr!(u64, "u64") macro_rules! num_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty { fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> { - let s = self.to_str(); + let s = self.to_string(); writer.write(s.as_bytes()).and_then(|()| { writer.write($suffix) }) @@ -564,7 +564,7 @@ pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> { } } -pub fn repr_to_str<T>(t: &T) -> String { +pub fn repr_to_string<T>(t: &T) -> String { let mut result = io::MemWriter::new(); write_repr(&mut result as &mut io::Writer, t).unwrap(); String::from_utf8(result.unwrap()).unwrap() diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 790df13c1ff..bb3e90958f1 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -59,7 +59,7 @@ //! ]; //! let matches = match getopts(args.tail(), opts) { //! Ok(m) => { m } -//! Err(f) => { fail!(f.to_str()) } +//! Err(f) => { fail!(f.to_string()) } //! }; //! if matches.opt_present("h") { //! print_usage(program.as_slice(), opts); @@ -222,9 +222,9 @@ impl Name { } } - fn to_str(&self) -> String { + fn to_string(&self) -> String { match *self { - Short(ch) => ch.to_str(), + Short(ch) => ch.to_string(), Long(ref s) => s.to_string() } } @@ -501,7 +501,7 @@ impl Fail_ { /// Convert a `Fail_` enum into an error string. #[deprecated="use `Show` (`{}` format specifier)"] pub fn to_err_msg(self) -> String { - self.to_str() + self.to_string() } } @@ -609,12 +609,12 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { name_pos += 1; let optid = match find_opt(opts.as_slice(), (*nm).clone()) { Some(id) => id, - None => return Err(UnrecognizedOption(nm.to_str())) + None => return Err(UnrecognizedOption(nm.to_string())) }; match opts.get(optid).hasarg { No => { if !i_arg.is_none() { - return Err(UnexpectedArgument(nm.to_str())); + return Err(UnexpectedArgument(nm.to_string())); } vals.get_mut(optid).push(Given); } @@ -635,7 +635,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { if !i_arg.is_none() { vals.get_mut(optid).push(Val(i_arg.clone().unwrap())); } else if i + 1 == l { - return Err(ArgumentMissing(nm.to_str())); + return Err(ArgumentMissing(nm.to_string())); } else { i += 1; vals.get_mut(optid).push(Val(args[i].clone())); @@ -652,12 +652,12 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let occ = opts.get(i).occur; if occ == Req { if n == 0 { - return Err(OptionMissing(opts.get(i).name.to_str())); + return Err(OptionMissing(opts.get(i).name.to_string())); } } if occ != Multi { if n > 1 { - return Err(OptionDuplicated(opts.get(i).name.to_str())); + return Err(OptionDuplicated(opts.get(i).name.to_string())); } } i += 1; diff --git a/src/libglob/lib.rs b/src/libglob/lib.rs index 6aa48dc748e..668000b2db4 100644 --- a/src/libglob/lib.rs +++ b/src/libglob/lib.rs @@ -703,11 +703,11 @@ mod test { for &p in pats.iter() { let pat = Pattern::new(p); for c in "abcdefghijklmnopqrstuvwxyz".chars() { - assert!(pat.matches(c.to_str().as_slice())); + assert!(pat.matches(c.to_string().as_slice())); } for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() { let options = MatchOptions {case_sensitive: false, .. MatchOptions::new()}; - assert!(pat.matches_with(c.to_str().as_slice(), options)); + assert!(pat.matches_with(c.to_string().as_slice(), options)); } assert!(pat.matches("1")); assert!(pat.matches("2")); diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 52990bae554..662722e08d9 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -666,7 +666,7 @@ mod tests { let mut writer = MemWriter::new(); render(&g, &mut writer).unwrap(); let mut r = BufReader::new(writer.get_ref()); - match r.read_to_str() { + match r.read_to_string() { Ok(string) => Ok(string.to_string()), Err(err) => Err(err), } @@ -768,7 +768,7 @@ r#"digraph hasse_diagram { render(&g, &mut writer).unwrap(); let mut r = BufReader::new(writer.get_ref()); - let r = r.read_to_str(); + let r = r.read_to_string(); assert_eq!(r.unwrap().as_slice(), r#"digraph syntax_tree { diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index 98553603313..dbca4ff7ff7 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -259,7 +259,7 @@ pub fn to_utf16(s: &CString) -> IoResult<Vec<u16>> { None => Err(IoError { code: libc::ERROR_INVALID_NAME as uint, extra: 0, - detail: Some("valid unicode input required".to_str()), + detail: Some("valid unicode input required".to_string()), }) } } diff --git a/src/libnative/io/pipe_unix.rs b/src/libnative/io/pipe_unix.rs index b5b2065f996..0e019fa7e8f 100644 --- a/src/libnative/io/pipe_unix.rs +++ b/src/libnative/io/pipe_unix.rs @@ -43,7 +43,7 @@ fn addr_to_sockaddr_un(addr: &CString) -> IoResult<(libc::sockaddr_storage, uint return Err(IoError { code: ERROR as uint, extra: 0, - detail: Some("path must be smaller than SUN_LEN".to_str()), + detail: Some("path must be smaller than SUN_LEN".to_string()), }) } s.sun_family = libc::AF_UNIX as libc::sa_family_t; diff --git a/src/libnative/io/pipe_win32.rs b/src/libnative/io/pipe_win32.rs index e5e8cdeffd7..ec40ff89bd2 100644 --- a/src/libnative/io/pipe_win32.rs +++ b/src/libnative/io/pipe_win32.rs @@ -479,7 +479,7 @@ impl rtio::RtioPipe for UnixStream { Err(IoError { code: libc::ERROR_OPERATION_ABORTED as uint, extra: amt, - detail: Some("short write during write".to_str()), + detail: Some("short write during write".to_string()), }) } else { Err(util::timeout("write timed out")) diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index 6fab73115cf..71702d180b9 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -170,7 +170,7 @@ impl rtio::RtioProcess for Process { Some(..) => return Err(IoError { code: ERROR as uint, extra: 0, - detail: Some("can't kill an exited process".to_str()), + detail: Some("can't kill an exited process".to_string()), }), None => {} } @@ -301,7 +301,7 @@ fn spawn_process_os(cfg: ProcessConfig, return Err(IoError { code: libc::ERROR_CALL_NOT_IMPLEMENTED as uint, extra: 0, - detail: Some("unsupported gid/uid requested on windows".to_str()), + detail: Some("unsupported gid/uid requested on windows".to_string()), }) } diff --git a/src/libnative/io/util.rs b/src/libnative/io/util.rs index 31ba2223082..06046cc74cf 100644 --- a/src/libnative/io/util.rs +++ b/src/libnative/io/util.rs @@ -30,7 +30,7 @@ pub fn timeout(desc: &'static str) -> IoError { IoError { code: ERROR as uint, extra: 0, - detail: Some(desc.to_str()), + detail: Some(desc.to_string()), } } @@ -40,7 +40,7 @@ pub fn short_write(n: uint, desc: &'static str) -> IoError { IoError { code: ERROR as uint, extra: n, - detail: Some(desc.to_str()), + detail: Some(desc.to_string()), } } diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index cc3753def59..046ba96f45a 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -2737,7 +2737,7 @@ mod bigint_tests { // attempt to allocate a vector of size (-1u) == huge. let x: BigInt = from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap(); - let _y = x.to_str(); + let _y = x.to_string(); } #[test] @@ -2842,14 +2842,14 @@ mod bench { } #[bench] - fn to_str(b: &mut Bencher) { + fn to_string(b: &mut Bencher) { let fac = factorial(100); let fib = fib(100); b.iter(|| { - fac.to_str(); + fac.to_string(); }); b.iter(|| { - fib.to_str(); + fib.to_string(); }); } diff --git a/src/libnum/complex.rs b/src/libnum/complex.rs index 9ee80d283cf..f4a3ac97a4e 100644 --- a/src/libnum/complex.rs +++ b/src/libnum/complex.rs @@ -347,9 +347,9 @@ mod test { } #[test] - fn test_to_str() { + fn test_to_string() { fn test(c : Complex64, s: String) { - assert_eq!(c.to_str(), s); + assert_eq!(c.to_string(), s); } test(_0_0i, "0+0i".to_string()); test(_1_0i, "1+0i".to_string()); diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index 1792f282eca..a279ede6fa5 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -17,6 +17,7 @@ use std::fmt; use std::from_str::FromStr; use std::num; use std::num::{Zero, One, ToStrRadix, FromStrRadix}; + use bigint::{BigInt, BigUint, Sign, Plus, Minus}; /// Represents the ratio between 2 numbers. @@ -603,7 +604,7 @@ mod test { fn test_to_from_str() { fn test(r: Rational, s: String) { assert_eq!(FromStr::from_str(s.as_slice()), Some(r)); - assert_eq!(r.to_str(), s); + assert_eq!(r.to_string(), s); } test(_1, "1".to_string()); test(_0, "0".to_string()); diff --git a/src/libregex_macros/lib.rs b/src/libregex_macros/lib.rs index c15b232d8e1..95ed334c5d4 100644 --- a/src/libregex_macros/lib.rs +++ b/src/libregex_macros/lib.rs @@ -87,7 +87,7 @@ fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) let re = match Regex::new(regex.as_slice()) { Ok(re) => re, Err(err) => { - cx.span_err(sp, err.to_str().as_slice()); + cx.span_err(sp, err.to_string().as_slice()); return DummyResult::any(sp) } }; @@ -621,11 +621,11 @@ fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<String> { let regex = match entry.node { ast::ExprLit(lit) => { match lit.node { - ast::LitStr(ref s, _) => s.to_str(), + ast::LitStr(ref s, _) => s.to_string(), _ => { cx.span_err(entry.span, format!( "expected string literal but got `{}`", - pprust::lit_to_str(lit)).as_slice()); + pprust::lit_to_string(lit)).as_slice()); return None } } @@ -633,7 +633,7 @@ fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<String> { _ => { cx.span_err(entry.span, format!( "expected string literal but got `{}`", - pprust::expr_to_str(entry)).as_slice()); + pprust::expr_to_string(entry)).as_slice()); return None } }; diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index f1856850701..e2264088b4a 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -773,7 +773,7 @@ pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems, pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext, t: ty::t, name: &str) -> String { - let s = ppaux::ty_to_str(ccx.tcx(), t); + let s = ppaux::ty_to_string(ccx.tcx(), t); let path = [PathName(token::intern(s.as_slice())), gensym_name(name)]; let hash = get_symbol_hash(ccx, t); @@ -1363,7 +1363,7 @@ fn link_args(cmd: &mut Command, if sess.targ_cfg.os == abi::OsMacos { cmd.args(["-dynamiclib", "-Wl,-dylib"]); - if !sess.opts.cg.no_rpath { + if sess.opts.cg.rpath { let mut v = Vec::from_slice("-Wl,-install_name,@rpath/".as_bytes()); v.push_all(out_filename.filename().unwrap()); cmd.arg(v.as_slice()); @@ -1382,7 +1382,7 @@ fn link_args(cmd: &mut Command, // FIXME (#2397): At some point we want to rpath our guesses as to // where extern libraries might live, based on the // addl_lib_search_paths - if !sess.opts.cg.no_rpath { + if sess.opts.cg.rpath { cmd.args(rpath::get_rpath_flags(sess, out_filename).as_slice()); } diff --git a/src/librustc/back/svh.rs b/src/librustc/back/svh.rs index 24b9ff970aa..324ed3b567e 100644 --- a/src/librustc/back/svh.rs +++ b/src/librustc/back/svh.rs @@ -340,13 +340,13 @@ mod svh_visitor { // trees might be faster. Implementing this is far // easier in short term. let macro_defn_as_string = - pprust::to_str(|pp_state| pp_state.print_mac(macro)); + pprust::to_string(|pp_state| pp_state.print_mac(macro)); macro_defn_as_string.hash(self.st); } else { // It is not possible to observe any kind of macro // invocation at this stage except `macro_rules!`. fail!("reached macro somehow: {}", - pprust::to_str(|pp_state| pp_state.print_mac(macro))); + pprust::to_string(|pp_state| pp_state.print_mac(macro))); } visit::walk_mac(self, macro, e); diff --git a/src/librustc/driver/config.rs b/src/librustc/driver/config.rs index e91dfd9587b..9daaa2792eb 100644 --- a/src/librustc/driver/config.rs +++ b/src/librustc/driver/config.rs @@ -306,8 +306,8 @@ cgoptions!( "a list of arguments to pass to llvm (space separated)"), save_temps: bool = (false, parse_bool, "save all temporary output files during compilation"), - no_rpath: bool = (false, parse_bool, - "disables setting the rpath in libs/exes"), + rpath: bool = (false, parse_bool, + "set rpath values in libs/exes"), no_prepopulate_passes: bool = (false, parse_bool, "don't pre-populate the pass manager with a list of passes"), no_vectorize_loops: bool = (false, parse_bool, diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 7e34ff2dbbd..6a016edcd28 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -594,7 +594,7 @@ impl pprust::PpAnn for IdentifiedAnnotation { match node { pprust::NodeItem(item) => { try!(pp::space(&mut s.s)); - s.synth_comment(item.id.to_str()) + s.synth_comment(item.id.to_string()) } pprust::NodeBlock(blk) => { try!(pp::space(&mut s.s)); @@ -602,7 +602,7 @@ impl pprust::PpAnn for IdentifiedAnnotation { } pprust::NodeExpr(expr) => { try!(pp::space(&mut s.s)); - try!(s.synth_comment(expr.id.to_str())); + try!(s.synth_comment(expr.id.to_string())); s.pclose() } pprust::NodePat(pat) => { @@ -636,7 +636,7 @@ impl pprust::PpAnn for TypedAnnotation { try!(pp::word(&mut s.s, "as")); try!(pp::space(&mut s.s)); try!(pp::word(&mut s.s, - ppaux::ty_to_str( + ppaux::ty_to_string( tcx, ty::expr_ty(tcx, expr)).as_slice())); s.pclose() diff --git a/src/librustc/driver/mod.rs b/src/librustc/driver/mod.rs index 807c2590566..ad0d8cac1e3 100644 --- a/src/librustc/driver/mod.rs +++ b/src/librustc/driver/mod.rs @@ -251,7 +251,7 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> { match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) { Ok(m) => m, Err(f) => { - early_error(f.to_str().as_slice()); + early_error(f.to_string().as_slice()); } }; @@ -450,7 +450,7 @@ fn monitor(f: proc():Send) { emitter.emit(None, note.as_slice(), diagnostic::Note) } - match r.read_to_str() { + match r.read_to_string() { Ok(s) => println!("{}", s), Err(e) => { emitter.emit(None, diff --git a/src/librustc/front/config.rs b/src/librustc/front/config.rs index 2fa0ab9072c..9bff6620aaa 100644 --- a/src/librustc/front/config.rs +++ b/src/librustc/front/config.rs @@ -109,12 +109,12 @@ fn fold_item_underscore(cx: &mut Context, item: &ast::Item_) -> ast::Item_ { .map(|x| *x).collect(); ast::ItemImpl((*a).clone(), (*b).clone(), c, methods) } - ast::ItemTrait(ref a, b, ref c, ref methods) => { + ast::ItemTrait(ref a, ref b, ref c, ref methods) => { let methods = methods.iter() .filter(|m| trait_method_in_cfg(cx, *m) ) .map(|x| (*x).clone()) .collect(); - ast::ItemTrait((*a).clone(), b, (*c).clone(), methods) + ast::ItemTrait((*a).clone(), (*b).clone(), (*c).clone(), methods) } ast::ItemStruct(ref def, ref generics) => { ast::ItemStruct(fold_struct(cx, &**def), generics.clone()) diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index b2c6840ad22..0860d111a9e 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -347,7 +347,7 @@ fn mk_test_module(cx: &TestCtxt) -> Gc<ast::Item> { span: DUMMY_SP, }; - debug!("Synthetic test module:\n{}\n", pprust::item_to_str(&item)); + debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); box(GC) item } diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index d07e74493be..a4425183cde 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -1883,7 +1883,7 @@ impl TypeNames { self.named_types.borrow().find_equiv(&s).map(|x| Type::from_ref(*x)) } - pub fn type_to_str(&self, ty: Type) -> String { + pub fn type_to_string(&self, ty: Type) -> String { unsafe { let s = llvm::LLVMTypeToString(ty.to_ref()); let ret = from_c_str(s); @@ -1893,11 +1893,11 @@ impl TypeNames { } pub fn types_to_str(&self, tys: &[Type]) -> String { - let strs: Vec<String> = tys.iter().map(|t| self.type_to_str(*t)).collect(); + let strs: Vec<String> = tys.iter().map(|t| self.type_to_string(*t)).collect(); format!("[{}]", strs.connect(",")) } - pub fn val_to_str(&self, val: ValueRef) -> String { + pub fn val_to_string(&self, val: ValueRef) -> String { unsafe { let s = llvm::LLVMValueToString(val); let ret = from_c_str(s); diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 7b8026e32e0..ae401b9d6f1 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -31,7 +31,7 @@ use middle::trans::adt; // for `adt::is_ffi_safe` use middle::typeck::astconv::ast_ty_to_ty; use middle::typeck::infer; use middle::{typeck, ty, def, pat_util, stability}; -use util::ppaux::{ty_to_str}; +use util::ppaux::{ty_to_string}; use util::nodemap::NodeSet; use lint::{Context, LintPass, LintArray}; @@ -412,14 +412,14 @@ impl HeapMemory { }); if n_uniq > 0 { - let s = ty_to_str(cx.tcx, ty); + let s = ty_to_string(cx.tcx, ty); let m = format!("type uses owned (Box type) pointers: {}", s); cx.span_lint(OWNED_HEAP_MEMORY, span, m.as_slice()); cx.span_lint(HEAP_MEMORY, span, m.as_slice()); } if n_box > 0 { - let s = ty_to_str(cx.tcx, ty); + let s = ty_to_string(cx.tcx, ty); let m = format!("type uses managed (@ type) pointers: {}", s); cx.span_lint(MANAGED_HEAP_MEMORY, span, m.as_slice()); cx.span_lint(HEAP_MEMORY, span, m.as_slice()); @@ -1114,7 +1114,7 @@ impl UnusedMut { match mode { ast::BindByValue(ast::MutMutable) => { if !token::get_ident(ident).get().starts_with("_") { - mutables.insert_or_update_with(ident.name as uint, + mutables.insert_or_update_with(ident.name.uint(), vec!(id), |_, old| { old.push(id); }); } } diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 79fbd73c23d..61aaf068c10 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -666,7 +666,7 @@ pub fn check_crate(tcx: &ty::ctxt, for &(lint, span, ref msg) in v.iter() { tcx.sess.span_bug(span, format!("unprocessed lint {} at {}: {}", - lint.as_str(), tcx.map.node_to_str(*id), *msg).as_slice()) + lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice()) } } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 29566fb1e7c..edf46c214ba 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -148,12 +148,12 @@ fn extract_crate_info(e: &Env, i: &ast::ViewItem) -> Option<CrateInfo> { ident, path_opt); let name = match *path_opt { Some((ref path_str, _)) => { - let name = path_str.get().to_str(); + let name = path_str.get().to_string(); validate_crate_name(Some(e.sess), name.as_slice(), Some(i.span)); name } - None => ident.get().to_str(), + None => ident.get().to_string(), }; Some(CrateInfo { ident: ident.get().to_string(), diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index f88c0d34ed8..cc41223688e 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -164,19 +164,6 @@ fn item_visibility(item: ebml::Doc) -> ast::Visibility { } } -fn item_sized(item: ebml::Doc) -> ast::Sized { - match reader::maybe_get_doc(item, tag_items_data_item_sized) { - None => ast::StaticSize, - Some(sized_doc) => { - match reader::doc_as_u8(sized_doc) as char { - 'd' => ast::DynSize, - 's' => ast::StaticSize, - _ => fail!("unknown sized-ness character") - } - } - } -} - fn item_method_sort(item: ebml::Doc) -> char { let mut ret = 'r'; reader::tagged_docs(item, tag_item_trait_method_sort, |doc| { @@ -336,7 +323,7 @@ fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident { let string = name.as_str_slice(); match intr.find_equiv(&string) { None => token::str_to_ident(string), - Some(val) => ast::Ident::new(val as ast::Name), + Some(val) => ast::Ident::new(val), } } @@ -393,7 +380,6 @@ pub fn get_trait_def(cdata: Cmd, let tp_defs = item_ty_param_defs(item_doc, tcx, cdata, tag_items_data_item_ty_param_bounds); let rp_defs = item_region_param_defs(item_doc, cdata); - let sized = item_sized(item_doc); let mut bounds = ty::empty_builtin_bounds(); // Collect the builtin bounds from the encoded supertraits. // FIXME(#8559): They should be encoded directly. @@ -405,12 +391,6 @@ pub fn get_trait_def(cdata: Cmd, }); true }); - // Turn sized into a bound, FIXME(#8559). - if sized == ast::StaticSize { - tcx.lang_items.to_builtin_kind(tcx.lang_items.sized_trait().unwrap()).map(|bound| { - bounds.add(bound); - }); - } ty::TraitDef { generics: ty::Generics {types: tp_defs, @@ -759,10 +739,11 @@ fn get_explicit_self(item: ebml::Doc) -> ast::ExplicitSelf_ { let explicit_self_kind = string.as_bytes()[0]; match explicit_self_kind as char { 's' => ast::SelfStatic, - 'v' => ast::SelfValue, - '~' => ast::SelfUniq, + 'v' => ast::SelfValue(special_idents::self_), + '~' => ast::SelfUniq(special_idents::self_), // FIXME(#4846) expl. region - '&' => ast::SelfRegion(None, get_mutability(string.as_bytes()[1])), + '&' => ast::SelfRegion(None, get_mutability(string.as_bytes()[1]), + special_idents::self_), _ => fail!("unknown self type code: `{}`", explicit_self_kind as char) } } @@ -1087,7 +1068,7 @@ fn list_crate_attributes(md: ebml::Doc, hash: &Svh, let r = get_attributes(md); for attr in r.iter() { - try!(write!(out, "{}\n", pprust::attribute_to_str(attr))); + try!(write!(out, "{}\n", pprust::attribute_to_string(attr))); } write!(out, "\n\n") diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 21713672f81..fbf0288418a 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -101,7 +101,7 @@ fn encode_impl_type_basename(ebml_w: &mut Encoder, name: Ident) { } pub fn encode_def_id(ebml_w: &mut Encoder, id: DefId) { - ebml_w.wr_tagged_str(tag_def_id, def_to_str(id).as_slice()); + ebml_w.wr_tagged_str(tag_def_id, def_to_string(id).as_slice()); } #[deriving(Clone)] @@ -116,7 +116,7 @@ fn encode_trait_ref(ebml_w: &mut Encoder, tag: uint) { let ty_str_ctxt = &tyencode::ctxt { diag: ecx.diag, - ds: def_to_str, + ds: def_to_string, tcx: ecx.tcx, abbrevs: &ecx.type_abbrevs }; @@ -141,7 +141,7 @@ fn encode_family(ebml_w: &mut Encoder, c: char) { ebml_w.end_tag(); } -pub fn def_to_str(did: DefId) -> String { +pub fn def_to_string(did: DefId) -> String { format!("{}:{}", did.krate, did.node) } @@ -151,7 +151,7 @@ fn encode_ty_type_param_defs(ebml_w: &mut Encoder, tag: uint) { let ty_str_ctxt = &tyencode::ctxt { diag: ecx.diag, - ds: def_to_str, + ds: def_to_string, tcx: ecx.tcx, abbrevs: &ecx.type_abbrevs }; @@ -172,7 +172,7 @@ fn encode_region_param_defs(ebml_w: &mut Encoder, ebml_w.end_tag(); ebml_w.wr_tagged_str(tag_region_param_def_def_id, - def_to_str(param.def_id).as_slice()); + def_to_string(param.def_id).as_slice()); ebml_w.wr_tagged_u64(tag_region_param_def_space, param.space.to_uint() as u64); @@ -204,7 +204,7 @@ fn encode_bounds_and_type(ebml_w: &mut Encoder, fn encode_variant_id(ebml_w: &mut Encoder, vid: DefId) { ebml_w.start_tag(tag_items_data_item_variant); - let s = def_to_str(vid); + let s = def_to_string(vid); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -214,7 +214,7 @@ pub fn write_type(ecx: &EncodeContext, typ: ty::t) { let ty_str_ctxt = &tyencode::ctxt { diag: ecx.diag, - ds: def_to_str, + ds: def_to_string, tcx: ecx.tcx, abbrevs: &ecx.type_abbrevs }; @@ -236,7 +236,7 @@ fn encode_method_fty(ecx: &EncodeContext, let ty_str_ctxt = &tyencode::ctxt { diag: ecx.diag, - ds: def_to_str, + ds: def_to_string, tcx: ecx.tcx, abbrevs: &ecx.type_abbrevs }; @@ -266,14 +266,14 @@ fn encode_disr_val(_: &EncodeContext, ebml_w: &mut Encoder, disr_val: ty::Disr) { ebml_w.start_tag(tag_disr_val); - let s = disr_val.to_str(); + let s = disr_val.to_string(); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } fn encode_parent_item(ebml_w: &mut Encoder, id: DefId) { ebml_w.start_tag(tag_items_data_parent_item); - let s = def_to_str(id); + let s = def_to_string(id); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -291,7 +291,7 @@ fn encode_struct_fields(ebml_w: &mut Encoder, encode_struct_field_family(ebml_w, f.vis); encode_def_id(ebml_w, f.id); ebml_w.start_tag(tag_item_field_origin); - let s = def_to_str(origin); + let s = def_to_string(origin); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); ebml_w.end_tag(); @@ -382,7 +382,7 @@ fn encode_reexported_static_method(ebml_w: &mut Encoder, exp.name, token::get_ident(method_ident)); ebml_w.start_tag(tag_items_data_item_reexport); ebml_w.start_tag(tag_items_data_item_reexport_def_id); - ebml_w.wr_str(def_to_str(method_def_id).as_slice()); + ebml_w.wr_str(def_to_string(method_def_id).as_slice()); ebml_w.end_tag(); ebml_w.start_tag(tag_items_data_item_reexport_name); ebml_w.wr_str(format!("{}::{}", @@ -529,7 +529,7 @@ fn encode_reexports(ecx: &EncodeContext, id); ebml_w.start_tag(tag_items_data_item_reexport); ebml_w.start_tag(tag_items_data_item_reexport_def_id); - ebml_w.wr_str(def_to_str(exp.def_id).as_slice()); + ebml_w.wr_str(def_to_string(exp.def_id).as_slice()); ebml_w.end_tag(); ebml_w.start_tag(tag_items_data_item_reexport_name); ebml_w.wr_str(exp.name.as_slice()); @@ -562,12 +562,12 @@ fn encode_info_for_mod(ecx: &EncodeContext, // Encode info about all the module children. for item in md.items.iter() { ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(local_def(item.id)).as_slice()); + ebml_w.wr_str(def_to_string(local_def(item.id)).as_slice()); ebml_w.end_tag(); each_auxiliary_node_id(*item, |auxiliary_node_id| { ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(local_def( + ebml_w.wr_str(def_to_string(local_def( auxiliary_node_id)).as_slice()); ebml_w.end_tag(); true @@ -579,10 +579,10 @@ fn encode_info_for_mod(ecx: &EncodeContext, debug!("(encoding info for module) ... encoding impl {} \ ({:?}/{:?})", token::get_ident(ident), - did, ecx.tcx.map.node_to_str(did)); + did, ecx.tcx.map.node_to_string(did)); ebml_w.start_tag(tag_mod_impl); - ebml_w.wr_str(def_to_str(local_def(did)).as_slice()); + ebml_w.wr_str(def_to_string(local_def(did)).as_slice()); ebml_w.end_tag(); } _ => {} @@ -628,10 +628,10 @@ fn encode_explicit_self(ebml_w: &mut Encoder, explicit_self: ast::ExplicitSelf_) // Encode the base self type. match explicit_self { - SelfStatic => { ebml_w.writer.write(&[ 's' as u8 ]); } - SelfValue => { ebml_w.writer.write(&[ 'v' as u8 ]); } - SelfUniq => { ebml_w.writer.write(&[ '~' as u8 ]); } - SelfRegion(_, m) => { + SelfStatic => { ebml_w.writer.write(&[ 's' as u8 ]); } + SelfValue(_) => { ebml_w.writer.write(&[ 'v' as u8 ]); } + SelfUniq(_) => { ebml_w.writer.write(&[ '~' as u8 ]); } + SelfRegion(_, m, _) => { // FIXME(#4846) encode custom lifetime ebml_w.writer.write(&['&' as u8]); encode_mutability(ebml_w, m); @@ -659,7 +659,7 @@ fn encode_provided_source(ebml_w: &mut Encoder, source_opt: Option<DefId>) { for source in source_opt.iter() { ebml_w.start_tag(tag_item_method_provided_source); - let s = def_to_str(*source); + let s = def_to_string(*source); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -881,16 +881,6 @@ fn encode_extension_implementations(ecx: &EncodeContext, } } -fn encode_sized(ebml_w: &mut Encoder, sized: Sized) { - ebml_w.start_tag(tag_items_data_item_sized); - let ch = match sized { - DynSize => 'd', - StaticSize => 's', - }; - ebml_w.wr_str(str::from_char(ch).as_slice()); - ebml_w.end_tag(); -} - fn encode_stability(ebml_w: &mut Encoder, stab_opt: Option<attr::Stability>) { stab_opt.map(|stab| { ebml_w.start_tag(tag_items_data_item_stability); @@ -916,7 +906,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } debug!("encoding info for item at {}", - tcx.sess.codemap().span_to_str(item.span)); + tcx.sess.codemap().span_to_string(item.span)); let def_id = local_def(item.id); let stab = stability::lookup(tcx, ast_util::local_def(item.id)); @@ -987,7 +977,7 @@ fn encode_info_for_item(ecx: &EncodeContext, // Encode all the items in this module. for foreign_item in fm.items.iter() { ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(local_def(foreign_item.id)).as_slice()); + ebml_w.wr_str(def_to_string(local_def(foreign_item.id)).as_slice()); ebml_w.end_tag(); } encode_visibility(ebml_w, vis); @@ -1111,7 +1101,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } for &method_def_id in methods.iter() { ebml_w.start_tag(tag_item_impl_method); - let s = def_to_str(method_def_id); + let s = def_to_string(method_def_id); ebml_w.writer.write(s.as_bytes()); ebml_w.end_tag(); } @@ -1149,7 +1139,7 @@ fn encode_info_for_item(ecx: &EncodeContext, ast_method) } } - ItemTrait(_, sized, ref super_traits, ref ms) => { + ItemTrait(_, _, ref super_traits, ref ms) => { add_to_index(item, ebml_w, index); ebml_w.start_tag(tag_items_data_item); encode_def_id(ebml_w, def_id); @@ -1163,9 +1153,6 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_trait_ref(ebml_w, ecx, &*trait_def.trait_ref, tag_item_trait_ref); encode_name(ebml_w, item.ident.name); encode_attributes(ebml_w, item.attrs.as_slice()); - // When we fix the rest of the supertrait nastiness (FIXME(#8559)), we - // should no longer need this ugly little hack either. - encode_sized(ebml_w, sized); encode_visibility(ebml_w, vis); encode_stability(ebml_w, stab); for &method_def_id in ty::trait_method_def_ids(tcx, def_id).iter() { @@ -1174,7 +1161,7 @@ fn encode_info_for_item(ecx: &EncodeContext, ebml_w.end_tag(); ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(method_def_id).as_slice()); + ebml_w.wr_str(def_to_string(method_def_id).as_slice()); ebml_w.end_tag(); } encode_path(ebml_w, path.clone()); @@ -1327,7 +1314,7 @@ fn my_visit_foreign_item(ni: &ForeignItem, // See above let ecx: &EncodeContext = unsafe { mem::transmute(ecx_ptr) }; debug!("writing foreign item {}::{}", - ecx.tcx.map.path_to_str(ni.id), + ecx.tcx.map.path_to_string(ni.id), token::get_ident(ni.ident)); let mut ebml_w = unsafe { @@ -1693,12 +1680,12 @@ fn encode_misc_info(ecx: &EncodeContext, ebml_w.start_tag(tag_misc_info_crate_items); for &item in krate.module.items.iter() { ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(local_def(item.id)).as_slice()); + ebml_w.wr_str(def_to_string(local_def(item.id)).as_slice()); ebml_w.end_tag(); each_auxiliary_node_id(item, |auxiliary_node_id| { ebml_w.start_tag(tag_mod_child); - ebml_w.wr_str(def_to_str(local_def( + ebml_w.wr_str(def_to_string(local_def( auxiliary_node_id)).as_slice()); ebml_w.end_tag(); true @@ -1939,7 +1926,7 @@ pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> String { let mut wr = MemWriter::new(); tyencode::enc_ty(&mut wr, &tyencode::ctxt { diag: tcx.sess.diagnostic(), - ds: def_to_str, + ds: def_to_string, tcx: tcx, abbrevs: &RefCell::new(HashMap::new()) }, t); diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index d7a7d2902b4..fb2b4951ea3 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -28,7 +28,7 @@ use middle::subst; use middle::subst::VecPerParamSpace; use middle::typeck::{MethodCall, MethodCallee, MethodOrigin}; use middle::{ty, typeck}; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; use syntax::{ast, ast_map, ast_util, codemap, fold}; use syntax::codemap::Span; @@ -86,7 +86,7 @@ pub fn encode_inlined_item(ecx: &e::EncodeContext, e::IIMethodRef(_, _, m) => m.id, }; debug!("> Encoding inlined item: {} ({})", - ecx.tcx.map.path_to_str(id), + ecx.tcx.map.path_to_string(id), ebml_w.writer.tell()); let ii = simplify_ast(ii); @@ -99,7 +99,7 @@ pub fn encode_inlined_item(ecx: &e::EncodeContext, ebml_w.end_tag(); debug!("< Encoded inlined fn: {} ({})", - ecx.tcx.map.path_to_str(id), + ecx.tcx.map.path_to_string(id), ebml_w.writer.tell()); } @@ -119,7 +119,7 @@ pub fn decode_inlined_item(cdata: &cstore::crate_metadata, debug!("> Decoding inlined fn: {}::?", { // Do an Option dance to use the path after it is moved below. - let s = ast_map::path_to_str(ast_map::Values(path.iter())); + let s = ast_map::path_to_string(ast_map::Values(path.iter())); path_as_str = Some(s); path_as_str.as_ref().map(|x| x.as_slice()) }); @@ -147,7 +147,7 @@ pub fn decode_inlined_item(cdata: &cstore::crate_metadata, match ii { ast::IIItem(i) => { debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<", - syntax::print::pprust::item_to_str(&*i)); + syntax::print::pprust::item_to_string(&*i)); } _ => { } } @@ -826,7 +826,7 @@ impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> { fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> { tyencode::ctxt { diag: self.tcx.sess.diagnostic(), - ds: e::def_to_str, + ds: e::def_to_string, tcx: self.tcx, abbrevs: &self.type_abbrevs } @@ -1391,7 +1391,7 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext, c::tag_table_node_type => { let ty = val_dsr.read_ty(xcx); debug!("inserting ty for node {:?}: {}", - id, ty_to_str(dcx.tcx, ty)); + id, ty_to_string(dcx.tcx, ty)); dcx.tcx.node_types.borrow_mut().insert(id as uint, ty); } c::tag_table_item_subst => { @@ -1523,7 +1523,7 @@ fn test_basic() { fn foo() {} )); } - +/* NOTE: When there's a snapshot, update this (yay quasiquoter!) #[test] fn test_smalltalk() { let cx = mk_ctxt(); @@ -1531,6 +1531,7 @@ fn test_smalltalk() { fn foo() -> int { 3 + 4 } // first smalltalk program ever executed. )); } +*/ #[test] fn test_more() { @@ -1561,7 +1562,7 @@ fn test_simplification() { ).unwrap()); match (item_out, item_exp) { (ast::IIItem(item_out), ast::IIItem(item_exp)) => { - assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp)); + assert!(pprust::item_to_string(item_out) == pprust::item_to_string(item_exp)); } _ => fail!() } diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index df208b9cdc1..db8ab8c83fb 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -351,7 +351,7 @@ impl<'a> CheckLoanCtxt<'a> { "it".to_string() } else { format!("`{}`", - self.bccx.loan_path_to_str(&*old_loan.loan_path)) + self.bccx.loan_path_to_string(&*old_loan.loan_path)) }; match (new_loan.kind, old_loan.kind) { @@ -360,7 +360,7 @@ impl<'a> CheckLoanCtxt<'a> { new_loan.span, format!("cannot borrow `{}` as mutable \ more than once at a time", - self.bccx.loan_path_to_str( + self.bccx.loan_path_to_string( &*new_loan.loan_path)).as_slice()); } @@ -369,7 +369,7 @@ impl<'a> CheckLoanCtxt<'a> { new_loan.span, format!("closure requires unique access to `{}` \ but {} is already borrowed", - self.bccx.loan_path_to_str(&*new_loan.loan_path), + self.bccx.loan_path_to_string(&*new_loan.loan_path), old_pronoun).as_slice()); } @@ -378,7 +378,7 @@ impl<'a> CheckLoanCtxt<'a> { new_loan.span, format!("cannot borrow `{}` as {} because \ previous closure requires unique access", - self.bccx.loan_path_to_str(&*new_loan.loan_path), + self.bccx.loan_path_to_string(&*new_loan.loan_path), new_loan.kind.to_user_str()).as_slice()); } @@ -387,7 +387,7 @@ impl<'a> CheckLoanCtxt<'a> { new_loan.span, format!("cannot borrow `{}` as {} because \ {} is also borrowed as {}", - self.bccx.loan_path_to_str(&*new_loan.loan_path), + self.bccx.loan_path_to_string(&*new_loan.loan_path), new_loan.kind.to_user_str(), old_pronoun, old_loan.kind.to_user_str()).as_slice()); @@ -399,7 +399,7 @@ impl<'a> CheckLoanCtxt<'a> { self.bccx.span_note( span, format!("borrow occurs due to use of `{}` in closure", - self.bccx.loan_path_to_str( + self.bccx.loan_path_to_string( &*new_loan.loan_path)).as_slice()); } _ => { } @@ -410,7 +410,7 @@ 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( + self.bccx.loan_path_to_string( &*old_loan.loan_path)) } @@ -418,14 +418,14 @@ impl<'a> CheckLoanCtxt<'a> { format!("the immutable borrow prevents subsequent \ moves or mutable borrows of `{0}` \ until the borrow ends", - self.bccx.loan_path_to_str(&*old_loan.loan_path)) + self.bccx.loan_path_to_string(&*old_loan.loan_path)) } ty::UniqueImmBorrow => { format!("the unique capture prevents subsequent \ moves or borrows of `{0}` \ until the borrow ends", - self.bccx.loan_path_to_str(&*old_loan.loan_path)) + self.bccx.loan_path_to_string(&*old_loan.loan_path)) } }; @@ -433,7 +433,7 @@ impl<'a> CheckLoanCtxt<'a> { euv::ClosureCapture(_) => { format!("previous borrow of `{}` occurs here due to \ use in closure", - self.bccx.loan_path_to_str(&*old_loan.loan_path)) + self.bccx.loan_path_to_string(&*old_loan.loan_path)) } euv::OverloadedOperator(..) | @@ -442,7 +442,7 @@ impl<'a> CheckLoanCtxt<'a> { euv::ClosureInvocation(..) | euv::RefBinding(..) => { format!("previous borrow of `{}` occurs here", - self.bccx.loan_path_to_str(&*old_loan.loan_path)) + self.bccx.loan_path_to_string(&*old_loan.loan_path)) } }; @@ -518,12 +518,12 @@ impl<'a> CheckLoanCtxt<'a> { self.bccx.span_err( span, format!("cannot use `{}` because it was mutably borrowed", - self.bccx.loan_path_to_str(copy_path).as_slice()) + self.bccx.loan_path_to_string(copy_path).as_slice()) .as_slice()); self.bccx.span_note( loan_span, format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_str(&*loan_path).as_slice()) + self.bccx.loan_path_to_string(&*loan_path).as_slice()) .as_slice()); } } @@ -543,19 +543,19 @@ impl<'a> CheckLoanCtxt<'a> { let err_message = match move_kind { move_data::Captured => format!("cannot move `{}` into closure because it is borrowed", - self.bccx.loan_path_to_str(move_path).as_slice()), + self.bccx.loan_path_to_string(move_path).as_slice()), move_data::Declared | move_data::MoveExpr | move_data::MovePat => format!("cannot move out of `{}` because it is borrowed", - self.bccx.loan_path_to_str(move_path).as_slice()) + self.bccx.loan_path_to_string(move_path).as_slice()) }; self.bccx.span_err(span, err_message.as_slice()); self.bccx.span_note( loan_span, format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_str(&*loan_path).as_slice()) + self.bccx.loan_path_to_string(&*loan_path).as_slice()) .as_slice()); } } @@ -567,7 +567,7 @@ impl<'a> CheckLoanCtxt<'a> { borrow_kind: ty::BorrowKind) -> UseError { debug!("analyze_restrictions_on_use(expr_id={:?}, use_path={})", - self.tcx().map.node_to_str(expr_id), + self.tcx().map.node_to_string(expr_id), use_path.repr(self.tcx())); let mut ret = UseOk; @@ -690,15 +690,15 @@ impl<'a> CheckLoanCtxt<'a> { assignment_span, format!("cannot assign to {} {} `{}`", assignee_cmt.mutbl.to_user_str(), - self.bccx.cmt_to_str(&*assignee_cmt), - self.bccx.loan_path_to_str(&*lp)).as_slice()); + self.bccx.cmt_to_string(&*assignee_cmt), + self.bccx.loan_path_to_string(&*lp)).as_slice()); } None => { self.bccx.span_err( assignment_span, format!("cannot assign to {} {}", assignee_cmt.mutbl.to_user_str(), - self.bccx.cmt_to_str(&*assignee_cmt)).as_slice()); + self.bccx.cmt_to_string(&*assignee_cmt)).as_slice()); } } return; @@ -824,10 +824,10 @@ impl<'a> CheckLoanCtxt<'a> { self.bccx.span_err( span, format!("cannot assign to `{}` because it is borrowed", - self.bccx.loan_path_to_str(loan_path)).as_slice()); + self.bccx.loan_path_to_string(loan_path)).as_slice()); self.bccx.span_note( loan.span, format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_str(loan_path)).as_slice()); + self.bccx.loan_path_to_string(loan_path)).as_slice()); } } diff --git a/src/librustc/middle/borrowck/gather_loans/move_error.rs b/src/librustc/middle/borrowck/gather_loans/move_error.rs index f5c91f7b1b3..9876e12d5cc 100644 --- a/src/librustc/middle/borrowck/gather_loans/move_error.rs +++ b/src/librustc/middle/borrowck/gather_loans/move_error.rs @@ -120,7 +120,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)).as_slice()); + bccx.cmt_to_string(&*move_from)).as_slice()); } mc::cat_downcast(ref b) | @@ -145,7 +145,7 @@ fn note_move_destination(bccx: &BorrowckCtxt, move_to_span: codemap::Span, pat_ident: &ast::Ident, is_first_note: bool) { - let pat_name = pprust::ident_to_str(pat_ident); + let pat_name = pprust::ident_to_string(pat_ident); if is_first_note { bccx.span_note( move_to_span, diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 9ab3202b909..426a1fbede5 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -418,7 +418,7 @@ impl<'a> BorrowckCtxt<'a> { pub fn report(&self, err: BckError) { self.span_err( err.span, - self.bckerr_to_str(&err).as_slice()); + self.bckerr_to_string(&err).as_slice()); self.note_and_explain_bckerr(err); } @@ -439,7 +439,7 @@ impl<'a> BorrowckCtxt<'a> { use_span, format!("{} of possibly uninitialized variable: `{}`", verb, - self.loan_path_to_str(lp)).as_slice()); + self.loan_path_to_string(lp)).as_slice()); } _ => { let partially = if lp == moved_lp {""} else {"partially "}; @@ -448,7 +448,7 @@ impl<'a> BorrowckCtxt<'a> { format!("{} of {}moved value: `{}`", verb, partially, - self.loan_path_to_str(lp)).as_slice()); + self.loan_path_to_string(lp)).as_slice()); } } @@ -472,7 +472,7 @@ impl<'a> BorrowckCtxt<'a> { self.tcx.sess.span_note( expr_span, format!("`{}` moved here because it has type `{}`, which is {}", - self.loan_path_to_str(moved_lp), + self.loan_path_to_string(moved_lp), expr_ty.user_string(self.tcx), suggestion).as_slice()); } @@ -483,7 +483,7 @@ impl<'a> BorrowckCtxt<'a> { format!("`{}` moved here because it has type `{}`, \ which is moved by default (use `ref` to \ override)", - self.loan_path_to_str(moved_lp), + self.loan_path_to_string(moved_lp), pat_ty.user_string(self.tcx)).as_slice()); } @@ -506,7 +506,7 @@ impl<'a> BorrowckCtxt<'a> { expr_span, format!("`{}` moved into closure environment here because it \ has type `{}`, which is {}", - self.loan_path_to_str(moved_lp), + self.loan_path_to_string(moved_lp), expr_ty.user_string(self.tcx), suggestion).as_slice()); } @@ -536,7 +536,7 @@ impl<'a> BorrowckCtxt<'a> { self.tcx.sess.span_err( span, format!("re-assignment of immutable variable `{}`", - self.loan_path_to_str(lp)).as_slice()); + self.loan_path_to_string(lp)).as_slice()); self.tcx.sess.span_note(assign.span, "prior assignment occurs here"); } @@ -552,20 +552,20 @@ impl<'a> BorrowckCtxt<'a> { self.tcx.sess.span_end_note(s, m); } - pub fn bckerr_to_str(&self, err: &BckError) -> String { + pub fn bckerr_to_string(&self, err: &BckError) -> String { match err.code { err_mutbl => { let descr = match opt_loan_path(&err.cmt) { None => { format!("{} {}", err.cmt.mutbl.to_user_str(), - self.cmt_to_str(&*err.cmt)) + self.cmt_to_string(&*err.cmt)) } Some(lp) => { format!("{} {} `{}`", err.cmt.mutbl.to_user_str(), - self.cmt_to_str(&*err.cmt), - self.loan_path_to_str(&*lp)) + self.cmt_to_string(&*err.cmt), + self.loan_path_to_string(&*lp)) } }; @@ -589,7 +589,7 @@ impl<'a> BorrowckCtxt<'a> { let msg = match opt_loan_path(&err.cmt) { None => "borrowed value".to_string(), Some(lp) => { - format!("`{}`", self.loan_path_to_str(&*lp)) + format!("`{}`", self.loan_path_to_string(&*lp)) } }; format!("{} does not live long enough", msg) @@ -597,9 +597,9 @@ impl<'a> BorrowckCtxt<'a> { err_borrowed_pointer_too_short(..) => { let descr = match opt_loan_path(&err.cmt) { Some(lp) => { - format!("`{}`", self.loan_path_to_str(&*lp)) + format!("`{}`", self.loan_path_to_string(&*lp)) } - None => self.cmt_to_str(&*err.cmt), + None => self.cmt_to_string(&*err.cmt), }; format!("lifetime of {} is too short to guarantee \ @@ -691,9 +691,9 @@ impl<'a> BorrowckCtxt<'a> { err_borrowed_pointer_too_short(loan_scope, ptr_scope) => { let descr = match opt_loan_path(&err.cmt) { Some(lp) => { - format!("`{}`", self.loan_path_to_str(&*lp)) + format!("`{}`", self.loan_path_to_string(&*lp)) } - None => self.cmt_to_str(&*err.cmt), + None => self.cmt_to_string(&*err.cmt), }; note_and_explain_region( self.tcx, @@ -710,7 +710,7 @@ impl<'a> BorrowckCtxt<'a> { } } - pub fn append_loan_path_to_str(&self, + pub fn append_loan_path_to_string(&self, loan_path: &LoanPath, out: &mut String) { match *loan_path { @@ -720,7 +720,7 @@ impl<'a> BorrowckCtxt<'a> { } LpExtend(ref lp_base, _, LpInterior(mc::InteriorField(fname))) => { - self.append_autoderefd_loan_path_to_str(&**lp_base, out); + self.append_autoderefd_loan_path_to_string(&**lp_base, out); match fname { mc::NamedField(fname) => { out.push_char('.'); @@ -728,24 +728,24 @@ impl<'a> BorrowckCtxt<'a> { } mc::PositionalField(idx) => { out.push_char('#'); // invent a notation here - out.push_str(idx.to_str().as_slice()); + out.push_str(idx.to_string().as_slice()); } } } LpExtend(ref lp_base, _, LpInterior(mc::InteriorElement(_))) => { - self.append_autoderefd_loan_path_to_str(&**lp_base, out); + self.append_autoderefd_loan_path_to_string(&**lp_base, out); out.push_str("[..]"); } LpExtend(ref lp_base, _, LpDeref(_)) => { out.push_char('*'); - self.append_loan_path_to_str(&**lp_base, out); + self.append_loan_path_to_string(&**lp_base, out); } } } - pub fn append_autoderefd_loan_path_to_str(&self, + pub fn append_autoderefd_loan_path_to_string(&self, loan_path: &LoanPath, out: &mut String) { match *loan_path { @@ -753,23 +753,23 @@ impl<'a> BorrowckCtxt<'a> { // For a path like `(*x).f` or `(*x)[3]`, autoderef // rules would normally allow users to omit the `*x`. // So just serialize such paths to `x.f` or x[3]` respectively. - self.append_autoderefd_loan_path_to_str(&**lp_base, out) + self.append_autoderefd_loan_path_to_string(&**lp_base, out) } LpVar(..) | LpUpvar(..) | LpExtend(_, _, LpInterior(..)) => { - self.append_loan_path_to_str(loan_path, out) + self.append_loan_path_to_string(loan_path, out) } } } - pub fn loan_path_to_str(&self, loan_path: &LoanPath) -> String { + pub fn loan_path_to_string(&self, loan_path: &LoanPath) -> String { let mut result = String::new(); - self.append_loan_path_to_str(loan_path, &mut result); + self.append_loan_path_to_string(loan_path, &mut result); result } - pub fn cmt_to_str(&self, cmt: &mc::cmt_) -> String { - self.mc().cmt_to_str(cmt) + pub fn cmt_to_string(&self, cmt: &mc::cmt_) -> String { + self.mc().cmt_to_string(cmt) } } @@ -815,11 +815,11 @@ impl Repr for LoanPath { fn repr(&self, tcx: &ty::ctxt) -> String { match self { &LpVar(id) => { - format!("$({})", tcx.map.node_to_str(id)) + format!("$({})", tcx.map.node_to_string(id)) } &LpUpvar(ty::UpvarId{ var_id, closure_expr_id }) => { - let s = tcx.map.node_to_str(var_id); + let s = tcx.map.node_to_string(var_id); format!("$({} captured by id={})", s, closure_expr_id) } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index c33580d869b..9f44f0babc7 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -64,7 +64,7 @@ impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { } else if n.data.id == ast::DUMMY_NODE_ID { dot::LabelStr("(dummy_node)".into_maybe_owned()) } else { - let s = self.ast_map.node_to_str(n.data.id); + let s = self.ast_map.node_to_string(n.data.id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); dot::EscStr(s.into_maybe_owned()) @@ -80,7 +80,7 @@ impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> { } else { put_one = true; } - let s = self.ast_map.node_to_str(node_id); + let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); label = label.append(format!("exiting scope_{} {}", diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index cf886702d86..33bf6ceed4f 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -108,7 +108,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_string(v.tcx, ety)).as_slice()) } } ExprPath(ref pth) => { diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 6ba112bf353..599f5f4024f 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -22,10 +22,10 @@ use syntax::ast::*; use syntax::ast_util::{is_unguarded, walk_pat}; use syntax::codemap::{Span, Spanned, DUMMY_SP}; use syntax::owned_slice::OwnedSlice; -use syntax::print::pprust::pat_to_str; +use syntax::print::pprust::pat_to_string; use syntax::visit; use syntax::visit::{Visitor, FnKind}; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; struct Matrix(Vec<Vec<Gc<Pat>>>); @@ -47,7 +47,7 @@ impl fmt::Show for Matrix { let &Matrix(ref m) = self; let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| { - row.iter().map(|&pat| pat_to_str(pat)).collect::<Vec<String>>() + row.iter().map(|&pat| pat_to_string(pat)).collect::<Vec<String>>() }).collect(); let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u); @@ -147,7 +147,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)).as_slice()); + ty_to_string(cx.tcx, pat_ty)).as_slice()); } // If the type *is* empty, it's vacuously exhaustive return; @@ -222,7 +222,8 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, m: &Matrix) { [] => wild(), _ => unreachable!() }; - let msg = format!("non-exhaustive patterns: `{0}` not covered", pat_to_str(&*witness)); + let msg = format!("non-exhaustive patterns: `{0}` not covered", + pat_to_string(&*witness)); cx.tcx.sess.span_err(sp, msg.as_slice()); } NotUseful => { @@ -780,7 +781,7 @@ fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) { Some(pat) => { let msg = format!( "refutable pattern in {} binding: `{}` not covered", - name, pat_to_str(&*pat) + name, pat_to_string(&*pat) ); cx.tcx.sess.span_err(loc.pat.span, msg.as_slice()); }, @@ -802,7 +803,7 @@ fn check_fn(cx: &mut MatchCheckCtxt, Some(pat) => { let msg = format!( "refutable pattern in function argument: `{}` not covered", - pat_to_str(&*pat) + pat_to_string(&*pat) ); cx.tcx.sess.span_err(input.pat.span, msg.as_slice()); }, diff --git a/src/librustc/middle/check_static.rs b/src/librustc/middle/check_static.rs index 33949ee5b16..1e948afb701 100644 --- a/src/librustc/middle/check_static.rs +++ b/src/librustc/middle/check_static.rs @@ -75,7 +75,7 @@ impl<'a> CheckStaticVisitor<'a> { impl<'a> Visitor<bool> for CheckStaticVisitor<'a> { fn visit_item(&mut self, i: &ast::Item, _is_const: bool) { - debug!("visit_item(item={})", pprust::item_to_str(i)); + debug!("visit_item(item={})", pprust::item_to_string(i)); match i.node { ast::ItemStatic(_, mutability, ref expr) => { match mutability { @@ -99,7 +99,7 @@ impl<'a> Visitor<bool> for CheckStaticVisitor<'a> { /// of a static item, this method does nothing but walking /// down through it. fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) { - debug!("visit_expr(expr={})", pprust::expr_to_str(e)); + debug!("visit_expr(expr={})", pprust::expr_to_string(e)); if !is_const { return visit::walk_expr(self, e, is_const); diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 5ac85833e22..7d9178162a6 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -164,18 +164,18 @@ impl<'a, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, O> { let cfgidx = to_cfgidx_or_die(id, &self.nodeid_to_index); let (start, end) = self.compute_id_range_frozen(cfgidx); let on_entry = self.on_entry.slice(start, end); - let entry_str = bits_to_str(on_entry); + let entry_str = bits_to_string(on_entry); let gens = self.gens.slice(start, end); let gens_str = if gens.iter().any(|&u| u != 0) { - format!(" gen: {}", bits_to_str(gens)) + format!(" gen: {}", bits_to_string(gens)) } else { "".to_string() }; let kills = self.kills.slice(start, end); let kills_str = if kills.iter().any(|&u| u != 0) { - format!(" kill: {}", bits_to_str(kills)) + format!(" kill: {}", bits_to_string(kills)) } else { "".to_string() }; @@ -289,7 +289,7 @@ impl<'a, O:DataFlowOperator> DataFlowContext<'a, O> { fn apply_gen_kill(&mut self, cfgidx: CFGIndex, bits: &mut [uint]) { //! Applies the gen and kill sets for `id` to `bits` debug!("{:s} apply_gen_kill(cfgidx={}, bits={}) [before]", - self.analysis_name, cfgidx, mut_bits_to_str(bits)); + self.analysis_name, cfgidx, mut_bits_to_string(bits)); let (start, end) = self.compute_id_range(cfgidx); let gens = self.gens.slice(start, end); bitwise(bits, gens, &Union); @@ -297,7 +297,7 @@ impl<'a, O:DataFlowOperator> DataFlowContext<'a, O> { bitwise(bits, kills, &Subtract); debug!("{:s} apply_gen_kill(cfgidx={}, bits={}) [after]", - self.analysis_name, cfgidx, mut_bits_to_str(bits)); + self.analysis_name, cfgidx, mut_bits_to_string(bits)); } fn compute_id_range_frozen(&self, cfgidx: CFGIndex) -> (uint, uint) { @@ -334,7 +334,7 @@ impl<'a, O:DataFlowOperator> DataFlowContext<'a, O> { let (start, end) = self.compute_id_range_frozen(cfgidx); let on_entry = self.on_entry.slice(start, end); debug!("{:s} each_bit_on_entry_frozen(id={:?}, on_entry={})", - self.analysis_name, id, bits_to_str(on_entry)); + self.analysis_name, id, bits_to_string(on_entry)); self.each_bit(on_entry, f) } @@ -348,7 +348,7 @@ impl<'a, O:DataFlowOperator> DataFlowContext<'a, O> { let (start, end) = self.compute_id_range_frozen(cfgidx); let gens = self.gens.slice(start, end); debug!("{:s} each_gen_bit(id={:?}, gens={})", - self.analysis_name, id, bits_to_str(gens)); + self.analysis_name, id, bits_to_string(gens)); self.each_bit(gens, f) } @@ -426,10 +426,10 @@ impl<'a, O:DataFlowOperator> DataFlowContext<'a, O> { if changed { let bits = self.kills.mut_slice(start, end); debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [before]", - self.analysis_name, flow_exit, mut_bits_to_str(bits)); + self.analysis_name, flow_exit, mut_bits_to_string(bits)); bits.copy_from(orig_kills.as_slice()); debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [after]", - self.analysis_name, flow_exit, mut_bits_to_str(bits)); + self.analysis_name, flow_exit, mut_bits_to_string(bits)); } true }); @@ -483,10 +483,10 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> { cfg: &cfg::CFG, in_out: &mut [uint]) { debug!("DataFlowContext::walk_cfg(in_out={}) {:s}", - bits_to_str(in_out), self.dfcx.analysis_name); + bits_to_string(in_out), self.dfcx.analysis_name); cfg.graph.each_node(|node_index, node| { debug!("DataFlowContext::walk_cfg idx={} id={} begin in_out={}", - node_index, node.data.id, bits_to_str(in_out)); + node_index, node.data.id, bits_to_string(in_out)); let (start, end) = self.dfcx.compute_id_range(node_index); @@ -526,7 +526,7 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> { let source = edge.source(); let cfgidx = edge.target(); debug!("{:s} propagate_bits_into_entry_set_for(pred_bits={}, {} to {})", - self.dfcx.analysis_name, bits_to_str(pred_bits), source, cfgidx); + self.dfcx.analysis_name, bits_to_string(pred_bits), source, cfgidx); let (start, end) = self.dfcx.compute_id_range(cfgidx); let changed = { // (scoping mutable borrow of self.dfcx.on_entry) @@ -536,17 +536,17 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> { if changed { debug!("{:s} changed entry set for {:?} to {}", self.dfcx.analysis_name, cfgidx, - bits_to_str(self.dfcx.on_entry.slice(start, end))); + bits_to_string(self.dfcx.on_entry.slice(start, end))); self.changed = true; } } } -fn mut_bits_to_str(words: &mut [uint]) -> String { - bits_to_str(words) +fn mut_bits_to_string(words: &mut [uint]) -> String { + bits_to_string(words) } -fn bits_to_str(words: &[uint]) -> String { +fn bits_to_string(words: &[uint]) -> String { let mut result = String::new(); let mut sep = '['; @@ -582,7 +582,7 @@ fn bitwise<Op:BitwiseOperator>(out_vec: &mut [uint], fn set_bit(words: &mut [uint], bit: uint) -> bool { debug!("set_bit: words={} bit={}", - mut_bits_to_str(words), bit_str(bit)); + mut_bits_to_string(words), bit_str(bit)); let word = bit / uint::BITS; let bit_in_word = bit % uint::BITS; let bit_mask = 1 << bit_in_word; diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index 2333b329996..782a380e23a 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -68,7 +68,7 @@ impl<'a> EffectCheckVisitor<'a> { _ => return }; debug!("effect: checking index with base type {}", - ppaux::ty_to_str(self.tcx, base_type)); + ppaux::ty_to_string(self.tcx, base_type)); match ty::get(base_type).sty { ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty::get(ty).sty { ty::ty_str => { @@ -147,7 +147,7 @@ impl<'a> Visitor<()> for EffectCheckVisitor<'a> { let method_call = MethodCall::expr(expr.id); let base_type = self.tcx.method_map.borrow().get(&method_call).ty; debug!("effect: method call case, base type is {}", - ppaux::ty_to_str(self.tcx, base_type)); + ppaux::ty_to_string(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, "invocation of unsafe method") @@ -156,7 +156,7 @@ impl<'a> Visitor<()> for EffectCheckVisitor<'a> { ast::ExprCall(base, _) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug!("effect: call case, base type is {}", - ppaux::ty_to_str(self.tcx, base_type)); + ppaux::ty_to_string(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, "call to unsafe function") } @@ -164,7 +164,7 @@ impl<'a> Visitor<()> for EffectCheckVisitor<'a> { ast::ExprUnary(ast::UnDeref, base) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug!("effect: unary case, base type is {}", - ppaux::ty_to_str(self.tcx, base_type)); + ppaux::ty_to_string(self.tcx, base_type)); match ty::get(base_type).sty { ty::ty_ptr(_) => { self.require_unsafe(expr.span, diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index a7154e78bc5..d432ced5226 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -15,13 +15,13 @@ use middle::subst; use middle::ty; use middle::typeck::{MethodCall, NoAdjustment}; use middle::typeck; -use util::ppaux::{Repr, ty_to_str}; +use util::ppaux::{Repr, ty_to_string}; use util::ppaux::UserString; use syntax::ast::*; use syntax::attr; use syntax::codemap::Span; -use syntax::print::pprust::{expr_to_str, ident_to_str}; +use syntax::print::pprust::{expr_to_string, ident_to_string}; use syntax::{visit}; use syntax::visit::Visitor; @@ -126,7 +126,7 @@ fn check_impl_of_trait(cx: &mut Context, it: &Item, trait_ref: &TraitRef, self_t 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), + ty_to_string(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 `{}`", @@ -246,7 +246,7 @@ fn check_fn( } pub fn check_expr(cx: &mut Context, e: &Expr) { - debug!("kind::check_expr({})", expr_to_str(e)); + debug!("kind::check_expr({})", expr_to_string(e)); // Handle any kind bounds on type parameters check_bounds_on_type_parameters(cx, e); @@ -492,7 +492,7 @@ pub fn check_typaram_bounds(cx: &Context, sp, format!("instantiating a type parameter with an incompatible type \ `{}`, which does not fulfill `{}`", - ty_to_str(cx.tcx, ty), + ty_to_string(cx.tcx, ty), missing.user_string(cx.tcx)).as_slice()); }); } @@ -509,14 +509,14 @@ pub fn check_freevar_bounds(cx: &Context, sp: Span, ty: ty::t, format!("cannot implicitly borrow variable of type `{}` in a \ bounded stack closure (implicit reference does not \ fulfill `{}`)", - ty_to_str(cx.tcx, rty), + ty_to_string(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), + ty_to_string(cx.tcx, ty), missing.user_string(cx.tcx)).as_slice()) } } @@ -533,20 +533,20 @@ pub fn check_trait_cast_bounds(cx: &Context, sp: Span, ty: ty::t, 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), + ty_to_string(cx.tcx, ty), missing.user_string(cx.tcx), bounds.user_string(cx.tcx)).as_slice()); }); } fn check_copy(cx: &Context, ty: ty::t, sp: Span, reason: &str) { debug!("type_contents({})={}", - ty_to_str(cx.tcx, ty), - ty::type_contents(cx.tcx, ty).to_str()); + ty_to_string(cx.tcx, ty), + ty::type_contents(cx.tcx, ty).to_string()); 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)).as_slice()); + ty_to_string(cx.tcx, ty)).as_slice()); cx.tcx.sess.span_note(sp, format!("{}", reason).as_slice()); } } @@ -558,7 +558,7 @@ pub fn check_static(tcx: &ty::ctxt, ty: ty::t, sp: Span) -> bool { tcx.sess.span_err(sp, format!("value may contain references; \ add `'static` bound to `{}`", - ty_to_str(tcx, ty)).as_slice()); + ty_to_string(tcx, ty)).as_slice()); } _ => { tcx.sess.span_err(sp, "value may contain references"); @@ -643,7 +643,7 @@ pub fn check_cast_for_escaping_regions( // source_span, // format!("source contains reference with lifetime \ // not found in the target type `{}`", - // ty_to_str(cx.tcx, target_ty))); + // ty_to_string(cx.tcx, target_ty))); // note_and_explain_region( // cx.tcx, "source data is only valid for ", r, ""); // } @@ -683,7 +683,7 @@ fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: String, sp: Span) { format!("variable `{}` has dynamically sized type \ `{}`", name, - ty_to_str(tcx, ty)).as_slice()); + ty_to_string(tcx, ty)).as_slice()); } } @@ -691,7 +691,7 @@ fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: String, sp: Span) { fn check_pat(cx: &mut Context, pat: &Pat) { let var_name = match pat.node { PatWild => Some("_".to_string()), - PatIdent(_, ref path1, _) => Some(ident_to_str(&path1.node).to_string()), + PatIdent(_, ref path1, _) => Some(ident_to_string(&path1.node).to_string()), _ => None }; @@ -702,7 +702,7 @@ fn check_pat(cx: &mut Context, pat: &Pat) { match ty { Some(ty) => { debug!("kind: checking sized-ness of variable {}: {}", - name, ty_to_str(cx.tcx, *ty)); + name, ty_to_string(cx.tcx, *ty)); check_sized(cx.tcx, *ty, name, pat.span); } None => {} // extern fn args diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index a3306245762..79742d31734 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -121,7 +121,7 @@ use syntax::ast::*; use syntax::codemap::{BytePos, original_sp, Span}; use syntax::parse::token::special_idents; use syntax::parse::token; -use syntax::print::pprust::{expr_to_str, block_to_str}; +use syntax::print::pprust::{expr_to_string, block_to_string}; use syntax::{visit, ast_util}; use syntax::visit::{Visitor, FnKind}; @@ -152,17 +152,17 @@ enum LiveNodeKind { ExitNode } -fn live_node_kind_to_str(lnk: LiveNodeKind, cx: &ty::ctxt) -> String { +fn live_node_kind_to_string(lnk: LiveNodeKind, cx: &ty::ctxt) -> String { let cm = cx.sess.codemap(); match lnk { FreeVarNode(s) => { - format!("Free var node [{}]", cm.span_to_str(s)) + format!("Free var node [{}]", cm.span_to_string(s)) } ExprNode(s) => { - format!("Expr node [{}]", cm.span_to_str(s)) + format!("Expr node [{}]", cm.span_to_string(s)) } VarDefNode(s) => { - format!("Var def node [{}]", cm.span_to_str(s)) + format!("Var def node [{}]", cm.span_to_string(s)) } ExitNode => "Exit node".to_string(), } @@ -272,8 +272,8 @@ impl<'a> IrMaps<'a> { self.lnks.push(lnk); self.num_live_nodes += 1; - debug!("{} is of kind {}", ln.to_str(), - live_node_kind_to_str(lnk, self.tcx)); + debug!("{} is of kind {}", ln.to_string(), + live_node_kind_to_string(lnk, self.tcx)); ln } @@ -282,7 +282,7 @@ impl<'a> IrMaps<'a> { let ln = self.add_live_node(lnk); self.live_node_map.insert(node_id, ln); - debug!("{} is node {}", ln.to_str(), node_id); + debug!("{} is node {}", ln.to_string(), node_id); } fn add_variable(&mut self, vk: VarKind) -> Variable { @@ -297,7 +297,7 @@ impl<'a> IrMaps<'a> { ImplicitRet => {} } - debug!("{} is {:?}", v.to_str(), vk); + debug!("{} is {:?}", v.to_string(), vk); v } @@ -317,7 +317,7 @@ impl<'a> IrMaps<'a> { fn variable_name(&self, var: Variable) -> String { match self.var_kinds.get(var.get()) { &Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => { - token::get_ident(nm).get().to_str() + token::get_ident(nm).get().to_string() }, &ImplicitRet => "<implicit-ret>".to_string() } @@ -675,7 +675,7 @@ impl<'a> Liveness<'a> { for var_idx in range(0u, self.ir.num_vars) { let idx = node_base_idx + var_idx; if test(idx).is_valid() { - try!(write!(wr, " {}", Variable(var_idx).to_str())); + try!(write!(wr, " {}", Variable(var_idx).to_string())); } } Ok(()) @@ -717,7 +717,7 @@ impl<'a> Liveness<'a> { self.write_vars(wr, ln, |idx| self.users.get(idx).reader); write!(wr, " writes"); self.write_vars(wr, ln, |idx| self.users.get(idx).writer); - write!(wr, " precedes {}]", self.successors.get(ln.get()).to_str()); + write!(wr, " precedes {}]", self.successors.get(ln.get()).to_string()); } str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string() } @@ -766,7 +766,7 @@ impl<'a> Liveness<'a> { }); debug!("merge_from_succ(ln={}, succ={}, first_merge={}, changed={})", - ln.to_str(), self.ln_str(succ_ln), first_merge, changed); + ln.to_string(), self.ln_str(succ_ln), first_merge, changed); return changed; fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool { @@ -787,14 +787,14 @@ impl<'a> Liveness<'a> { self.users.get_mut(idx).reader = invalid_node(); self.users.get_mut(idx).writer = invalid_node(); - debug!("{} defines {} (idx={}): {}", writer.to_str(), var.to_str(), + debug!("{} defines {} (idx={}): {}", writer.to_string(), var.to_string(), idx, self.ln_str(writer)); } // Either read, write, or both depending on the acc bitset fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) { debug!("{} accesses[{:x}] {}: {}", - ln.to_str(), acc, var.to_str(), self.ln_str(ln)); + ln.to_string(), acc, var.to_string(), self.ln_str(ln)); let idx = self.idx(ln, var); let user = self.users.get_mut(idx); @@ -822,7 +822,7 @@ impl<'a> Liveness<'a> { // effectively a return---this only occurs in `for` loops, // where the body is really a closure. - debug!("compute: using id for block, {}", block_to_str(body)); + debug!("compute: using id for block, {}", block_to_string(body)); let exit_ln = self.s.exit_ln; let entry_ln: LiveNode = @@ -837,7 +837,7 @@ impl<'a> Liveness<'a> { } body.id }, - entry_ln.to_str()); + entry_ln.to_string()); entry_ln } @@ -928,7 +928,7 @@ impl<'a> Liveness<'a> { fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode) -> LiveNode { - debug!("propagate_through_expr: {}", expr_to_str(expr)); + debug!("propagate_through_expr: {}", expr_to_string(expr)); match expr.node { // Interesting cases with control flow or which gen/kill @@ -942,7 +942,7 @@ impl<'a> Liveness<'a> { } ExprFnBlock(_, ref blk) | ExprProc(_, ref blk) => { - debug!("{} is an ExprFnBlock or ExprProc", expr_to_str(expr)); + debug!("{} is an ExprFnBlock or ExprProc", expr_to_string(expr)); /* The next-node for a break is the successor of the entire @@ -1314,7 +1314,7 @@ impl<'a> Liveness<'a> { first_merge = false; } debug!("propagate_through_loop: using id for loop body {} {}", - expr.id, block_to_str(body)); + expr.id, block_to_string(body)); let cond_ln = self.propagate_through_opt_expr(cond, ln); let body_ln = self.with_loop_nodes(expr.id, succ, ln, |this| { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 96716ce09e0..33ab2ed3632 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -66,7 +66,7 @@ use middle::def; use middle::ty; use middle::typeck; use util::nodemap::NodeMap; -use util::ppaux::{ty_to_str, Repr}; +use util::ppaux::{ty_to_string, Repr}; use syntax::ast::{MutImmutable, MutMutable}; use syntax::ast; @@ -217,7 +217,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)).as_slice()); + ty_to_string(tcx, t)).as_slice()); } } } @@ -980,7 +980,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { // get the type of the *subpattern* and use that. debug!("cat_pattern: id={} pat={} cmt={}", - pat.id, pprust::pat_to_str(pat), + pat.id, pprust::pat_to_string(pat), cmt.repr(self.tcx())); op(self, cmt.clone(), pat); @@ -1105,7 +1105,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { Ok(()) } - pub fn cmt_to_str(&self, cmt: &cmt_) -> String { + pub fn cmt_to_string(&self, cmt: &cmt_) -> String { match cmt.cat { cat_static_item => { "static item".to_string() @@ -1151,10 +1151,10 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { "captured outer variable".to_string() } cat_discr(ref cmt, _) => { - self.cmt_to_str(&**cmt) + self.cmt_to_string(&**cmt) } cat_downcast(ref cmt) => { - self.cmt_to_str(&**cmt) + self.cmt_to_string(&**cmt) } } } @@ -1311,7 +1311,7 @@ impl Repr for InteriorKind { fn repr(&self, _tcx: &ty::ctxt) -> String { match *self { InteriorField(NamedField(fld)) => { - token::get_name(fld).get().to_str() + token::get_name(fld).get().to_string() } InteriorField(PositionalField(i)) => format!("#{:?}", i), InteriorElement(_) => "[]".to_string(), diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 76e962a3bc4..7630321bd55 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -375,7 +375,7 @@ enum FieldName { impl<'a> PrivacyVisitor<'a> { // used when debugging fn nodestr(&self, id: ast::NodeId) -> String { - self.tcx.map.node_to_str(id).to_string() + self.tcx.map.node_to_string(id).to_string() } // Determines whether the given definition is public from the point of view @@ -423,7 +423,7 @@ impl<'a> PrivacyVisitor<'a> { } debug!("privacy - local {} not public all the way down", - self.tcx.map.node_to_str(did.node)); + self.tcx.map.node_to_string(did.node)); // return quickly for things in the same module if self.parents.find(&did.node) == self.parents.find(&self.curitem) { debug!("privacy - same parent, we're done here"); diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 682dcb2b709..26bb0b62cb0 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -336,7 +336,7 @@ impl<'a> ReachableContext<'a> { .bug(format!("found unexpected thingy in worklist: {}", self.tcx .map - .node_to_str(search_item)).as_slice()) + .node_to_string(search_item)).as_slice()) } } } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 3b59736e292..df4d3b7efe4 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -821,7 +821,7 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor, body.id={}, \ cx.parent={})", id, - visitor.sess.codemap().span_to_str(sp), + visitor.sess.codemap().span_to_string(sp), body.id, cx.parent); diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 30a513407a5..129a5b7c6be 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -25,6 +25,7 @@ use syntax::ast; use syntax::ast_util::{local_def}; use syntax::ast_util::{walk_pat, trait_method_to_ty_method}; use syntax::ext::mtwt; +use syntax::parse::token::special_names; use syntax::parse::token::special_idents; use syntax::parse::token; use syntax::codemap::{Span, DUMMY_SP, Pos}; @@ -790,7 +791,7 @@ impl PrimitiveTypeTable { } -fn namespace_error_to_str(ns: NamespaceError) -> &'static str { +fn namespace_error_to_string(ns: NamespaceError) -> &'static str { match ns { NoError => "", ModuleError | TypeError => "type or module", @@ -830,9 +831,9 @@ struct Resolver<'a> { current_self_type: Option<Ty>, // The ident for the keyword "self". - self_ident: Ident, + self_name: Name, // The ident for the non-keyword "Self". - type_self_ident: Ident, + type_self_name: Name, // The idents for the primitive types. primitive_type_table: PrimitiveTypeTable, @@ -926,8 +927,8 @@ impl<'a> Resolver<'a> { current_trait_ref: None, current_self_type: None, - self_ident: special_idents::self_, - type_self_ident: special_idents::type_self, + self_name: special_names::self_, + type_self_name: special_names::type_self, primitive_type_table: PrimitiveTypeTable::new(), @@ -1071,14 +1072,14 @@ impl<'a> Resolver<'a> { let ns = ns.unwrap(); self.resolve_error(sp, format!("duplicate definition of {} `{}`", - namespace_error_to_str(duplicate_type), + namespace_error_to_string(duplicate_type), 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), + namespace_error_to_string(duplicate_type), token::get_ident(name)).as_slice()); } } @@ -1508,7 +1509,7 @@ impl<'a> Resolver<'a> { false, true)); debug!("(build reduced graph for item) found extern `{}`", - self.module_to_str(&*external_module)); + self.module_to_string(&*external_module)); parent.module().external_module_children.borrow_mut() .insert(name.name, external_module.clone()); self.build_reduced_graph_for_external_crate(external_module); @@ -1862,7 +1863,7 @@ impl<'a> Resolver<'a> { /// Builds the reduced graph rooted at the given external module. fn populate_external_module(&mut self, module: Rc<Module>) { debug!("(populating external module) attempting to populate {}", - self.module_to_str(&*module)); + self.module_to_string(&*module)); let def_id = match module.def_id.get() { None => { @@ -1930,7 +1931,7 @@ impl<'a> Resolver<'a> { SingleImport(target, _) => { debug!("(building import directive) building import \ directive: {}::{}", - self.idents_to_str(module_.imports.borrow().last().unwrap() + self.idents_to_string(module_.imports.borrow().last().unwrap() .module_path.as_slice()), token::get_ident(target)); @@ -2003,7 +2004,7 @@ impl<'a> Resolver<'a> { /// submodules. fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) { debug!("(resolving imports for module subtree) resolving {}", - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); let orig_module = replace(&mut self.current_module, module_.clone()); self.resolve_imports_for_module(module_.clone()); self.current_module = orig_module; @@ -2030,7 +2031,7 @@ impl<'a> Resolver<'a> { if module.all_imports_resolved() { debug!("(resolving imports for module) all imports resolved for \ {}", - self.module_to_str(&*module)); + self.module_to_string(&*module)); return; } @@ -2047,7 +2048,7 @@ impl<'a> Resolver<'a> { None => (import_directive.span, String::new()) }; let msg = format!("unresolved import `{}`{}", - self.import_path_to_str( + self.import_path_to_string( import_directive.module_path .as_slice(), import_directive.subclass), @@ -2063,7 +2064,7 @@ impl<'a> Resolver<'a> { } } - fn idents_to_str(&self, idents: &[Ident]) -> String { + fn idents_to_string(&self, idents: &[Ident]) -> String { let mut first = true; let mut result = String::new(); for ident in idents.iter() { @@ -2077,15 +2078,15 @@ impl<'a> Resolver<'a> { result } - fn path_idents_to_str(&self, path: &Path) -> String { + fn path_idents_to_string(&self, path: &Path) -> String { let identifiers: Vec<ast::Ident> = path.segments .iter() .map(|seg| seg.identifier) .collect(); - self.idents_to_str(identifiers.as_slice()) + self.idents_to_string(identifiers.as_slice()) } - fn import_directive_subclass_to_str(&mut self, + fn import_directive_subclass_to_string(&mut self, subclass: ImportDirectiveSubclass) -> String { match subclass { @@ -2096,16 +2097,16 @@ impl<'a> Resolver<'a> { } } - fn import_path_to_str(&mut self, + fn import_path_to_string(&mut self, idents: &[Ident], subclass: ImportDirectiveSubclass) -> String { if idents.is_empty() { - self.import_directive_subclass_to_str(subclass) + self.import_directive_subclass_to_string(subclass) } else { (format!("{}::{}", - self.idents_to_str(idents), - self.import_directive_subclass_to_str( + self.idents_to_string(idents), + self.import_directive_subclass_to_string( subclass))).to_string() } } @@ -2124,8 +2125,8 @@ impl<'a> Resolver<'a> { debug!("(resolving import for module) resolving import `{}::...` in \ `{}`", - self.idents_to_str(module_path.as_slice()), - self.module_to_str(&*module_)); + self.idents_to_string(module_path.as_slice()), + self.module_to_string(&*module_)); // First, resolve the module path for the directive, if necessary. let container = if module_path.len() == 0 { @@ -2231,9 +2232,9 @@ impl<'a> Resolver<'a> { debug!("(resolving single import) resolving `{}` = `{}::{}` from \ `{}` id {}, last private {:?}", token::get_ident(target), - self.module_to_str(&*containing_module), + self.module_to_string(&*containing_module), token::get_ident(source), - self.module_to_str(module_), + self.module_to_string(module_), directive.id, lp); @@ -2420,7 +2421,7 @@ impl<'a> Resolver<'a> { if value_result.is_unbound() && type_result.is_unbound() { let msg = format!("There is no `{}` in `{}`", token::get_ident(source), - self.module_to_str(&*containing_module)); + self.module_to_string(&*containing_module)); return Failed(Some((directive.span, msg))); } let value_used_public = value_used_reexport || value_used_public; @@ -2494,7 +2495,7 @@ impl<'a> Resolver<'a> { debug!("(resolving glob import) writing module resolution \ {:?} into `{}`", target_import_resolution.type_target.is_none(), - self.module_to_str(module_)); + self.module_to_string(module_)); if !target_import_resolution.is_public { debug!("(resolving glob import) nevermind, just kidding"); @@ -2590,9 +2591,9 @@ impl<'a> Resolver<'a> { debug!("(resolving glob import) writing resolution `{}` in `{}` \ to `{}`", - token::get_name(name).get().to_str(), - self.module_to_str(&*containing_module), - self.module_to_str(module_)); + token::get_name(name).get().to_string(), + self.module_to_string(&*containing_module), + self.module_to_string(module_)); // Merge the child item into the import resolution. if name_bindings.defined_in_public_namespace(ValueNS) { @@ -2652,7 +2653,7 @@ impl<'a> Resolver<'a> { false) { Failed(None) => { let segment_name = token::get_ident(name); - let module_name = self.module_to_str(&*search_module); + let module_name = self.module_to_string(&*search_module); let mut span = span; let msg = if "???" == module_name.as_slice() { span.hi = span.lo + Pos::from_uint(segment_name.get().len()); @@ -2660,10 +2661,10 @@ impl<'a> Resolver<'a> { match search_parent_externals(name.name, &self.current_module) { Some(module) => { - let path_str = self.idents_to_str(module_path); - let target_mod_str = self.module_to_str(&*module); + let path_str = self.idents_to_string(module_path); + let target_mod_str = self.module_to_string(&*module); let current_mod_str = - self.module_to_str(&*self.current_module); + self.module_to_string(&*self.current_module); let prefix = if target_mod_str == current_mod_str { "self::".to_string() @@ -2771,8 +2772,8 @@ impl<'a> Resolver<'a> { debug!("(resolving module path for import) processing `{}` rooted at \ `{}`", - self.idents_to_str(module_path), - self.module_to_str(&*module_)); + self.idents_to_string(module_path), + self.module_to_string(&*module_)); // Resolve the module prefix, if any. let module_prefix_result = self.resolve_module_prefix(module_.clone(), @@ -2783,7 +2784,7 @@ impl<'a> Resolver<'a> { let last_private; match module_prefix_result { Failed(None) => { - let mpath = self.idents_to_str(module_path); + let mpath = self.idents_to_string(module_path); let mpath = mpath.as_slice(); match mpath.rfind(':') { Some(idx) => { @@ -2865,7 +2866,7 @@ impl<'a> Resolver<'a> { namespace {:?} in `{}`", token::get_ident(name), namespace, - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); // The current module node is handled specially. First, check for // its immediate children. @@ -3098,7 +3099,7 @@ impl<'a> Resolver<'a> { break } debug!("(resolving module prefix) resolving `super` at {}", - self.module_to_str(&*containing_module)); + self.module_to_string(&*containing_module)); match self.get_nearest_normal_module_parent(containing_module) { None => return Failed(None), Some(new_module) => { @@ -3109,7 +3110,7 @@ impl<'a> Resolver<'a> { } debug!("(resolving module prefix) finished resolving prefix at {}", - self.module_to_str(&*containing_module)); + self.module_to_string(&*containing_module)); return Success(PrefixFound(containing_module, i)); } @@ -3129,7 +3130,7 @@ impl<'a> Resolver<'a> { -> ResolveResult<(Target, bool)> { debug!("(resolving name in module) resolving `{}` in `{}`", token::get_name(name).get(), - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); // First, check the direct children of the module. self.populate_module_if_necessary(&module_); @@ -3262,19 +3263,19 @@ impl<'a> Resolver<'a> { // OK. Continue. debug!("(recording exports for module subtree) recording \ exports for local module `{}`", - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); } None => { // Record exports for the root module. debug!("(recording exports for module subtree) recording \ exports for root module `{}`", - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); } Some(_) => { // Bail out. debug!("(recording exports for module subtree) not recording \ exports for `{}`", - self.module_to_str(&*module_)); + self.module_to_string(&*module_)); return; } } @@ -3390,7 +3391,7 @@ impl<'a> Resolver<'a> { None => { debug!("!!! (with scope) didn't find `{}` in `{}`", token::get_ident(name), - self.module_to_str(&*orig_module)); + self.module_to_string(&*orig_module)); } Some(name_bindings) => { match (*name_bindings).get_module_if_available() { @@ -3398,7 +3399,7 @@ impl<'a> Resolver<'a> { debug!("!!! (with scope) didn't find module \ for `{}` in `{}`", token::get_ident(name), - self.module_to_str(&*orig_module)); + self.module_to_string(&*orig_module)); } Some(module_) => { self.current_module = module_; @@ -3598,6 +3599,7 @@ impl<'a> Resolver<'a> { item.id, ItemRibKind), |this| { + this.resolve_type_parameters(&generics.ty_params); visit::walk_item(this, item, ()); }); } @@ -3623,12 +3625,12 @@ impl<'a> Resolver<'a> { methods.as_slice()); } - ItemTrait(ref generics, _, ref traits, ref methods) => { + ItemTrait(ref generics, ref unbound, ref traits, ref methods) => { // Create a new rib for the self type. let self_type_rib = Rib::new(ItemRibKind); - // plain insert (no renaming) - let name = self.type_self_ident.name; + // plain insert (no renaming, types are not currently hygienic....) + let name = self.type_self_name; self_type_rib.bindings.borrow_mut() .insert(name, DlDef(DefSelfTy(item.id))); self.type_ribs.borrow_mut().push(self_type_rib); @@ -3645,6 +3647,12 @@ impl<'a> Resolver<'a> { for trt in traits.iter() { this.resolve_trait_reference(item.id, trt, TraitDerivation); } + match unbound { + &Some(ast::TraitTyParamBound(ref tpb)) => { + this.resolve_trait_reference(item.id, tpb, TraitDerivation); + } + _ => {} + } for method in (*methods).iter() { // Create a new rib for the method-specific type @@ -3856,11 +3864,15 @@ impl<'a> Resolver<'a> { } fn resolve_type_parameters(&mut self, - type_parameters: &OwnedSlice<TyParam>) { + type_parameters: &OwnedSlice<TyParam>) { for type_parameter in type_parameters.iter() { for bound in type_parameter.bounds.iter() { self.resolve_type_parameter_bound(type_parameter.id, bound); } + match &type_parameter.unbound { + &Some(ref unbound) => self.resolve_type_parameter_bound(type_parameter.id, unbound), + &None => {} + } match type_parameter.default { Some(ref ty) => self.resolve_type(&**ty), None => {} @@ -3887,12 +3899,12 @@ impl<'a> Resolver<'a> { } fn resolve_trait_reference(&mut self, - id: NodeId, - trait_reference: &TraitRef, - reference_type: TraitReferenceType) { + id: NodeId, + trait_reference: &TraitRef, + reference_type: TraitReferenceType) { match self.resolve_path(id, &trait_reference.path, TypeNS, true) { None => { - let path_str = self.path_idents_to_str(&trait_reference.path); + let path_str = self.path_idents_to_string(&trait_reference.path); let usage_str = match reference_type { TraitBoundingTypeParameter => "bound type parameter with", TraitImplementation => "implement", @@ -3911,7 +3923,7 @@ impl<'a> Resolver<'a> { (def, _) => { self.resolve_error(trait_reference.path.span, format!("`{}` is not a trait", - self.path_idents_to_str( + self.path_idents_to_string( &trait_reference.path))); // If it's a typedef, give a note @@ -3959,7 +3971,7 @@ impl<'a> Resolver<'a> { .identifier), def); debug!("(resolving struct) writing resolution for `{}` (id {})", - this.path_idents_to_str(path), + this.path_idents_to_string(path), path_id); this.record_def(path_id, (def, lp)); } @@ -4071,7 +4083,7 @@ impl<'a> Resolver<'a> { let method_name = method.ident.name; if self.method_map.borrow().find(&(method_name, did)).is_none() { - let path_str = self.path_idents_to_str(&trait_ref.path); + let path_str = self.path_idents_to_string(&trait_ref.path); self.resolve_error(method.span, format!("method `{}` is not a member of trait `{}`", token::get_name(method_name), @@ -4281,13 +4293,13 @@ impl<'a> Resolver<'a> { // Write the result into the def map. debug!("(resolving type) writing resolution for `{}` \ (id {})", - self.path_idents_to_str(path), + self.path_idents_to_string(path), path_id); self.record_def(path_id, def); } None => { let msg = format!("use of undeclared type name `{}`", - self.path_idents_to_str(path)); + self.path_idents_to_string(path)); self.resolve_error(ty.span, msg.as_slice()); } } @@ -4488,7 +4500,7 @@ impl<'a> Resolver<'a> { debug!("(resolving pattern) didn't find struct \ def: {:?}", result); let msg = format!("`{}` does not name a structure", - self.path_idents_to_str(path)); + self.path_idents_to_string(path)); self.resolve_error(path.span, msg.as_slice()); } } @@ -4718,7 +4730,7 @@ impl<'a> Resolver<'a> { Some((span, msg)) => (span, msg), None => { let msg = format!("Use of undeclared module `{}`", - self.idents_to_str( + self.idents_to_string( module_path_idents.as_slice())); (path.span, msg) } @@ -4794,7 +4806,7 @@ impl<'a> Resolver<'a> { Some((span, msg)) => (span, msg), None => { let msg = format!("Use of undeclared module `::{}`", - self.idents_to_str( + self.idents_to_string( module_path_idents.as_slice())); (path.span, msg) } @@ -4999,7 +5011,7 @@ impl<'a> Resolver<'a> { match get_module(self, path.span, ident_path.as_slice()) { Some(module) => match module.children.borrow().find(&name) { Some(binding) => { - let p_str = self.path_idents_to_str(&path); + let p_str = self.path_idents_to_string(&path); match binding.def_for_namespace(ValueNS) { Some(DefStaticMethod(_, provenance, _)) => { match provenance { @@ -5021,7 +5033,7 @@ impl<'a> Resolver<'a> { let method_map = self.method_map.borrow(); match self.current_trait_ref { Some((did, ref trait_ref)) => { - let path_str = self.path_idents_to_str(&trait_ref.path); + let path_str = self.path_idents_to_string(&trait_ref.path); match method_map.find(&(name, did)) { Some(&SelfStatic) => return StaticTraitMethod(path_str), @@ -5094,7 +5106,7 @@ impl<'a> Resolver<'a> { Some(def) => { // Write the result into the def map. debug!("(resolving expr) resolved `{}`", - self.path_idents_to_str(path)); + self.path_idents_to_string(path)); // First-class methods are not supported yet; error // out here. @@ -5114,7 +5126,7 @@ impl<'a> Resolver<'a> { self.record_def(expr.id, def); } None => { - let wrong_name = self.path_idents_to_str(path); + let wrong_name = self.path_idents_to_string(path); // Be helpful if the name refers to a struct // (The pattern matching def_tys where the id is in self.structs // matches on regular structs while excluding tuple- and enum-like @@ -5148,8 +5160,8 @@ impl<'a> Resolver<'a> { false // Stop advancing }); - if method_scope && token::get_name(self.self_ident.name).get() - == wrong_name.as_slice() { + if method_scope && token::get_name(self.self_name).get() + == wrong_name.as_slice() { self.resolve_error( expr.span, "`self` is not available \ @@ -5210,7 +5222,7 @@ impl<'a> Resolver<'a> { debug!("(resolving expression) didn't find struct \ def: {:?}", result); let msg = format!("`{}` does not name a structure", - self.path_idents_to_str(path)); + self.path_idents_to_string(path)); self.resolve_error(path.span, msg.as_slice()); } } @@ -5510,7 +5522,7 @@ impl<'a> Resolver<'a> { // /// A somewhat inefficient routine to obtain the name of a module. - fn module_to_str(&self, module: &Module) -> String { + fn module_to_string(&self, module: &Module) -> String { let mut idents = Vec::new(); fn collect_mod(idents: &mut Vec<ast::Ident>, module: &Module) { @@ -5521,6 +5533,7 @@ impl<'a> Resolver<'a> { collect_mod(idents, &*module.upgrade().unwrap()); } BlockParentLink(ref module, _) => { + // danger, shouldn't be ident? idents.push(special_idents::opaque); collect_mod(idents, &*module.upgrade().unwrap()); } @@ -5531,14 +5544,14 @@ impl<'a> Resolver<'a> { if idents.len() == 0 { return "???".to_string(); } - self.idents_to_str(idents.move_iter().rev() + self.idents_to_string(idents.move_iter().rev() .collect::<Vec<ast::Ident>>() .as_slice()) } #[allow(dead_code)] // useful for debugging fn dump_module(&mut self, module_: Rc<Module>) { - debug!("Dump of module `{}`:", self.module_to_str(&*module_)); + debug!("Dump of module `{}`:", self.module_to_string(&*module_)); debug!("Children:"); self.populate_module_if_necessary(&module_); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 8ff5331cec2..1c85413a8d8 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -24,7 +24,7 @@ use syntax::codemap::Span; use syntax::owned_slice::OwnedSlice; use syntax::parse::token::special_idents; use syntax::parse::token; -use syntax::print::pprust::{lifetime_to_str}; +use syntax::print::pprust::{lifetime_to_string}; use syntax::visit; use syntax::visit::Visitor; use util::nodemap::NodeMap; @@ -372,7 +372,7 @@ impl<'a> LifetimeContext<'a> { } debug!("lifetime_ref={} id={} resolved to {:?}", - lifetime_to_str(lifetime_ref), + lifetime_to_string(lifetime_ref), lifetime_ref.id, def); self.named_region_map.insert(lifetime_ref.id, def); diff --git a/src/librustc/middle/save/mod.rs b/src/librustc/middle/save/mod.rs index 1bb5ffdccb5..d16e2bbf66b 100644 --- a/src/librustc/middle/save/mod.rs +++ b/src/librustc/middle/save/mod.rs @@ -51,7 +51,7 @@ use syntax::parse::token; use syntax::parse::token::{get_ident,keywords}; use syntax::visit; use syntax::visit::Visitor; -use syntax::print::pprust::{path_to_str,ty_to_str}; +use syntax::print::pprust::{path_to_string,ty_to_string}; use middle::save::span_utils::SpanUtils; use middle::save::recorder::Recorder; @@ -108,7 +108,7 @@ impl <'l> DxrVisitor<'l> { if spans.len() < path.segments.len() { error!("Mis-calculated spans for path '{}'. \ Found {} spans, expected {}. Found spans:", - path_to_str(path), spans.len(), path.segments.len()); + path_to_string(path), spans.len(), path.segments.len()); for s in spans.iter() { let loc = self.sess.codemap().lookup_char_pos(s.lo); error!(" '{}' in {}, line {}", @@ -126,7 +126,7 @@ impl <'l> DxrVisitor<'l> { let sub_path = ast::Path{span: *span, // span for the last segment global: path.global, segments: segs}; - let qualname = path_to_str(&sub_path); + let qualname = path_to_string(&sub_path); result.push((*span, qualname)); segs = sub_path.segments; } @@ -249,7 +249,7 @@ impl <'l> DxrVisitor<'l> { self.collecting = false; let span_utils = self.span; for &(id, ref p, _, _) in self.collected_paths.iter() { - let typ = ppaux::ty_to_str(&self.analysis.ty_cx, + let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *self.analysis.ty_cx.node_types.borrow().get(&(id as uint))); // get the span only for the name of the variable (I hope the path is only ever a // variable name, but who knows?) @@ -257,7 +257,7 @@ impl <'l> DxrVisitor<'l> { span_utils.span_for_last_ident(p.span), id, qualname, - path_to_str(p).as_slice(), + path_to_string(p).as_slice(), typ.as_slice()); } self.collected_paths.clear(); @@ -280,7 +280,7 @@ impl <'l> DxrVisitor<'l> { match item.node { ast::ItemImpl(_, _, ty, _) => { let mut result = String::from_str("<"); - result.push_str(ty_to_str(&*ty).as_slice()); + result.push_str(ty_to_string(&*ty).as_slice()); match ty::trait_of_method(&self.analysis.ty_cx, ast_util::local_def(method.id)) { @@ -400,7 +400,7 @@ impl <'l> DxrVisitor<'l> { ast::NamedField(ident, _) => { let name = get_ident(ident); let qualname = format!("{}::{}", qualname, name); - let typ = ppaux::ty_to_str(&self.analysis.ty_cx, + let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *self.analysis.ty_cx.node_types.borrow().get(&(field.node.id as uint))); match self.span.sub_span_before_token(field.span, token::COLON) { Some(sub_span) => self.fmt.field_str(field.span, @@ -452,7 +452,7 @@ impl <'l> DxrVisitor<'l> { decl: ast::P<ast::FnDecl>, ty_params: &ast::Generics, body: ast::P<ast::Block>) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Fn); self.fmt.fn_str(item.span, @@ -482,7 +482,7 @@ impl <'l> DxrVisitor<'l> { mt: ast::Mutability, expr: &ast::Expr) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); // If the variable is immutable, save the initialising expression. let value = match mt { @@ -497,7 +497,7 @@ impl <'l> DxrVisitor<'l> { get_ident(item.ident).get(), qualname.as_slice(), value.as_slice(), - ty_to_str(&*typ).as_slice(), + ty_to_string(&*typ).as_slice(), e.cur_scope); // walk type and init value @@ -510,7 +510,7 @@ impl <'l> DxrVisitor<'l> { e: DxrVisitorEnv, def: &ast::StructDef, ty_params: &ast::Generics) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); let ctor_id = match def.ctor_id { Some(node_id) => node_id, @@ -538,7 +538,7 @@ impl <'l> DxrVisitor<'l> { e: DxrVisitorEnv, enum_definition: &ast::EnumDef, ty_params: &ast::Generics) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); match self.span.sub_span_after_keyword(item.span, keywords::Enum) { Some(sub_span) => self.fmt.enum_str(item.span, Some(sub_span), @@ -639,7 +639,7 @@ impl <'l> DxrVisitor<'l> { generics: &ast::Generics, trait_refs: &Vec<ast::TraitRef>, methods: &Vec<ast::TraitMethod>) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait); self.fmt.trait_str(item.span, @@ -678,7 +678,7 @@ impl <'l> DxrVisitor<'l> { item: &ast::Item, // The module in question, represented as an item. e: DxrVisitorEnv, m: &ast::Mod) { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); let cm = self.sess.codemap(); let filename = cm.span_to_filename(m.inner); @@ -971,8 +971,8 @@ impl<'l> Visitor<DxrVisitorEnv> for DxrVisitor<'l> { self.process_trait(item, e, generics, trait_refs, methods), ast::ItemMod(ref m) => self.process_mod(item, e, m), ast::ItemTy(ty, ref ty_params) => { - let qualname = self.analysis.ty_cx.map.path_to_str(item.id); - let value = ty_to_str(&*ty); + let qualname = self.analysis.ty_cx.map.path_to_string(item.id); + let value = ty_to_string(&*ty); let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Type); self.fmt.typedef_str(item.span, sub_span, @@ -1231,7 +1231,7 @@ impl<'l> Visitor<DxrVisitorEnv> for DxrVisitor<'l> { return } - let id = String::from_str("$").append(ex.id.to_str().as_slice()); + let id = String::from_str("$").append(ex.id.to_string().as_slice()); self.process_formals(&decl.inputs, id.as_slice(), e); // walk arg and return types @@ -1288,7 +1288,7 @@ impl<'l> Visitor<DxrVisitorEnv> for DxrVisitor<'l> { def::DefBinding(id, _) => self.fmt.variable_str(p.span, sub_span, id, - path_to_str(p).as_slice(), + path_to_string(p).as_slice(), value.as_slice(), ""), def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind, @@ -1331,7 +1331,7 @@ impl<'l> Visitor<DxrVisitorEnv> for DxrVisitor<'l> { for &(id, ref p, ref immut, _) in self.collected_paths.iter() { let value = if *immut { value.to_owned() } else { "<mutable>".to_owned() }; let types = self.analysis.ty_cx.node_types.borrow(); - let typ = ppaux::ty_to_str(&self.analysis.ty_cx, *types.get(&(id as uint))); + let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint))); // Get the span only for the name of the variable (I hope the path // is only ever a variable name, but who knows?). let sub_span = self.span.span_for_last_ident(p.span); @@ -1339,7 +1339,7 @@ impl<'l> Visitor<DxrVisitorEnv> for DxrVisitor<'l> { self.fmt.variable_str(p.span, sub_span, id, - path_to_str(p).as_slice(), + path_to_string(p).as_slice(), value.as_slice(), typ.as_slice()); } diff --git a/src/librustc/middle/save/recorder.rs b/src/librustc/middle/save/recorder.rs index fd76d6d37d1..7869aec1683 100644 --- a/src/librustc/middle/save/recorder.rs +++ b/src/librustc/middle/save/recorder.rs @@ -252,7 +252,7 @@ impl<'a> FmtStrs<'a> { // the local case they can be overridden in one block and there is no nice way // to refer to such a scope in english, so we just hack it by appending the // variable def's node id - let qualname = String::from_str(name).append("$").append(id.to_str().as_slice()); + let qualname = String::from_str(name).append("$").append(id.to_string().as_slice()); self.check_and_record(Variable, span, sub_span, diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 11d09aa49cf..3cfd1aaee8f 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -214,7 +214,7 @@ use middle::trans::type_of; use middle::trans::debuginfo; use middle::ty; use util::common::indenter; -use util::ppaux::{Repr, vec_map_to_str}; +use util::ppaux::{Repr, vec_map_to_string}; use std; use std::collections::HashMap; @@ -409,7 +409,7 @@ fn expand_nested_bindings<'a, 'b>( bcx.to_str(), m.repr(bcx.tcx()), col, - bcx.val_to_str(val)); + bcx.val_to_string(val)); let _indenter = indenter(); m.iter().map(|br| { @@ -449,7 +449,7 @@ fn enter_match<'a, 'b>( bcx.to_str(), m.repr(bcx.tcx()), col, - bcx.val_to_str(val)); + bcx.val_to_string(val)); let _indenter = indenter(); m.iter().filter_map(|br| { @@ -485,7 +485,7 @@ fn enter_default<'a, 'b>( bcx.to_str(), m.repr(bcx.tcx()), col, - bcx.val_to_str(val)); + bcx.val_to_string(val)); let _indenter = indenter(); // Collect all of the matches that can match against anything. @@ -541,7 +541,7 @@ fn enter_opt<'a, 'b>( m.repr(bcx.tcx()), *opt, col, - bcx.val_to_str(val)); + bcx.val_to_string(val)); let _indenter = indenter(); let ctor = match opt { @@ -922,7 +922,7 @@ fn compare_values<'a>( let did = langcall(cx, None, format!("comparison of `{}`", - cx.ty_to_str(rhs_t)).as_slice(), + cx.ty_to_string(rhs_t)).as_slice(), StrEqFnLangItem); callee::trans_lang_call(cx, did, [lhs, rhs], None) } @@ -988,7 +988,7 @@ fn insert_lllocals<'a>(mut bcx: &'a Block<'a>, bindings_map: &BindingsMap, debug!("binding {:?} to {}", binding_info.id, - bcx.val_to_str(llval)); + bcx.val_to_string(llval)); bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum); if bcx.sess().opts.debuginfo == FullDebugInfo { @@ -1011,9 +1011,9 @@ fn compile_guard<'a, 'b>( -> &'b Block<'b> { debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})", bcx.to_str(), - bcx.expr_to_str(guard_expr), + bcx.expr_to_string(guard_expr), m.repr(bcx.tcx()), - vec_map_to_str(vals, |v| bcx.val_to_str(*v))); + vec_map_to_string(vals, |v| bcx.val_to_string(*v))); let _indenter = indenter(); let mut bcx = insert_lllocals(bcx, &data.bindings_map, None); @@ -1050,7 +1050,7 @@ fn compile_submatch<'a, 'b>( debug!("compile_submatch(bcx={}, m={}, vals={})", bcx.to_str(), m.repr(bcx.tcx()), - vec_map_to_str(vals, |v| bcx.val_to_str(*v))); + vec_map_to_string(vals, |v| bcx.val_to_string(*v))); let _indenter = indenter(); let _icx = push_ctxt("match::compile_submatch"); let mut bcx = bcx; @@ -1155,7 +1155,7 @@ fn compile_submatch_continue<'a, 'b>( debug!("options={:?}", opts); let mut kind = no_branch; let mut test_val = val; - debug!("test_val={}", bcx.val_to_str(test_val)); + debug!("test_val={}", bcx.val_to_string(test_val)); if opts.len() > 0u { match *opts.get(0) { var(_, ref repr, _) => { diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 4c7db01657b..898cb036ea5 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -63,7 +63,7 @@ use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel}; use syntax::ast; use syntax::attr; use syntax::attr::IntType; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; type Hint = attr::ReprAttr; @@ -135,7 +135,7 @@ pub fn represent_node(bcx: &Block, node: ast::NodeId) -> Rc<Repr> { /// Decides how to represent a given type. pub fn represent_type(cx: &CrateContext, t: ty::t) -> Rc<Repr> { - debug!("Representing: {}", ty_to_str(cx.tcx(), t)); + debug!("Representing: {}", ty_to_string(cx.tcx(), t)); match cx.adt_reprs.borrow().find(&t) { Some(repr) => return repr.clone(), None => {} diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 08cdde38c34..84b253306ff 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -71,7 +71,7 @@ use middle::trans::value::Value; use middle::ty; use middle::typeck; use util::common::indenter; -use util::ppaux::{Repr, ty_to_str}; +use util::ppaux::{Repr, ty_to_string}; use util::sha2::Sha256; use util::nodemap::NodeMap; @@ -301,7 +301,7 @@ 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), + bcx.ty_to_string(info_ty), s).as_slice()); } } @@ -706,7 +706,7 @@ pub fn iter_structural_ty<'r, let variant_cx = fcx.new_temp_block( format!("enum-iter-variant-{}", - variant.disr_val.to_str().as_slice()) + variant.disr_val.to_string().as_slice()) .as_slice()); match adt::trans_case(cx, &*repr, variant.disr_val) { _match::single_result(r) => { @@ -809,7 +809,7 @@ pub fn fail_if_zero_or_overflows<'a>( } _ => { cx.sess().bug(format!("fail-if-zero on unexpected type: {}", - ty_to_str(cx.tcx(), rhs_t)).as_slice()); + ty_to_string(cx.tcx(), rhs_t)).as_slice()); } }; let bcx = with_cond(cx, is_zero, |bcx| { @@ -903,7 +903,7 @@ pub fn invoke<'a>( debug!("invoke at ???"); } Some(id) => { - debug!("invoke at {}", bcx.tcx().map.node_to_str(id)); + debug!("invoke at {}", bcx.tcx().map.node_to_string(id)); } } @@ -1173,7 +1173,7 @@ pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext, if id == -1 { "".to_string() } else { - ccx.tcx.map.path_to_str(id).to_string() + ccx.tcx.map.path_to_string(id).to_string() }, id, param_substs.repr(ccx.tcx())); @@ -1474,7 +1474,7 @@ pub fn trans_fn(ccx: &CrateContext, param_substs: ¶m_substs, id: ast::NodeId, attrs: &[ast::Attribute]) { - let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_string()); + let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string()); debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx())); let _icx = push_ctxt("trans_fn"); let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id)); @@ -1527,7 +1527,7 @@ fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext, _ => ccx.sess().bug( format!("trans_enum_variant_or_tuple_like_struct: \ unexpected ctor return type {}", - ty_to_str(ccx.tcx(), ctor_ty)).as_slice()) + ty_to_string(ccx.tcx(), ctor_ty)).as_slice()) }; let arena = TypedArena::new(); @@ -2010,7 +2010,7 @@ fn exported_name(ccx: &CrateContext, id: ast::NodeId, _ => ccx.tcx.map.with_path(id, |mut path| { if attr::contains_name(attrs, "no_mangle") { // Don't mangle - path.last().unwrap().to_str() + path.last().unwrap().to_string() } else { match weak_lang_items::link_name(attrs) { Some(name) => name.get().to_string(), diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index e1c02f543bf..ce11cd24f7b 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -122,8 +122,8 @@ pub fn Invoke(cx: &Block, check_not_terminated(cx); terminate(cx, "Invoke"); debug!("Invoke({} with arguments ({}))", - cx.val_to_str(fn_), - args.iter().map(|a| cx.val_to_str(*a)).collect::<Vec<String>>().connect(", ")); + cx.val_to_string(fn_), + args.iter().map(|a| cx.val_to_string(*a)).collect::<Vec<String>>().connect(", ")); B(cx).invoke(fn_, args, then, catch, attributes) } diff --git a/src/librustc/middle/trans/builder.rs b/src/librustc/middle/trans/builder.rs index a9c1adac3d7..3a9e3e4cf9b 100644 --- a/src/librustc/middle/trans/builder.rs +++ b/src/librustc/middle/trans/builder.rs @@ -161,9 +161,9 @@ impl<'a> Builder<'a> { self.count_insn("invoke"); debug!("Invoke {} with args ({})", - self.ccx.tn.val_to_str(llfn), + self.ccx.tn.val_to_string(llfn), args.iter() - .map(|&v| self.ccx.tn.val_to_str(v)) + .map(|&v| self.ccx.tn.val_to_string(v)) .collect::<Vec<String>>() .connect(", ")); @@ -497,8 +497,8 @@ impl<'a> Builder<'a> { pub fn store(&self, val: ValueRef, ptr: ValueRef) { debug!("Store {} -> {}", - self.ccx.tn.val_to_str(val), - self.ccx.tn.val_to_str(ptr)); + self.ccx.tn.val_to_string(val), + self.ccx.tn.val_to_string(ptr)); assert!(self.llbuilder.is_not_null()); self.count_insn("store"); unsafe { @@ -508,8 +508,8 @@ impl<'a> Builder<'a> { pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) { debug!("Store {} -> {}", - self.ccx.tn.val_to_str(val), - self.ccx.tn.val_to_str(ptr)); + self.ccx.tn.val_to_string(val), + self.ccx.tn.val_to_string(ptr)); assert!(self.llbuilder.is_not_null()); self.count_insn("store.volatile"); unsafe { @@ -520,8 +520,8 @@ impl<'a> Builder<'a> { pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) { debug!("Store {} -> {}", - self.ccx.tn.val_to_str(val), - self.ccx.tn.val_to_str(ptr)); + self.ccx.tn.val_to_string(val), + self.ccx.tn.val_to_string(ptr)); self.count_insn("store.atomic"); unsafe { let ty = Type::from_ref(llvm::LLVMTypeOf(ptr)); @@ -760,7 +760,7 @@ impl<'a> Builder<'a> { if self.ccx.sess().asm_comments() { let s = format!("{} ({})", text, - self.ccx.sess().codemap().span_to_str(sp)); + self.ccx.sess().codemap().span_to_string(sp)); debug!("{}", s.as_slice()); self.add_comment(s.as_slice()); } @@ -794,11 +794,11 @@ impl<'a> Builder<'a> { else { lib::llvm::False }; let argtys = inputs.iter().map(|v| { - debug!("Asm Input Type: {:?}", self.ccx.tn.val_to_str(*v)); + debug!("Asm Input Type: {:?}", self.ccx.tn.val_to_string(*v)); val_ty(*v) }).collect::<Vec<_>>(); - debug!("Asm Output Type: {:?}", self.ccx.tn.type_to_str(output)); + debug!("Asm Output Type: {:?}", self.ccx.tn.type_to_string(output)); let fty = Type::func(argtys.as_slice(), &output); unsafe { let v = llvm::LLVMInlineAsm( @@ -812,9 +812,9 @@ impl<'a> Builder<'a> { self.count_insn("call"); debug!("Call {} with args ({})", - self.ccx.tn.val_to_str(llfn), + self.ccx.tn.val_to_string(llfn), args.iter() - .map(|&v| self.ccx.tn.val_to_str(v)) + .map(|&v| self.ccx.tn.val_to_string(v)) .collect::<Vec<String>>() .connect(", ")); diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index c5361045549..2e4a3d9fd7e 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -108,7 +108,7 @@ fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> { expr.span, format!("type of callee is neither bare-fn nor closure: \ {}", - bcx.ty_to_str(datum.ty)).as_slice()); + bcx.ty_to_string(datum.ty)).as_slice()); } } } @@ -905,7 +905,7 @@ pub fn trans_arg_datum<'a>( let arg_datum_ty = arg_datum.ty; - debug!(" arg datum: {}", arg_datum.to_str(bcx.ccx())); + debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx())); let mut val; if ty::type_is_bot(arg_datum_ty) { @@ -949,11 +949,11 @@ pub fn trans_arg_datum<'a>( // this could happen due to e.g. subtyping let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty); debug!("casting actual type ({}) to match formal ({})", - bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty)); + bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty)); val = PointerCast(bcx, val, llformal_arg_ty); } } - debug!("--- trans_arg_datum passing {}", bcx.val_to_str(val)); + debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val)); Result::new(bcx, val) } diff --git a/src/librustc/middle/trans/cleanup.rs b/src/librustc/middle/trans/cleanup.rs index 0bcf94997cd..0485b100446 100644 --- a/src/librustc/middle/trans/cleanup.rs +++ b/src/librustc/middle/trans/cleanup.rs @@ -85,7 +85,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { */ debug!("push_ast_cleanup_scope({})", - self.ccx.tcx.map.node_to_str(id)); + self.ccx.tcx.map.node_to_string(id)); // FIXME(#2202) -- currently closure bodies have a parent // region, which messes up the assertion below, since there @@ -109,7 +109,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { id: ast::NodeId, exits: [&'a Block<'a>, ..EXIT_MAX]) { debug!("push_loop_cleanup_scope({})", - self.ccx.tcx.map.node_to_str(id)); + self.ccx.tcx.map.node_to_string(id)); assert_eq!(Some(id), self.top_ast_scope()); self.push_scope(CleanupScope::new(LoopScopeKind(id, exits))); @@ -133,7 +133,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { */ debug!("pop_and_trans_ast_cleanup_scope({})", - self.ccx.tcx.map.node_to_str(cleanup_scope)); + self.ccx.tcx.map.node_to_string(cleanup_scope)); assert!(self.top_scope(|s| s.kind.is_ast_with_id(cleanup_scope))); @@ -152,7 +152,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { */ debug!("pop_loop_cleanup_scope({})", - self.ccx.tcx.map.node_to_str(cleanup_scope)); + self.ccx.tcx.map.node_to_string(cleanup_scope)); assert!(self.top_scope(|s| s.kind.is_loop_with_id(cleanup_scope))); @@ -246,7 +246,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { debug!("schedule_drop_mem({:?}, val={}, ty={})", cleanup_scope, - self.ccx.tn.val_to_str(val), + self.ccx.tn.val_to_string(val), ty.repr(self.ccx.tcx())); self.schedule_clean(cleanup_scope, drop as Box<Cleanup>); @@ -272,7 +272,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { debug!("schedule_drop_and_zero_mem({:?}, val={}, ty={}, zero={})", cleanup_scope, - self.ccx.tn.val_to_str(val), + self.ccx.tn.val_to_string(val), ty.repr(self.ccx.tcx()), true); @@ -298,7 +298,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { debug!("schedule_drop_immediate({:?}, val={}, ty={})", cleanup_scope, - self.ccx.tn.val_to_str(val), + self.ccx.tn.val_to_string(val), ty.repr(self.ccx.tcx())); self.schedule_clean(cleanup_scope, drop as Box<Cleanup>); @@ -318,7 +318,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> { debug!("schedule_free_value({:?}, val={}, heap={:?})", cleanup_scope, - self.ccx.tn.val_to_str(val), + self.ccx.tn.val_to_string(val), heap); self.schedule_clean(cleanup_scope, drop as Box<Cleanup>); @@ -358,7 +358,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)).as_slice()); + self.ccx.tcx.map.node_to_string(cleanup_scope)).as_slice()); } fn schedule_clean_in_custom_scope(&self, diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index b2564936fa4..ef147eb22b5 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -27,7 +27,7 @@ use middle::trans::type_of::*; use middle::trans::type_::Type; use middle::ty; use util::ppaux::Repr; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; use arena::TypedArena; use syntax::ast; @@ -104,8 +104,8 @@ pub struct EnvValue { } impl EnvValue { - pub fn to_str(&self, ccx: &CrateContext) -> String { - format!("{}({})", self.action, self.datum.to_str(ccx)) + pub fn to_string(&self, ccx: &CrateContext) -> String { + format!("{}({})", self.action, self.datum.to_string(ccx)) } } @@ -124,7 +124,7 @@ pub fn mk_closure_tys(tcx: &ty::ctxt, } }).collect(); let cdata_ty = ty::mk_tup(tcx, bound_tys); - debug!("cdata_ty={}", ty_to_str(tcx, cdata_ty)); + debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty)); return cdata_ty; } @@ -196,16 +196,16 @@ pub fn store_environment<'a>( let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty); let llbox = PointerCast(bcx, llbox, llboxptr_ty); - debug!("tuplify_box_ty = {}", ty_to_str(tcx, cbox_ty)); + debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty)); // Copy expr values into boxed bindings. let mut bcx = bcx; for (i, bv) in bound_values.move_iter().enumerate() { - debug!("Copy {} into closure", bv.to_str(ccx)); + debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { add_comment(bcx, format!("Copy {} into closure", - bv.to_str(ccx)).as_slice()); + bv.to_string(ccx)).as_slice()); } let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]); diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index de5de64e346..23a391cb86d 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -196,13 +196,13 @@ impl param_substs { } } -fn param_substs_to_str(this: ¶m_substs, tcx: &ty::ctxt) -> String { +fn param_substs_to_string(this: ¶m_substs, tcx: &ty::ctxt) -> String { format!("param_substs({})", this.substs.repr(tcx)) } impl Repr for param_substs { fn repr(&self, tcx: &ty::ctxt) -> String { - param_substs_to_str(self, tcx) + param_substs_to_string(self, tcx) } } @@ -436,11 +436,11 @@ impl<'a> Block<'a> { token::get_ident(ident).get().to_string() } - pub fn node_id_to_str(&self, id: ast::NodeId) -> String { - self.tcx().map.node_to_str(id).to_string() + pub fn node_id_to_string(&self, id: ast::NodeId) -> String { + self.tcx().map.node_to_string(id).to_string() } - pub fn expr_to_str(&self, e: &ast::Expr) -> String { + pub fn expr_to_string(&self, e: &ast::Expr) -> String { e.repr(self.tcx()) } @@ -454,15 +454,15 @@ impl<'a> Block<'a> { } } - pub fn val_to_str(&self, val: ValueRef) -> String { - self.ccx().tn.val_to_str(val) + pub fn val_to_string(&self, val: ValueRef) -> String { + self.ccx().tn.val_to_string(val) } pub fn llty_str(&self, ty: Type) -> String { - self.ccx().tn.type_to_str(ty) + self.ccx().tn.type_to_string(ty) } - pub fn ty_to_str(&self, t: ty::t) -> String { + pub fn ty_to_string(&self, t: ty::t) -> String { t.repr(self.tcx()) } @@ -645,7 +645,7 @@ pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint]) let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); debug!("const_get_elt(v={}, us={:?}, r={})", - cx.tn.val_to_str(v), us, cx.tn.val_to_str(r)); + cx.tn.val_to_string(v), us, cx.tn.val_to_string(r)); return r; } diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 52a097ca6f0..11a8207f8c4 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -31,7 +31,7 @@ use middle::trans::type_::Type; use middle::trans::type_of; use middle::trans::debuginfo; use middle::ty; -use util::ppaux::{Repr, ty_to_str}; +use util::ppaux::{Repr, ty_to_string}; use std::c_str::ToCStr; use std::gc::Gc; @@ -42,6 +42,7 @@ use syntax::{ast, ast_util}; pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit) -> ValueRef { let _icx = push_ctxt("trans_lit"); + debug!("const_lit: {}", lit); match lit.node { ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false), ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false), @@ -59,7 +60,7 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit) _ => cx.sess().span_bug(lit.span, format!("integer literal has type {} (expected int \ or uint)", - ty_to_str(cx.tcx(), lit_int_ty)).as_slice()) + ty_to_string(cx.tcx(), lit_int_ty)).as_slice()) } } ast::LitFloat(ref fs, t) => { @@ -155,14 +156,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)).as_slice()) + ty_to_string(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)).as_slice()) + ty_to_string(cx.tcx(), t)).as_slice()) } } } @@ -285,7 +286,7 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef llvm::LLVMDumpValue(C_undef(llty)); } cx.sess().bug(format!("const {} of type {} has size {} instead of {}", - e.repr(cx.tcx()), ty_to_str(cx.tcx(), ety), + e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety), csize, tsize).as_slice()); } (llconst, inlineable) diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index e9b1c56eb00..acc44d08d3c 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -126,8 +126,8 @@ pub fn trans_if<'a>(bcx: &'a Block<'a>, dest: expr::Dest) -> &'a Block<'a> { debug!("trans_if(bcx={}, if_id={}, cond={}, thn={:?}, dest={})", - bcx.to_str(), if_id, bcx.expr_to_str(cond), thn.id, - dest.to_str(bcx.ccx())); + bcx.to_str(), if_id, bcx.expr_to_string(cond), thn.id, + dest.to_string(bcx.ccx())); let _icx = push_ctxt("trans_if"); let mut bcx = bcx; diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index b93469ad2fb..b65f5a5c7d6 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -23,7 +23,7 @@ use middle::trans::glue; use middle::trans::tvec; use middle::trans::type_of; use middle::ty; -use util::ppaux::{ty_to_str}; +use util::ppaux::{ty_to_string}; use syntax::ast; @@ -596,10 +596,10 @@ impl<K:KindOps> Datum<K> { } #[allow(dead_code)] // useful for debugging - pub fn to_str(&self, ccx: &CrateContext) -> String { + pub fn to_string(&self, ccx: &CrateContext) -> String { format!("Datum({}, {}, {:?})", - ccx.tn.val_to_str(self.val), - ty_to_str(ccx.tcx(), self.ty), + ccx.tn.val_to_string(self.val), + ty_to_string(ccx.tcx(), self.ty), self.kind) } diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index f281d8e2448..9acd0487199 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -270,7 +270,7 @@ impl TypeMap { metadata: DIType) { if !self.type_to_metadata.insert(ty::type_id(type_), metadata) { cx.sess().bug(format!("Type metadata for ty::t '{}' is already in the TypeMap!", - ppaux::ty_to_str(cx.tcx(), type_)).as_slice()); + ppaux::ty_to_string(cx.tcx(), type_)).as_slice()); } } @@ -504,7 +504,7 @@ impl TypeMap { }, _ => { cx.sess().bug(format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}", - ppaux::ty_to_str(cx.tcx(), type_).as_slice(), + ppaux::ty_to_string(cx.tcx(), type_).as_slice(), ty::get(type_).sty).as_slice()) } }; @@ -808,7 +808,7 @@ pub fn create_global_var_metadata(cx: &CrateContext, let type_metadata = type_metadata(cx, variable_type, span); let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id)); - let var_name = token::get_ident(ident).get().to_str(); + let var_name = token::get_ident(ident).get().to_string(); let linkage_name = namespace_node.mangled_name_of_contained_item(var_name.as_slice()); let var_scope = namespace_node.scope; @@ -1056,7 +1056,7 @@ pub fn set_source_location(fcx: &FunctionContext, FunctionDebugContext(box ref function_debug_context) => { let cx = fcx.ccx; - debug!("set_source_location: {}", cx.sess().codemap().span_to_str(span)); + debug!("set_source_location: {}", cx.sess().codemap().span_to_string(span)); if function_debug_context.source_locations_enabled.get() { let loc = span_start(cx, span); @@ -1812,7 +1812,7 @@ impl RecursiveTypeDescription { type_map.find_metadata_for_type(unfinished_type).is_none() { cx.sess().bug(format!("Forward declaration of potentially recursive type \ '{}' was not found in TypeMap!", - ppaux::ty_to_str(cx.tcx(), unfinished_type)) + ppaux::ty_to_string(cx.tcx(), unfinished_type)) .as_slice()); } } @@ -2245,7 +2245,7 @@ fn describe_enum_variant(cx: &CrateContext, Some(ref names) => { names.iter() .map(|ident| { - token::get_ident(*ident).get().to_str().into_string() + token::get_ident(*ident).get().to_string().into_string() }).collect() } None => variant_info.args.iter().map(|_| "".to_string()).collect() @@ -2872,7 +2872,7 @@ fn trait_pointer_metadata(cx: &CrateContext, ty::ty_uniq(pointee_type) => pointee_type, ty::ty_rptr(_, ty::mt { ty, .. }) => ty, _ => { - let pp_type_name = ppaux::ty_to_str(cx.tcx(), trait_pointer_type); + let pp_type_name = ppaux::ty_to_string(cx.tcx(), trait_pointer_type); cx.sess().bug(format!("debuginfo: Unexpected trait-pointer type in \ trait_pointer_metadata(): {}", pp_type_name.as_slice()).as_slice()); @@ -2882,7 +2882,7 @@ fn trait_pointer_metadata(cx: &CrateContext, let def_id = match ty::get(trait_object_type).sty { ty::ty_trait(box ty::TyTrait { def_id, .. }) => def_id, _ => { - let pp_type_name = ppaux::ty_to_str(cx.tcx(), trait_object_type); + let pp_type_name = ppaux::ty_to_string(cx.tcx(), trait_object_type); cx.sess().bug(format!("debuginfo: Unexpected trait-object type in \ trait_pointer_metadata(): {}", pp_type_name.as_slice()).as_slice()); @@ -3064,7 +3064,7 @@ fn type_metadata(cx: &CrateContext, the debuginfo::TypeMap but it \ was not. (ty::t = {})", unique_type_id_str.as_slice(), - ppaux::ty_to_str(cx.tcx(), t)); + ppaux::ty_to_string(cx.tcx(), t)); cx.sess().span_bug(usage_site_span, error_message.as_slice()); } }; @@ -3079,7 +3079,7 @@ fn type_metadata(cx: &CrateContext, debuginfo::TypeMap. \ UniqueTypeId={}, ty::t={}", unique_type_id_str.as_slice(), - ppaux::ty_to_str(cx.tcx(), t)); + ppaux::ty_to_string(cx.tcx(), t)); cx.sess().span_bug(usage_site_span, error_message.as_slice()); } } @@ -3879,7 +3879,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, ty::ty_infer(_) | ty::ty_param(_) => { cx.sess().bug(format!("debuginfo: Trying to create type name for \ - unexpected type: {}", ppaux::ty_to_str(cx.tcx(), t)).as_slice()); + unexpected type: {}", ppaux::ty_to_string(cx.tcx(), t)).as_slice()); } } diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 85e85f8ab55..516c46564cd 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -75,7 +75,7 @@ use middle::trans::type_::Type; use syntax::ast; use syntax::codemap; -use syntax::print::pprust::{expr_to_str}; +use syntax::print::pprust::{expr_to_string}; use std::gc::Gc; @@ -91,9 +91,9 @@ pub enum Dest { } impl Dest { - pub fn to_str(&self, ccx: &CrateContext) -> String { + pub fn to_string(&self, ccx: &CrateContext) -> String { match *self { - SaveIn(v) => format!("SaveIn({})", ccx.tn.val_to_str(v)), + SaveIn(v) => format!("SaveIn({})", ccx.tn.val_to_string(v)), Ignore => "Ignore".to_string() } } @@ -148,7 +148,7 @@ pub fn trans<'a>(bcx: &'a Block<'a>, * the stack. */ - debug!("trans(expr={})", bcx.expr_to_str(expr)); + debug!("trans(expr={})", bcx.expr_to_string(expr)); let mut bcx = bcx; let fcx = bcx.fcx; @@ -178,7 +178,7 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, Some(adj) => { adj } }; debug!("unadjusted datum for expr {}: {}", - expr.id, datum.to_str(bcx.ccx())); + expr.id, datum.to_string(bcx.ccx())); match adjustment { AutoAddEnv(..) => { datum = unpack_datum!(bcx, add_env(bcx, expr, datum)); @@ -216,7 +216,7 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, datum = scratch.to_expr_datum(); } } - debug!("after adjustments, datum={}", datum.to_str(bcx.ccx())); + debug!("after adjustments, datum={}", datum.to_string(bcx.ccx())); return DatumBlock {bcx: bcx, datum: datum}; fn auto_slice<'a>( @@ -325,7 +325,7 @@ fn trans_unadjusted<'a>(bcx: &'a Block<'a>, let mut bcx = bcx; - debug!("trans_unadjusted(expr={})", bcx.expr_to_str(expr)); + debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr)); let _indenter = indenter(); debuginfo::set_source_location(bcx.fcx, expr.id, expr.span); @@ -545,8 +545,8 @@ fn trans_index<'a>(bcx: &'a Block<'a>, let (base, len) = base_datum.get_vec_base_and_len(bcx); - debug!("trans_index: base {}", bcx.val_to_str(base)); - debug!("trans_index: len {}", bcx.val_to_str(len)); + debug!("trans_index: base {}", bcx.val_to_string(base)); + debug!("trans_index: len {}", bcx.val_to_string(len)); let bounds_check = ICmp(bcx, lib::llvm::IntUGE, ix_val, len); let expect = ccx.get_intrinsic(&("llvm.expect.i1")); @@ -780,7 +780,7 @@ fn trans_rvalue_dps_unadjusted<'a>(bcx: &'a Block<'a>, let expr_ty = expr_ty(bcx, expr); let store = ty::ty_closure_store(expr_ty); debug!("translating block function {} with type {}", - expr_to_str(expr), expr_ty.repr(tcx)); + expr_to_string(expr), expr_ty.repr(tcx)); closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest) } ast::ExprCall(ref f, ref args) => { @@ -893,7 +893,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)).as_slice()); + def, bcx.node_id_to_string(ref_expr.id)).as_slice()); } } } @@ -974,7 +974,7 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>, } }; debug!("take_local(nid={:?}, v={}, ty={})", - nid, bcx.val_to_str(datum.val), bcx.ty_to_str(datum.ty)); + nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty)); datum } } @@ -1462,13 +1462,13 @@ fn trans_binary<'a>(bcx: &'a Block<'a>, debug!("trans_binary (expr {}): lhs_datum={}", expr.id, - lhs_datum.to_str(ccx)); + lhs_datum.to_string(ccx)); let lhs_ty = lhs_datum.ty; let lhs = lhs_datum.to_llscalarish(bcx); debug!("trans_binary (expr {}): rhs_datum={}", expr.id, - rhs_datum.to_str(ccx)); + rhs_datum.to_string(ccx)); let rhs_ty = rhs_datum.ty; let rhs = rhs_datum.to_llscalarish(bcx); trans_eager_binop(bcx, expr, binop_ty, op, @@ -1729,7 +1729,7 @@ fn trans_assign_op<'a>( let _icx = push_ctxt("trans_assign_op"); let mut bcx = bcx; - debug!("trans_assign_op(expr={})", bcx.expr_to_str(expr)); + debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr)); // User-defined operator methods cannot be used with `+=` etc right now assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id))); @@ -1799,7 +1799,7 @@ fn deref_once<'a>(bcx: &'a Block<'a>, debug!("deref_once(expr={}, datum={}, method_call={})", expr.repr(bcx.tcx()), - datum.to_str(ccx), + datum.to_string(ccx), method_call); let mut bcx = bcx; @@ -1877,7 +1877,7 @@ fn deref_once<'a>(bcx: &'a Block<'a>, }; debug!("deref_once(expr={}, method_call={}, result={})", - expr.id, method_call, r.datum.to_str(ccx)); + expr.id, method_call, r.datum.to_string(ccx)); return r; diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 9d7261f8094..0b12cd3da82 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -266,8 +266,8 @@ pub fn trans_native_call<'a>( llfn={}, \ llretptr={})", callee_ty.repr(tcx), - ccx.tn.val_to_str(llfn), - ccx.tn.val_to_str(llretptr)); + ccx.tn.val_to_string(llfn), + ccx.tn.val_to_string(llretptr)); let (fn_abi, fn_sig) = match ty::get(callee_ty).sty { ty::ty_bare_fn(ref fn_ty) => (fn_ty.abi, fn_ty.sig.clone()), @@ -314,9 +314,9 @@ pub fn trans_native_call<'a>( debug!("argument {}, llarg_rust={}, rust_indirect={}, arg_ty={}", i, - ccx.tn.val_to_str(llarg_rust), + ccx.tn.val_to_string(llarg_rust), rust_indirect, - ccx.tn.type_to_str(arg_tys[i].ty)); + ccx.tn.type_to_string(arg_tys[i].ty)); // Ensure that we always have the Rust value indirectly, // because it makes bitcasting easier. @@ -330,7 +330,7 @@ pub fn trans_native_call<'a>( } debug!("llarg_rust={} (after indirection)", - ccx.tn.val_to_str(llarg_rust)); + ccx.tn.val_to_string(llarg_rust)); // Check whether we need to do any casting match arg_tys[i].cast { @@ -339,7 +339,7 @@ pub fn trans_native_call<'a>( } debug!("llarg_rust={} (after casting)", - ccx.tn.val_to_str(llarg_rust)); + ccx.tn.val_to_string(llarg_rust)); // Finally, load the value if needed for the foreign ABI let foreign_indirect = arg_tys[i].is_indirect(); @@ -355,7 +355,7 @@ pub fn trans_native_call<'a>( }; debug!("argument {}, llarg_foreign={}", - i, ccx.tn.val_to_str(llarg_foreign)); + i, ccx.tn.val_to_string(llarg_foreign)); // fill padding with undef value match arg_tys[i].pad { @@ -430,10 +430,10 @@ pub fn trans_native_call<'a>( None => fn_type.ret_ty.ty }; - debug!("llretptr={}", ccx.tn.val_to_str(llretptr)); - debug!("llforeign_retval={}", ccx.tn.val_to_str(llforeign_retval)); - debug!("llrust_ret_ty={}", ccx.tn.type_to_str(llrust_ret_ty)); - debug!("llforeign_ret_ty={}", ccx.tn.type_to_str(llforeign_ret_ty)); + debug!("llretptr={}", ccx.tn.val_to_string(llretptr)); + debug!("llforeign_retval={}", ccx.tn.val_to_string(llforeign_retval)); + debug!("llrust_ret_ty={}", ccx.tn.type_to_string(llrust_ret_ty)); + debug!("llforeign_ret_ty={}", ccx.tn.type_to_string(llforeign_ret_ty)); if llrust_ret_ty == llforeign_ret_ty { base::store_ty(bcx, llforeign_retval, llretptr, fn_sig.output) @@ -538,7 +538,7 @@ pub fn register_rust_fn_with_foreign_abi(ccx: &CrateContext, let llfn = base::register_fn_llvmty(ccx, sp, sym, node_id, cconv, llfn_ty); add_argument_attributes(&tys, llfn); debug!("register_rust_fn_with_foreign_abi(node_id={:?}, llfn_ty={}, llfn={})", - node_id, ccx.tn.type_to_str(llfn_ty), ccx.tn.val_to_str(llfn)); + node_id, ccx.tn.type_to_string(llfn_ty), ccx.tn.val_to_string(llfn)); llfn } @@ -583,13 +583,13 @@ 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", - ccx.tcx.map.path_to_str(id), + ccx.tcx.map.path_to_string(id), t.repr(tcx)).as_slice()); } }; debug!("build_rust_fn: path={} id={} t={}", - ccx.tcx.map.path_to_str(id), + ccx.tcx.map.path_to_string(id), id, t.repr(tcx)); let llfn = base::decl_internal_rust_fn(ccx, t, ps.as_slice()); @@ -610,8 +610,8 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, let t = ty::node_id_to_type(tcx, id); debug!("build_wrap_fn(llrustfn={}, llwrapfn={}, t={})", - ccx.tn.val_to_str(llrustfn), - ccx.tn.val_to_str(llwrapfn), + ccx.tn.val_to_string(llrustfn), + ccx.tn.val_to_string(llwrapfn), t.repr(ccx.tcx())); // Avoid all the Rust generation stuff and just generate raw @@ -668,11 +668,11 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, match foreign_outptr { Some(llforeign_outptr) => { debug!("out pointer, foreign={}", - ccx.tn.val_to_str(llforeign_outptr)); + ccx.tn.val_to_string(llforeign_outptr)); let llrust_retptr = builder.bitcast(llforeign_outptr, llrust_ret_ty.ptr_to()); debug!("out pointer, foreign={} (casted)", - ccx.tn.val_to_str(llrust_retptr)); + ccx.tn.val_to_string(llrust_retptr)); llrust_args.push(llrust_retptr); return_alloca = None; } @@ -683,8 +683,8 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, allocad={}, \ llrust_ret_ty={}, \ return_ty={}", - ccx.tn.val_to_str(slot), - ccx.tn.type_to_str(llrust_ret_ty), + ccx.tn.val_to_string(slot), + ccx.tn.type_to_string(llrust_ret_ty), tys.fn_sig.output.repr(tcx)); llrust_args.push(slot); return_alloca = Some(slot); @@ -712,7 +712,7 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, let mut llforeign_arg = llvm::LLVMGetParam(llwrapfn, foreign_index); debug!("llforeign_arg {}{}: {}", "#", - i, ccx.tn.val_to_str(llforeign_arg)); + i, ccx.tn.val_to_string(llforeign_arg)); debug!("rust_indirect = {}, foreign_indirect = {}", rust_indirect, foreign_indirect); @@ -751,12 +751,12 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, }; debug!("llrust_arg {}{}: {}", "#", - i, ccx.tn.val_to_str(llrust_arg)); + i, ccx.tn.val_to_string(llrust_arg)); llrust_args.push(llrust_arg); } // Perform the call itself - debug!("calling llrustfn = {}, t = {}", ccx.tn.val_to_str(llrustfn), t.repr(ccx.tcx())); + debug!("calling llrustfn = {}, t = {}", ccx.tn.val_to_string(llrustfn), t.repr(ccx.tcx())); let attributes = base::get_fn_llvm_attributes(ccx, t); let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), attributes.as_slice()); @@ -876,9 +876,9 @@ fn foreign_types_for_fn_ty(ccx: &CrateContext, ret_def={}", ty.repr(ccx.tcx()), ccx.tn.types_to_str(llsig.llarg_tys.as_slice()), - ccx.tn.type_to_str(llsig.llret_ty), + ccx.tn.type_to_string(llsig.llret_ty), ccx.tn.types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()), - ccx.tn.type_to_str(fn_ty.ret_ty.ty), + ccx.tn.type_to_string(fn_ty.ret_ty.ty), ret_def); ForeignTypes { diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index d046778485c..4d9f004e3dc 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -167,11 +167,11 @@ pub fn lazily_emit_visit_glue(ccx: &CrateContext, ti: &tydesc_info) -> ValueRef match ti.visit_glue.get() { Some(visit_glue) => visit_glue, None => { - debug!("+++ lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty)); + debug!("+++ lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_string(ccx.tcx(), ti.ty)); let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, "visit"); ti.visit_glue.set(Some(glue_fn)); make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, "visit"); - debug!("--- lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty)); + debug!("--- lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_string(ccx.tcx(), ti.ty)); glue_fn } } @@ -432,13 +432,13 @@ pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info { if ccx.sess().count_type_sizes() { println!("{}\t{}", llsize_of_real(ccx, llty), - ppaux::ty_to_str(ccx.tcx(), t)); + ppaux::ty_to_string(ccx.tcx(), t)); } let llsize = llsize_of(ccx, llty); let llalign = llalign_of(ccx, llty); let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc"); - debug!("+++ declare_tydesc {} {}", ppaux::ty_to_str(ccx.tcx(), t), name); + debug!("+++ declare_tydesc {} {}", ppaux::ty_to_string(ccx.tcx(), t), name); let gvar = name.as_slice().with_c_str(|buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type().to_ref(), buf) @@ -447,10 +447,10 @@ pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info { note_unique_llvm_symbol(ccx, name); let ty_name = token::intern_and_get_ident( - ppaux::ty_to_str(ccx.tcx(), t).as_slice()); + ppaux::ty_to_string(ccx.tcx(), t).as_slice()); let ty_name = C_str_slice(ccx, ty_name); - debug!("--- declare_tydesc {}", ppaux::ty_to_str(ccx.tcx(), t)); + debug!("--- declare_tydesc {}", ppaux::ty_to_string(ccx.tcx(), t)); tydesc_info { ty: t, tydesc: gvar, @@ -468,7 +468,7 @@ fn declare_generic_glue(ccx: &CrateContext, t: ty::t, llfnty: Type, ccx, t, format!("glue_{}", name).as_slice()); - debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t)); + debug!("{} is for type {}", fn_nm, ppaux::ty_to_string(ccx.tcx(), t)); let llfn = decl_cdecl_fn(ccx, fn_nm.as_slice(), llfnty, ty::mk_nil()); note_unique_llvm_symbol(ccx, fn_nm); return llfn; diff --git a/src/librustc/middle/trans/intrinsic.rs b/src/librustc/middle/trans/intrinsic.rs index 5022e0bf05b..28bdc6852e8 100644 --- a/src/librustc/middle/trans/intrinsic.rs +++ b/src/librustc/middle/trans/intrinsic.rs @@ -29,7 +29,7 @@ use middle::ty; use syntax::ast; use syntax::ast_map; use syntax::parse::token; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; pub fn get_simple_intrinsic(ccx: &CrateContext, item: &ast::ForeignItem) -> Option<ValueRef> { let name = match token::get_ident(item.ident).get() { @@ -398,10 +398,10 @@ pub fn trans_intrinsic(ccx: &CrateContext, format!("transmute called on types with different sizes: \ {} ({} bit{}) to \ {} ({} bit{})", - ty_to_str(ccx.tcx(), in_type), + ty_to_string(ccx.tcx(), in_type), in_type_size, if in_type_size == 1 {""} else {"s"}, - ty_to_str(ccx.tcx(), out_type), + ty_to_string(ccx.tcx(), out_type), out_type_size, if out_type_size == 1 {""} else {"s"}).as_slice()); } @@ -587,14 +587,14 @@ pub fn check_intrinsics(ccx: &CrateContext) { .span_err(transmute_restriction.span, format!("transmute called on types with different sizes: \ {} ({} bit{}) to {} ({} bit{})", - ty_to_str(ccx.tcx(), transmute_restriction.from), + ty_to_string(ccx.tcx(), transmute_restriction.from), from_type_size as uint, if from_type_size == 1 { "" } else { "s" }, - ty_to_str(ccx.tcx(), transmute_restriction.to), + ty_to_string(ccx.tcx(), transmute_restriction.to), to_type_size as uint, if to_type_size == 1 { "" diff --git a/src/librustc/middle/trans/llrepr.rs b/src/librustc/middle/trans/llrepr.rs index 3cd1a59abef..f7884ca5643 100644 --- a/src/librustc/middle/trans/llrepr.rs +++ b/src/librustc/middle/trans/llrepr.rs @@ -25,13 +25,13 @@ impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] { impl LlvmRepr for Type { fn llrepr(&self, ccx: &CrateContext) -> String { - ccx.tn.type_to_str(*self) + ccx.tn.type_to_string(*self) } } impl LlvmRepr for ValueRef { fn llrepr(&self, ccx: &CrateContext) -> String { - ccx.tn.val_to_str(*self) + ccx.tn.val_to_string(*self) } } diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index e1d43c52400..c79e435707a 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -502,12 +502,15 @@ fn emit_vtable_methods(bcx: &Block, ExprId(0), substs.clone(), vtables.clone()); - if m.explicit_self == ast::SelfValue { - fn_ref = trans_unboxing_shim(bcx, - fn_ref, - &*m, - m_id, - substs.clone()); + match m.explicit_self { + ast::SelfValue(_) => { + fn_ref = trans_unboxing_shim(bcx, + fn_ref, + &*m, + m_id, + substs.clone()); + }, + _ => {} } fn_ref } diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index ee581f75634..e50eb8f0be9 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -23,7 +23,7 @@ use middle::trans::meth; use middle::trans::type_::Type; use middle::trans::type_of::*; use middle::ty; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; use std::rc::Rc; use arena::TypedArena; @@ -98,7 +98,7 @@ impl<'a, 'b> Reflector<'a, 'b> { debug!("passing {} args:", args.len()); let mut bcx = self.bcx; for (i, a) in args.iter().enumerate() { - debug!("arg {}: {}", i, bcx.val_to_str(*a)); + debug!("arg {}: {}", i, bcx.val_to_string(*a)); } let result = unpack_result!(bcx, callee::trans_call_inner( self.bcx, None, mth_ty, @@ -129,7 +129,7 @@ impl<'a, 'b> Reflector<'a, 'b> { pub fn visit_ty(&mut self, t: ty::t) { let bcx = self.bcx; let tcx = bcx.tcx(); - debug!("reflect::visit_ty {}", ty_to_str(bcx.tcx(), t)); + debug!("reflect::visit_ty {}", ty_to_string(bcx.tcx(), t)); match ty::get(t).sty { ty::ty_bot => self.leaf("bot"), @@ -175,7 +175,7 @@ impl<'a, 'b> Reflector<'a, 'b> { ty::ty_trait(..) => { let extra = [ self.c_slice(token::intern_and_get_ident( - ty_to_str(tcx, t).as_slice())) + ty_to_string(tcx, t).as_slice())) ]; self.visit("trait", extra); } @@ -204,7 +204,7 @@ impl<'a, 'b> Reflector<'a, 'b> { ty::ty_trait(..) => { let extra = [ self.c_slice(token::intern_and_get_ident( - ty_to_str(tcx, t).as_slice())) + ty_to_string(tcx, t).as_slice())) ]; self.visit("trait", extra); } @@ -269,7 +269,7 @@ impl<'a, 'b> Reflector<'a, 'b> { let extra = (vec!( self.c_slice( - token::intern_and_get_ident(ty_to_str(tcx, + token::intern_and_get_ident(ty_to_string(tcx, t).as_slice())), self.c_bool(named_fields), self.c_uint(fields.len()) diff --git a/src/librustc/middle/trans/tvec.rs b/src/librustc/middle/trans/tvec.rs index 19d7d6c6a00..a6e554039e7 100644 --- a/src/librustc/middle/trans/tvec.rs +++ b/src/librustc/middle/trans/tvec.rs @@ -29,7 +29,7 @@ use middle::trans::machine::{llsize_of, nonzero_llsize_of, llsize_of_alloc}; use middle::trans::type_::Type; use middle::trans::type_of; use middle::ty; -use util::ppaux::ty_to_str; +use util::ppaux::ty_to_string; use syntax::ast; use syntax::parse::token::InternedString; @@ -73,12 +73,12 @@ pub struct VecTypes { } impl VecTypes { - pub fn to_str(&self, ccx: &CrateContext) -> String { + pub fn to_string(&self, ccx: &CrateContext) -> String { format!("VecTypes {{unit_ty={}, llunit_ty={}, \ llunit_size={}, llunit_alloc_size={}}}", - ty_to_str(ccx.tcx(), self.unit_ty), - ccx.tn.type_to_str(self.llunit_ty), - ccx.tn.val_to_str(self.llunit_size), + ty_to_string(ccx.tcx(), self.unit_ty), + ccx.tn.type_to_string(self.llunit_ty), + ccx.tn.val_to_string(self.llunit_size), self.llunit_alloc_size) } } @@ -97,7 +97,7 @@ pub fn trans_fixed_vstore<'a>( // generate the content. debug!("trans_fixed_vstore(vstore_expr={}, dest={:?})", - bcx.expr_to_str(vstore_expr), dest.to_str(bcx.ccx())); + bcx.expr_to_string(vstore_expr), dest.to_string(bcx.ccx())); let vt = vec_types_from_expr(bcx, vstore_expr); @@ -129,7 +129,7 @@ pub fn trans_slice_vstore<'a>( let mut bcx = bcx; debug!("trans_slice_vstore(vstore_expr={}, dest={})", - bcx.expr_to_str(vstore_expr), dest.to_str(ccx)); + bcx.expr_to_string(vstore_expr), dest.to_string(ccx)); // Handle the &"..." case: match content_expr.node { @@ -150,7 +150,7 @@ pub fn trans_slice_vstore<'a>( // Handle the &[...] case: let vt = vec_types_from_expr(bcx, vstore_expr); let count = elements_required(bcx, content_expr); - debug!("vt={}, count={:?}", vt.to_str(ccx), count); + debug!("vt={}, count={:?}", vt.to_string(ccx), count); let llcount = C_uint(ccx, count); let llfixed; @@ -202,8 +202,8 @@ pub fn trans_lit_str<'a>( */ debug!("trans_lit_str(lit_expr={}, dest={})", - bcx.expr_to_str(lit_expr), - dest.to_str(bcx.ccx())); + bcx.expr_to_string(lit_expr), + dest.to_string(bcx.ccx())); match dest { Ignore => bcx, @@ -233,7 +233,7 @@ pub fn trans_uniq_vstore<'a>(bcx: &'a Block<'a>, * the array elements into them. */ - debug!("trans_uniq_vstore(vstore_expr={})", bcx.expr_to_str(vstore_expr)); + debug!("trans_uniq_vstore(vstore_expr={})", bcx.expr_to_string(vstore_expr)); let fcx = bcx.fcx; let ccx = fcx.ccx; @@ -297,7 +297,7 @@ pub fn trans_uniq_vstore<'a>(bcx: &'a Block<'a>, let dataptr = get_dataptr(bcx, val); debug!("alloc_uniq_vec() returned val={}, dataptr={}", - bcx.val_to_str(val), bcx.val_to_str(dataptr)); + bcx.val_to_string(val), bcx.val_to_string(dataptr)); let bcx = write_content(bcx, &vt, vstore_expr, content_expr, SaveIn(dataptr)); @@ -319,9 +319,9 @@ pub fn write_content<'a>( let mut bcx = bcx; debug!("write_content(vt={}, dest={}, vstore_expr={:?})", - vt.to_str(bcx.ccx()), - dest.to_str(bcx.ccx()), - bcx.expr_to_str(vstore_expr)); + vt.to_string(bcx.ccx()), + dest.to_string(bcx.ccx()), + bcx.expr_to_string(vstore_expr)); match content_expr.node { ast::ExprLit(lit) => { @@ -361,7 +361,7 @@ pub fn write_content<'a>( for (i, element) in elements.iter().enumerate() { let lleltptr = GEPi(bcx, lldest, [i]); debug!("writing index {:?} with lleltptr={:?}", - i, bcx.val_to_str(lleltptr)); + i, bcx.val_to_string(lleltptr)); bcx = expr::trans_into(bcx, &**element, SaveIn(lleltptr)); fcx.schedule_drop_mem( diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index 028722071a6..50c81596edf 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -199,7 +199,7 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { t, t_norm.repr(cx.tcx()), t_norm, - cx.tn.type_to_str(llty)); + cx.tn.type_to_string(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } @@ -291,7 +291,7 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, - cx.tn.type_to_str(llty)); + cx.tn.type_to_string(llty)); cx.lltypes.borrow_mut().insert(t, llty); diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 282ccf1155d..f9eda70d16e 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -32,8 +32,8 @@ use middle::typeck::MethodCall; use middle::ty_fold; use middle::ty_fold::{TypeFoldable,TypeFolder}; use middle; -use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str}; -use util::ppaux::{trait_store_to_str, ty_to_str}; +use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string}; +use util::ppaux::{trait_store_to_string, ty_to_string}; use util::ppaux::{Repr, UserString}; use util::common::{indenter}; use util::nodemap::{NodeMap, NodeSet, DefIdMap, DefIdSet, FnvHashMap}; @@ -2243,8 +2243,8 @@ pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool { fn type_requires(cx: &ctxt, seen: &mut Vec<DefId>, r_ty: t, ty: t) -> bool { debug!("type_requires({}, {})?", - ::util::ppaux::ty_to_str(cx, r_ty), - ::util::ppaux::ty_to_str(cx, ty)); + ::util::ppaux::ty_to_string(cx, r_ty), + ::util::ppaux::ty_to_string(cx, ty)); let r = { get(r_ty).sty == get(ty).sty || @@ -2252,8 +2252,8 @@ pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool { }; debug!("type_requires({}, {})? {}", - ::util::ppaux::ty_to_str(cx, r_ty), - ::util::ppaux::ty_to_str(cx, ty), + ::util::ppaux::ty_to_string(cx, r_ty), + ::util::ppaux::ty_to_string(cx, ty), r); return r; } @@ -2261,8 +2261,8 @@ pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool { fn subtypes_require(cx: &ctxt, seen: &mut Vec<DefId>, r_ty: t, ty: t) -> bool { debug!("subtypes_require({}, {})?", - ::util::ppaux::ty_to_str(cx, r_ty), - ::util::ppaux::ty_to_str(cx, ty)); + ::util::ppaux::ty_to_string(cx, r_ty), + ::util::ppaux::ty_to_string(cx, ty)); let r = match get(ty).sty { // fixed length vectors need special treatment compared to @@ -2337,8 +2337,8 @@ pub fn is_instantiable(cx: &ctxt, r_ty: t) -> bool { }; debug!("subtypes_require({}, {})? {}", - ::util::ppaux::ty_to_str(cx, r_ty), - ::util::ppaux::ty_to_str(cx, ty), + ::util::ppaux::ty_to_string(cx, r_ty), + ::util::ppaux::ty_to_string(cx, ty), r); return r; @@ -2381,7 +2381,7 @@ pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability { fn type_structurally_recursive(cx: &ctxt, sp: Span, seen: &mut Vec<DefId>, ty: t) -> Representability { debug!("type_structurally_recursive: {}", - ::util::ppaux::ty_to_str(cx, ty)); + ::util::ppaux::ty_to_string(cx, ty)); // Compare current type to previously seen types match get(ty).sty { @@ -2441,7 +2441,7 @@ pub fn is_type_representable(cx: &ctxt, sp: Span, ty: t) -> Representability { } debug!("is_type_representable: {}", - ::util::ppaux::ty_to_str(cx, ty)); + ::util::ppaux::ty_to_string(cx, ty)); // To avoid a stack overflow when checking an enum variant or struct that // contains a different, structurally recursive type, maintain a stack @@ -2595,7 +2595,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)).as_slice()) + cx.map.node_to_string(id)).as_slice()) } } @@ -2608,7 +2608,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)).as_slice()) + cx.map.node_to_string(id)).as_slice()) } } @@ -2842,7 +2842,7 @@ pub fn adjust_ty(cx: &ctxt, format!("the {}th autoderef failed: \ {}", i, - ty_to_str(cx, adjusted_ty)) + ty_to_string(cx, adjusted_ty)) .as_slice()); } } @@ -3220,11 +3220,11 @@ pub fn param_tys_in_type(ty: t) -> Vec<ParamTy> { rslt } -pub fn ty_sort_str(cx: &ctxt, t: t) -> String { +pub fn ty_sort_string(cx: &ctxt, t: t) -> String { match get(t).sty { ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) | ty_uint(_) | ty_float(_) | ty_str => { - ::util::ppaux::ty_to_str(cx, t) + ::util::ppaux::ty_to_string(cx, t) } ty_enum(id, _) => format!("enum {}", item_path_str(cx, id)), @@ -3277,18 +3277,18 @@ pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String { terr_mismatch => "types differ".to_string(), terr_fn_style_mismatch(values) => { format!("expected {} fn but found {} fn", - values.expected.to_str(), - values.found.to_str()) + values.expected.to_string(), + values.found.to_string()) } terr_abi_mismatch(values) => { format!("expected {} fn but found {} fn", - values.expected.to_str(), - values.found.to_str()) + values.expected.to_string(), + values.found.to_string()) } terr_onceness_mismatch(values) => { format!("expected {} fn but found {} fn", - values.expected.to_str(), - values.found.to_str()) + values.expected.to_string(), + values.found.to_string()) } terr_sigil_mismatch(values) => { format!("expected {}, found {}", @@ -3344,22 +3344,22 @@ pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String { terr_regions_insufficiently_polymorphic(br, _) => { format!("expected bound lifetime parameter {}, \ but found concrete lifetime", - bound_region_ptr_to_str(cx, br)) + bound_region_ptr_to_string(cx, br)) } terr_regions_overly_polymorphic(br, _) => { format!("expected concrete lifetime, \ but found bound lifetime parameter {}", - bound_region_ptr_to_str(cx, br)) + bound_region_ptr_to_string(cx, br)) } terr_trait_stores_differ(_, ref values) => { format!("trait storage differs: expected `{}` but found `{}`", - trait_store_to_str(cx, (*values).expected), - trait_store_to_str(cx, (*values).found)) + trait_store_to_string(cx, (*values).expected), + trait_store_to_string(cx, (*values).found)) } terr_sorts(values) => { format!("expected {} but found {}", - ty_sort_str(cx, values.expected), - ty_sort_str(cx, values.found)) + ty_sort_string(cx, values.expected), + ty_sort_string(cx, values.found)) } terr_traits(values) => { format!("expected trait `{}` but found trait `{}`", @@ -3384,13 +3384,13 @@ pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String { } terr_int_mismatch(ref values) => { format!("expected `{}` but found `{}`", - values.expected.to_str(), - values.found.to_str()) + values.expected.to_string(), + values.found.to_string()) } terr_float_mismatch(ref values) => { format!("expected `{}` but found `{}`", - values.expected.to_str(), - values.found.to_str()) + values.expected.to_string(), + values.found.to_string()) } terr_variadic_mismatch(ref values) => { format!("expected {} fn but found {} function", @@ -3701,7 +3701,7 @@ pub fn substd_enum_variants(cx: &ctxt, } pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String { - with_path(cx, id, |path| ast_map::path_to_str(path)).to_string() + with_path(cx, id, |path| ast_map::path_to_string(path)).to_string() } pub enum DtorKind { @@ -3973,7 +3973,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)).as_slice()); + cx.map.node_to_string(did.node)).as_slice()); } } } @@ -3995,7 +3995,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)).as_slice()); + cx.map.node_to_string(did.node)).as_slice()); } } }); @@ -4621,7 +4621,7 @@ pub fn hash_crate_independent(tcx: &ctxt, t: t, svh: &Svh) -> u64 { } impl Variance { - pub fn to_str(self) -> &'static str { + pub fn to_string(self) -> &'static str { match self { Covariant => "+", Contravariant => "-", diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 286cb536475..90331d8f434 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -66,7 +66,7 @@ use syntax::abi; use syntax::{ast, ast_util}; use syntax::codemap::Span; use syntax::owned_slice::OwnedSlice; -use syntax::print::pprust::{lifetime_to_str, path_to_str}; +use syntax::print::pprust::{lifetime_to_string, path_to_string}; pub trait AstConv { fn tcx<'a>(&'a self) -> &'a ty::ctxt; @@ -108,7 +108,7 @@ pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime) }; debug!("ast_region_to_region(lifetime={} id={}) yields {}", - lifetime_to_str(lifetime), + lifetime_to_string(lifetime), lifetime.id, r.repr(tcx)); r @@ -142,7 +142,7 @@ pub fn opt_ast_region_to_region<AC:AstConv,RS:RegionScope>( }; debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {}", - opt_lifetime.as_ref().map(|e| lifetime_to_str(e)), + opt_lifetime.as_ref().map(|e| lifetime_to_string(e)), r.repr(this.tcx())); r @@ -331,7 +331,7 @@ pub fn ast_ty_to_prim_ty(tcx: &ty::ctxt, ast_ty: &ast::Ty) -> Option<ty::t> { None => { tcx.sess.span_bug(ast_ty.span, format!("unbound path {}", - path_to_str(path)).as_slice()) + path_to_string(path)).as_slice()) } Some(&d) => d }; @@ -394,7 +394,7 @@ pub fn ast_ty_to_builtin_ty<AC:AstConv, .sess .span_bug(ast_ty.span, format!("unbound path {}", - path_to_str(path)).as_slice()) + path_to_string(path)).as_slice()) } Some(&d) => d }; @@ -793,7 +793,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>( tcx.sess .span_bug(ast_ty.span, format!("unbound path {}", - path_to_str(path)).as_slice()) + path_to_string(path)).as_slice()) } Some(&d) => d }; @@ -808,7 +808,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>( } match a_def { def::DefTrait(_) => { - let path_str = path_to_str(path); + let path_str = path_to_string(path); tcx.sess.span_err( ast_ty.span, format!("reference to trait `{name}` where a \ @@ -835,7 +835,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>( def::DefMod(id) => { tcx.sess.span_fatal(ast_ty.span, format!("found module name used as a type: {}", - tcx.map.node_to_str(id.node)).as_slice()); + tcx.map.node_to_string(id.node)).as_slice()); } def::DefPrimTy(_) => { fail!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call"); @@ -938,10 +938,10 @@ fn ty_of_method_or_bare_fn<AC:AstConv>(this: &AC, id: ast::NodeId, let self_ty = opt_self_info.and_then(|self_info| { match self_info.explicit_self.node { ast::SelfStatic => None, - ast::SelfValue => { + ast::SelfValue(_) => { Some(self_info.untransformed_self_ty) } - ast::SelfRegion(ref lifetime, mutability) => { + ast::SelfRegion(ref lifetime, mutability, _) => { let region = opt_ast_region_to_region(this, &rb, self_info.explicit_self.span, @@ -950,7 +950,7 @@ fn ty_of_method_or_bare_fn<AC:AstConv>(this: &AC, id: ast::NodeId, ty::mt {ty: self_info.untransformed_self_ty, mutbl: mutability})) } - ast::SelfUniq => { + ast::SelfUniq(_) => { Some(ty::mk_uniq(this.tcx(), self_info.untransformed_self_ty)) } } diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index a5e7db1d6fd..2232cc49657 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -399,11 +399,11 @@ pub fn check_struct_like_enum_variant_pat(pcx: &pat_ctxt, variant_id, substitutions, etc); } Some(&def::DefStruct(..)) | Some(&def::DefVariant(..)) => { - let name = pprust::path_to_str(path); + let name = pprust::path_to_string(path); tcx.sess.span_err(span, format!("mismatched types: expected `{}` but \ found `{}`", - fcx.infcx().ty_to_str(expected), + fcx.infcx().ty_to_string(expected), name).as_slice()); } _ => { @@ -525,9 +525,9 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { .span_err(path.span, format!("`{}` does not name the \ structure `{}`", - pprust::path_to_str(path), + pprust::path_to_string(path), fcx.infcx() - .ty_to_str(expected)).as_slice()) + .ty_to_string(expected)).as_slice()) } check_struct_pat(pcx, pat.id, pat.span, expected, path, @@ -747,7 +747,7 @@ fn check_pointer_pat(pcx: &pat_ctxt, tcx.sess.span_err( span, format!("type `{}` cannot be dereferenced", - fcx.infcx().ty_to_str(expected)).as_slice()); + fcx.infcx().ty_to_string(expected)).as_slice()); fcx.write_error(pat_id); } _ => { diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 6e44665fb3b..a184ecac9de 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -30,14 +30,14 @@ itself (note that inherent impls can only be defined in the same module as the type itself). Inherent candidates are not always derived from impls. If you have a -trait instance, such as a value of type `Box<ToStr>`, then the trait -methods (`to_str()`, in this case) are inherently associated with it. +trait instance, such as a value of type `Box<ToString>`, then the trait +methods (`to_string()`, in this case) are inherently associated with it. Another case is type parameters, in which case the methods of their bounds are inherent. Extension candidates are derived from imported traits. If I have the -trait `ToStr` imported, and I call `to_str()` on a value of type `T`, -then we will go off to find out whether there is an impl of `ToStr` +trait `ToString` imported, and I call `to_string()` on a value of type `T`, +then we will go off to find out whether there is an impl of `ToString` for `T`. These kinds of method calls are called "extension methods". They can be defined in any module, not only the one that defined `T`. Furthermore, you must import the trait to call such a method. @@ -270,12 +270,12 @@ fn construct_transformed_self_ty_for_object( ast::SelfStatic => { tcx.sess.span_bug(span, "static method for object type receiver"); } - ast::SelfValue => { + ast::SelfValue(_) => { let tr = ty::mk_trait(tcx, trait_def_id, obj_substs, ty::empty_builtin_bounds()); ty::mk_uniq(tcx, tr) } - ast::SelfRegion(..) | ast::SelfUniq => { + ast::SelfRegion(..) | ast::SelfUniq(..) => { let transformed_self_ty = *method_ty.fty.sig.inputs.get(0); match ty::get(transformed_self_ty).sty { ty::ty_rptr(r, mt) => { // must be SelfRegion @@ -376,7 +376,7 @@ impl<'a> LookupContext<'a> { autoderefs: uint) -> Option<Option<MethodCallee>> { debug!("search_step: self_ty={} autoderefs={}", - self.ty_to_str(self_ty), autoderefs); + self.ty_to_string(self_ty), autoderefs); match self.deref_args { check::DontDerefArgs => { @@ -508,7 +508,7 @@ impl<'a> LookupContext<'a> { did: DefId, substs: &subst::Substs) { debug!("push_inherent_candidates_from_object(did={}, substs={})", - self.did_to_str(did), + self.did_to_string(did), substs.repr(self.tcx())); let _indenter = indenter(); let tcx = self.tcx(); @@ -733,7 +733,7 @@ impl<'a> LookupContext<'a> { None => None, Some(method) => { debug!("(searching for autoderef'd method) writing \ - adjustment {:?} for {}", adjustment, self.ty_to_str( self_ty)); + adjustment {:?} for {}", adjustment, self.ty_to_string( self_ty)); match adjustment { Some((self_expr_id, adj)) => { self.fcx.write_adjustment(self_expr_id, adj); @@ -809,7 +809,7 @@ impl<'a> LookupContext<'a> { fn auto_slice_vec(&self, mt: ty::mt, autoderefs: uint) -> Option<MethodCallee> { let tcx = self.tcx(); - debug!("auto_slice_vec {}", ppaux::ty_to_str(tcx, mt.ty)); + debug!("auto_slice_vec {}", ppaux::ty_to_string(tcx, mt.ty)); // First try to borrow to a slice let entry = self.search_for_some_kind_of_autorefd_method( @@ -886,7 +886,7 @@ impl<'a> LookupContext<'a> { * `~[]` to `&[]`. */ - debug!("search_for_autosliced_method {}", ppaux::ty_to_str(self.tcx(), self_ty)); + debug!("search_for_autosliced_method {}", ppaux::ty_to_string(self.tcx(), self_ty)); let sty = ty::get(self_ty).sty.clone(); match sty { @@ -939,7 +939,7 @@ impl<'a> LookupContext<'a> { ty_infer(TyVar(_)) => { self.bug(format!("unexpected type: {}", - self.ty_to_str(self_ty)).as_slice()); + self.ty_to_string(self_ty)).as_slice()); } } } @@ -993,7 +993,7 @@ impl<'a> LookupContext<'a> { } fn search_for_method(&self, rcvr_ty: ty::t) -> Option<MethodCallee> { - debug!("search_for_method(rcvr_ty={})", self.ty_to_str(rcvr_ty)); + debug!("search_for_method(rcvr_ty={})", self.ty_to_string(rcvr_ty)); let _indenter = indenter(); // I am not sure that inherent methods should have higher @@ -1094,7 +1094,7 @@ impl<'a> LookupContext<'a> { let tcx = self.tcx(); debug!("confirm_candidate(rcvr_ty={}, candidate={})", - self.ty_to_str(rcvr_ty), + self.ty_to_string(rcvr_ty), candidate.repr(self.tcx())); self.enforce_object_limitations(candidate); @@ -1177,7 +1177,7 @@ impl<'a> LookupContext<'a> { fn_style: bare_fn_ty.fn_style, abi: bare_fn_ty.abi.clone(), }); - debug!("after replacing bound regions, fty={}", self.ty_to_str(fty)); + debug!("after replacing bound regions, fty={}", self.ty_to_string(fty)); // Before, we only checked whether self_ty could be a subtype // of rcvr_ty; now we actually make it so (this may cause @@ -1191,8 +1191,8 @@ impl<'a> LookupContext<'a> { Err(_) => { self.bug(format!( "{} was a subtype of {} but now is not?", - self.ty_to_str(rcvr_ty), - self.ty_to_str(transformed_self_ty)).as_slice()); + self.ty_to_string(rcvr_ty), + self.ty_to_string(transformed_self_ty)).as_slice()); } } @@ -1227,7 +1227,7 @@ impl<'a> LookupContext<'a> { through an object"); } - ast::SelfValue | ast::SelfRegion(..) | ast::SelfUniq => {} + ast::SelfValue(_) | ast::SelfRegion(..) | ast::SelfUniq(_) => {} } // reason (a) above @@ -1288,7 +1288,7 @@ impl<'a> LookupContext<'a> { // candidate method's `self_ty`. fn is_relevant(&self, rcvr_ty: ty::t, candidate: &Candidate) -> bool { debug!("is_relevant(rcvr_ty={}, candidate={})", - self.ty_to_str(rcvr_ty), candidate.repr(self.tcx())); + self.ty_to_string(rcvr_ty), candidate.repr(self.tcx())); return match candidate.method_ty.explicit_self { SelfStatic => { @@ -1296,7 +1296,7 @@ impl<'a> LookupContext<'a> { self.report_statics == ReportStaticMethods } - SelfValue => { + SelfValue(_) => { debug!("(is relevant?) explicit self is by-value"); match ty::get(rcvr_ty).sty { ty::ty_uniq(typ) => { @@ -1319,7 +1319,7 @@ impl<'a> LookupContext<'a> { } } - SelfRegion(_, m) => { + SelfRegion(_, m, _) => { debug!("(is relevant?) explicit self is a region"); match ty::get(rcvr_ty).sty { ty::ty_rptr(_, mt) => { @@ -1339,7 +1339,7 @@ impl<'a> LookupContext<'a> { } } - SelfUniq => { + SelfUniq(_) => { debug!("(is relevant?) explicit self is a unique pointer"); match ty::get(rcvr_ty).sty { ty::ty_uniq(typ) => { @@ -1457,11 +1457,11 @@ impl<'a> LookupContext<'a> { self.fcx.tcx() } - fn ty_to_str(&self, t: ty::t) -> String { - self.fcx.infcx().ty_to_str(t) + fn ty_to_string(&self, t: ty::t) -> String { + self.fcx.infcx().ty_to_string(t) } - fn did_to_str(&self, did: DefId) -> String { + fn did_to_string(&self, did: DefId) -> String { ty::item_path_str(self.tcx(), did) } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 1d0c3074a4f..9f5fcb61f5f 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -397,8 +397,8 @@ impl<'a> Visitor<()> for GatherLocalsVisitor<'a> { }; self.assign(local.id, o_ty); debug!("Local variable {} is assigned type {}", - self.fcx.pat_to_str(&*local.pat), - self.fcx.infcx().ty_to_str( + self.fcx.pat_to_string(&*local.pat), + self.fcx.infcx().ty_to_string( self.fcx.inh.locals.borrow().get_copy(&local.id))); visit::walk_local(self, local, ()); } @@ -411,7 +411,7 @@ impl<'a> Visitor<()> for GatherLocalsVisitor<'a> { self.assign(p.id, None); debug!("Pattern binding {} is assigned to {}", token::get_ident(path1.node), - self.fcx.infcx().ty_to_str( + self.fcx.infcx().ty_to_string( self.fcx.inh.locals.borrow().get_copy(&p.id))); } _ => {} @@ -534,7 +534,7 @@ fn span_for_field(tcx: &ty::ctxt, field: &ty::field_ty, struct_id: ast::DefId) - let item = match tcx.map.find(struct_id.node) { Some(ast_map::NodeItem(item)) => item, None => fail!("node not in ast map: {}", struct_id.node), - _ => fail!("expected item, found {}", tcx.map.node_to_str(struct_id.node)) + _ => fail!("expected item, found {}", tcx.map.node_to_string(struct_id.node)) }; match item.node { @@ -803,7 +803,7 @@ fn check_impl_methods_against_trait(ccx: &CrateCtxt, format!( "method `{}` is not a member of trait `{}`", token::get_ident(impl_method_ty.ident), - pprust::path_to_str(&ast_trait_ref.path)).as_slice()); + pprust::path_to_string(&ast_trait_ref.path)).as_slice()); } } } @@ -870,7 +870,7 @@ fn compare_impl_method(tcx: &ty::ctxt, format!("method `{}` has a `{}` declaration in the impl, \ but not in the trait", token::get_ident(trait_m.ident), - pprust::explicit_self_to_str( + pprust::explicit_self_to_string( impl_m.explicit_self)).as_slice()); return; } @@ -880,7 +880,7 @@ fn compare_impl_method(tcx: &ty::ctxt, format!("method `{}` has a `{}` declaration in the trait, \ but not in the impl", token::get_ident(trait_m.ident), - pprust::explicit_self_to_str( + pprust::explicit_self_to_string( trait_m.explicit_self)).as_slice()); return; } @@ -1051,7 +1051,7 @@ fn compare_impl_method(tcx: &ty::ctxt, declaration", token::get_ident(trait_m.ident), i, - ppaux::trait_ref_to_str( + ppaux::trait_ref_to_string( tcx, &*impl_trait_bound)).as_slice()) } @@ -1101,8 +1101,8 @@ fn check_cast(fcx: &FnCtxt, let t_e = fcx.expr_ty(e); - debug!("t_1={}", fcx.infcx().ty_to_str(t_1)); - debug!("t_e={}", fcx.infcx().ty_to_str(t_e)); + debug!("t_1={}", fcx.infcx().ty_to_string(t_1)); + debug!("t_e={}", fcx.infcx().ty_to_string(t_e)); if ty::type_is_error(t_e) { fcx.write_error(id); @@ -1126,13 +1126,13 @@ fn check_cast(fcx: &FnCtxt, fcx.type_error_message(span, |actual| { format!("cast from nil: `{}` as `{}`", actual, - fcx.infcx().ty_to_str(t_1)) + fcx.infcx().ty_to_string(t_1)) }, t_e, None); } else if ty::type_is_nil(t_1) { fcx.type_error_message(span, |actual| { format!("cast to nil: `{}` as `{}`", actual, - fcx.infcx().ty_to_str(t_1)) + fcx.infcx().ty_to_string(t_1)) }, t_e, None); } @@ -1149,7 +1149,7 @@ fn check_cast(fcx: &FnCtxt, format!("illegal cast; cast through an \ integer first: `{}` as `{}`", actual, - fcx.infcx().ty_to_str(t_1)) + fcx.infcx().ty_to_string(t_1)) }, t_e, None); } // casts from C-like enums are allowed @@ -1217,7 +1217,7 @@ fn check_cast(fcx: &FnCtxt, fcx.type_error_message(span, |actual| { format!("non-scalar cast: `{}` as `{}`", actual, - fcx.infcx().ty_to_str(t_1)) + fcx.infcx().ty_to_string(t_1)) }, t_e, None); } @@ -1286,7 +1286,7 @@ impl<'a> FnCtxt<'a> { #[inline] pub fn write_ty(&self, node_id: ast::NodeId, ty: ty::t) { debug!("write_ty({}, {}) in fcx {}", - node_id, ppaux::ty_to_str(self.tcx(), ty), self.tag()); + node_id, ppaux::ty_to_string(self.tcx(), ty), self.tag()); self.inh.node_types.borrow_mut().insert(node_id, ty); } @@ -1343,7 +1343,7 @@ impl<'a> FnCtxt<'a> { ast_ty_to_ty(self, self.infcx(), ast_t) } - pub fn pat_to_str(&self, pat: &ast::Pat) -> String { + pub fn pat_to_string(&self, pat: &ast::Pat) -> String { pat.repr(self.tcx()) } @@ -1363,7 +1363,7 @@ impl<'a> FnCtxt<'a> { None => { self.tcx().sess.bug( format!("no type for node {}: {} in fcx {}", - id, self.tcx().map.node_to_str(id), + id, self.tcx().map.node_to_string(id), self.tag()).as_slice()); } } @@ -1375,7 +1375,7 @@ impl<'a> FnCtxt<'a> { None => { self.tcx().sess.bug( format!("no method entry for node {}: {} in fcx {}", - id, self.tcx().map.node_to_str(id), + id, self.tcx().map.node_to_string(id), self.tag()).as_slice()); } } @@ -1842,7 +1842,7 @@ fn check_argument_types(fcx: &FnCtxt, }; debug!("check_argument_types: formal_tys={:?}", - formal_tys.iter().map(|t| fcx.infcx().ty_to_str(*t)).collect::<Vec<String>>()); + formal_tys.iter().map(|t| fcx.infcx().ty_to_string(*t)).collect::<Vec<String>>()); // Check the arguments. // We do this in a pretty awful way: first we typecheck any arguments @@ -2410,7 +2410,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, operation `{}` not \ supported for floating \ point SIMD vector `{}`", - ast_util::binop_to_str(op), + ast_util::binop_to_string(op), actual) }, lhs_t, @@ -2440,7 +2440,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, |actual| { format!("binary operation `{}` cannot be applied \ to type `{}`", - ast_util::binop_to_str(op), + ast_util::binop_to_string(op), actual) }, lhs_t, @@ -2457,7 +2457,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, operation `{}=` \ cannot be applied to \ type `{}`", - ast_util::binop_to_str(op), + ast_util::binop_to_string(op), actual) }, lhs_t, @@ -2506,7 +2506,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, trait_did, [lhs_expr, rhs], DontAutoderefReceiver, || { fcx.type_error_message(ex.span, |actual| { format!("binary operation `{}` cannot be applied to type `{}`", - ast_util::binop_to_str(op), + ast_util::binop_to_string(op), actual) }, lhs_resolved_t, None) }) @@ -2594,7 +2594,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, expected_sig); let fty_sig = fn_ty.sig.clone(); let fty = ty::mk_closure(tcx, fn_ty); - debug!("check_expr_fn fty={}", fcx.infcx().ty_to_str(fty)); + debug!("check_expr_fn fty={}", fcx.infcx().ty_to_string(fty)); fcx.write_ty(expr.id, fty); @@ -2628,7 +2628,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, autoderef(fcx, expr.span, expr_t, Some(base.id), lvalue_pref, |base_t, _| { match ty::get(base_t).sty { ty::ty_struct(base_id, ref substs) => { - debug!("struct named {}", ppaux::ty_to_str(tcx, base_t)); + debug!("struct named {}", ppaux::ty_to_string(tcx, base_t)); let fields = ty::lookup_struct_fields(tcx, base_id); lookup_field_ty(tcx, base_id, fields.as_slice(), field.node.name, &(*substs)) @@ -3386,7 +3386,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, tcx.sess .span_err(path.span, format!("`{}` does not name a structure", - pprust::path_to_str( + pprust::path_to_string( path)).as_slice()) } } @@ -3454,10 +3454,10 @@ fn check_expr_with_unifier(fcx: &FnCtxt, } debug!("type of expr({}) {} is...", expr.id, - syntax::print::pprust::expr_to_str(expr)); + syntax::print::pprust::expr_to_string(expr)); debug!("... {}, expected is {}", - ppaux::ty_to_str(tcx, fcx.expr_ty(expr)), - expected.repr(tcx)) + ppaux::ty_to_string(tcx, fcx.expr_ty(expr)), + expected.repr(tcx)); unifier(); } @@ -3792,7 +3792,7 @@ pub fn check_instantiable(tcx: &ty::ctxt, format!("this type cannot be instantiated without an \ instance of itself; consider using \ `Option<{}>`", - ppaux::ty_to_str(tcx, item_ty)).as_slice()); + ppaux::ty_to_string(tcx, item_ty)).as_slice()); false } else { true @@ -3853,7 +3853,7 @@ pub fn check_enum_variants_sized(ccx: &CrateCtxt, dynamically sized types may only \ appear as the final type in a \ variant", - ppaux::ty_to_str(ccx.tcx, + ppaux::ty_to_string(ccx.tcx, *t)).as_slice()); } } @@ -3918,7 +3918,7 @@ pub fn check_enum_variants(ccx: &CrateCtxt, match v.node.disr_expr { Some(e) => { - debug!("disr expr, checking {}", pprust::expr_to_str(&*e)); + debug!("disr expr, checking {}", pprust::expr_to_string(&*e)); let inh = blank_inherited_fields(ccx); let fcx = blank_fn_ctxt(ccx, &inh, rty, e.id); @@ -4522,7 +4522,7 @@ pub fn check_bounds_are_used(ccx: &CrateCtxt, tps: &OwnedSlice<ast::TyParam>, ty: ty::t) { debug!("check_bounds_are_used(n_tps={}, ty={})", - tps.len(), ppaux::ty_to_str(ccx.tcx, ty)); + tps.len(), ppaux::ty_to_string(ccx.tcx, ty)); // make a vector of booleans initially false, set to true when used if tps.len() == 0u { return; } @@ -4840,7 +4840,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) { fty, || { format!("intrinsic has wrong type: expected `{}`", - ppaux::ty_to_str(ccx.tcx, fty)) + ppaux::ty_to_string(ccx.tcx, fty)) }); } } diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index 07fb43d0d34..924934e4bcd 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -133,7 +133,7 @@ use middle::typeck::infer; use middle::typeck::MethodCall; use middle::pat_util; use util::nodemap::NodeMap; -use util::ppaux::{ty_to_str, region_to_str, Repr}; +use util::ppaux::{ty_to_string, region_to_string, Repr}; use syntax::ast; use syntax::codemap::Span; @@ -876,7 +876,7 @@ fn constrain_autoderefs(rcx: &mut Rcx, let r_deref_expr = ty::ReScope(deref_expr.id); for i in range(0u, derefs) { debug!("constrain_autoderefs(deref_expr=?, derefd_ty={}, derefs={:?}/{:?}", - rcx.fcx.infcx().ty_to_str(derefd_ty), + rcx.fcx.infcx().ty_to_string(derefd_ty), i, derefs); let method_call = MethodCall::autoderef(deref_expr.id, i); @@ -948,7 +948,7 @@ fn constrain_index(rcx: &mut Rcx, */ debug!("constrain_index(index_expr=?, indexed_ty={}", - rcx.fcx.infcx().ty_to_str(indexed_ty)); + rcx.fcx.infcx().ty_to_string(indexed_ty)); let r_index_expr = ty::ReScope(index_expr.id); match ty::get(indexed_ty).sty { @@ -984,7 +984,7 @@ fn constrain_regions_in_type_of_node( |method_call| rcx.resolve_method_type(method_call)); debug!("constrain_regions_in_type_of_node(\ ty={}, ty0={}, id={}, minimum_lifetime={:?})", - ty_to_str(tcx, ty), ty_to_str(tcx, ty0), + ty_to_string(tcx, ty), ty_to_string(tcx, ty0), id, minimum_lifetime); constrain_regions_in_type(rcx, minimum_lifetime, origin, ty); } @@ -1011,8 +1011,8 @@ fn constrain_regions_in_type( let tcx = rcx.fcx.ccx.tcx; debug!("constrain_regions_in_type(minimum_lifetime={}, ty={})", - region_to_str(tcx, "", false, minimum_lifetime), - ty_to_str(tcx, ty)); + region_to_string(tcx, "", false, minimum_lifetime), + ty_to_string(tcx, ty)); relate_nested_regions(tcx, Some(minimum_lifetime), ty, |r_sub, r_sup| { debug!("relate_nested_regions(r_sub={}, r_sup={})", @@ -1190,7 +1190,7 @@ fn link_region_from_node_type(rcx: &Rcx, let rptr_ty = rcx.resolve_node_type(id); if !ty::type_is_bot(rptr_ty) && !ty::type_is_error(rptr_ty) { let tcx = rcx.fcx.ccx.tcx; - debug!("rptr_ty={}", ty_to_str(tcx, rptr_ty)); + debug!("rptr_ty={}", ty_to_string(tcx, rptr_ty)); let r = ty::ty_region(tcx, span, rptr_ty); link_region(rcx, span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed); diff --git a/src/librustc/middle/typeck/check/regionmanip.rs b/src/librustc/middle/typeck/check/regionmanip.rs index 146b42a00ff..53e26f8696f 100644 --- a/src/librustc/middle/typeck/check/regionmanip.rs +++ b/src/librustc/middle/typeck/check/regionmanip.rs @@ -30,7 +30,7 @@ pub fn replace_late_bound_regions_in_fn_sig( let mut map = HashMap::new(); let fn_sig = { let mut f = ty_fold::RegionFolder::regions(tcx, |r| { - debug!("region r={}", r.to_str()); + debug!("region r={}", r.to_string()); match r { ty::ReLateBound(s, br) if s == fn_sig.binder_id => { *map.find_or_insert_with(br, |_| mapf(br)) @@ -153,7 +153,7 @@ pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) { } for &t in all_tys.iter() { - debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t)); + debug!("relate_free_regions(t={})", ppaux::ty_to_string(tcx, t)); relate_nested_regions(tcx, None, t, |a, b| { match (&a, &b) { (&ty::ReFree(free_a), &ty::ReFree(free_b)) => { diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index bda47d99ed7..d2a1ef786bd 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -16,7 +16,7 @@ use middle::typeck::astconv::AstConv; use middle::typeck::check::{FnCtxt, impl_self_ty}; use middle::typeck::check::{structurally_resolved_type}; use middle::typeck::check::writeback; -use middle::typeck::infer::fixup_err_to_str; +use middle::typeck::infer::fixup_err_to_string; use middle::typeck::infer::{resolve_and_force_all_but_regions, resolve_type}; use middle::typeck::infer; use middle::typeck::{vtable_origin, vtable_res, vtable_param_res}; @@ -35,7 +35,7 @@ use std::collections::HashSet; use syntax::ast; use syntax::ast_util; use syntax::codemap::Span; -use syntax::print::pprust::expr_to_str; +use syntax::print::pprust::expr_to_string; use syntax::visit; use syntax::visit::Visitor; @@ -154,8 +154,8 @@ fn lookup_vtables_for_param(vcx: &VtableContext, vcx.tcx().sess.span_fatal(span, format!("failed to find an implementation of \ trait {} for {}", - vcx.infcx.trait_ref_to_str(&*trait_ref), - vcx.infcx.ty_to_str(ty)).as_slice()); + vcx.infcx.trait_ref_to_string(&*trait_ref), + vcx.infcx.ty_to_string(ty)).as_slice()); } } true @@ -205,8 +205,8 @@ fn relate_trait_refs(vcx: &VtableContext, let tcx = vcx.tcx(); tcx.sess.span_err(span, format!("expected {}, but found {} ({})", - ppaux::trait_ref_to_str(tcx, &r_exp_trait_ref), - ppaux::trait_ref_to_str(tcx, &r_act_trait_ref), + ppaux::trait_ref_to_string(tcx, &r_exp_trait_ref), + ppaux::trait_ref_to_string(tcx, &r_act_trait_ref), ty::type_err_to_str(tcx, err)).as_slice()); } } @@ -385,8 +385,8 @@ fn search_for_vtable(vcx: &VtableContext, debug!("(checking vtable) num 2 relating trait \ ty {} to of_trait_ref {}", - vcx.infcx.trait_ref_to_str(&*trait_ref), - vcx.infcx.trait_ref_to_str(&*of_trait_ref)); + vcx.infcx.trait_ref_to_string(&*trait_ref), + vcx.infcx.trait_ref_to_string(&*of_trait_ref)); relate_trait_refs(vcx, span, of_trait_ref, trait_ref.clone()); @@ -488,7 +488,7 @@ fn fixup_ty(vcx: &VtableContext, tcx.sess.span_fatal(span, format!("cannot determine a type for this bounded type \ parameter: {}", - fixup_err_to_str(e)).as_slice()) + fixup_err_to_string(e)).as_slice()) } Err(_) => { None @@ -527,7 +527,7 @@ pub fn early_resolve_expr(ex: &ast::Expr, fcx: &FnCtxt, is_early: bool) { } debug!("vtable: early_resolve_expr() ex with id {:?} (early: {}): {}", - ex.id, is_early, expr_to_str(ex)); + ex.id, is_early, expr_to_string(ex)); let _indent = indenter(); let cx = fcx.ccx; @@ -626,7 +626,7 @@ pub fn early_resolve_expr(ex: &ast::Expr, fcx: &FnCtxt, is_early: bool) { ex.span, format!("can only cast an boxed pointer \ to a boxed object, not a {}", - ty::ty_sort_str(fcx.tcx(), src_ty)).as_slice()); + ty::ty_sort_string(fcx.tcx(), src_ty)).as_slice()); } _ => {} } @@ -639,7 +639,7 @@ pub fn early_resolve_expr(ex: &ast::Expr, fcx: &FnCtxt, is_early: bool) { ex.span, format!("can only cast an &-pointer \ to an &-object, not a {}", - ty::ty_sort_str(fcx.tcx(), src_ty)).as_slice()); + ty::ty_sort_string(fcx.tcx(), src_ty)).as_slice()); } _ => {} } @@ -657,7 +657,7 @@ pub fn early_resolve_expr(ex: &ast::Expr, fcx: &FnCtxt, is_early: bool) { let did = def.def_id(); let item_ty = ty::lookup_item_type(cx.tcx, did); debug!("early resolve expr: def {:?} {:?}, {:?}, {}", ex.id, did, def, - fcx.infcx().ty_to_str(item_ty.ty)); + fcx.infcx().ty_to_string(item_ty.ty)); debug!("early_resolve_expr: looking up vtables for type params {}", item_ty.generics.types.repr(fcx.tcx())); let vcx = fcx.vtable_context(); diff --git a/src/librustc/middle/typeck/check/writeback.rs b/src/librustc/middle/typeck/check/writeback.rs index eb43144571e..59b65fdbec7 100644 --- a/src/librustc/middle/typeck/check/writeback.rs +++ b/src/librustc/middle/typeck/check/writeback.rs @@ -31,7 +31,7 @@ use std::cell::Cell; use syntax::ast; use syntax::codemap::Span; -use syntax::print::pprust::pat_to_str; +use syntax::print::pprust::pat_to_string; use syntax::visit; use syntax::visit::Visitor; @@ -159,7 +159,7 @@ impl<'cx> Visitor<()> for WritebackCx<'cx> { self.visit_node_id(ResolvingPattern(p.span), p.id); debug!("Type for pattern binding {} (id {}) resolved to {}", - pat_to_str(p), + pat_to_string(p), p.id, ty::node_id_to_type(self.tcx(), p.id).repr(self.tcx())); @@ -403,7 +403,7 @@ impl<'cx> Resolver<'cx> { span, format!("cannot determine a type for \ this expression: {}", - infer::fixup_err_to_str(e)).as_slice()) + infer::fixup_err_to_string(e)).as_slice()) } ResolvingLocal(span) => { @@ -411,7 +411,7 @@ impl<'cx> Resolver<'cx> { span, format!("cannot determine a type for \ this local variable: {}", - infer::fixup_err_to_str(e)).as_slice()) + infer::fixup_err_to_string(e)).as_slice()) } ResolvingPattern(span) => { @@ -419,7 +419,7 @@ impl<'cx> Resolver<'cx> { span, format!("cannot determine a type for \ this pattern binding: {}", - infer::fixup_err_to_str(e)).as_slice()) + infer::fixup_err_to_string(e)).as_slice()) } ResolvingUpvar(upvar_id) => { @@ -430,8 +430,8 @@ impl<'cx> Resolver<'cx> { captured variable `{}`: {}", ty::local_var_name_str( self.tcx, - upvar_id.var_id).get().to_str(), - infer::fixup_err_to_str(e)).as_slice()); + upvar_id.var_id).get().to_string(), + infer::fixup_err_to_string(e)).as_slice()); } ResolvingImplRes(span) => { diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index bf88ec5c438..b6cdeb92aa3 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -63,7 +63,7 @@ use syntax::codemap; use syntax::owned_slice::OwnedSlice; use syntax::parse::token::special_idents; use syntax::parse::token; -use syntax::print::pprust::{path_to_str}; +use syntax::print::pprust::{path_to_string}; use syntax::visit; struct CollectItemTypesVisitor<'a> { @@ -665,7 +665,7 @@ pub fn instantiate_trait_ref(ccx: &CrateCtxt, ccx.tcx.sess.span_fatal( ast_trait_ref.path.span, format!("`{}` is not a trait", - path_to_str(&ast_trait_ref.path)).as_slice()); + path_to_string(&ast_trait_ref.path)).as_slice()); } } } @@ -692,9 +692,9 @@ pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> Rc<ty::TraitDef> { _ => {} } - let (generics, sized, supertraits) = match it.node { - ast::ItemTrait(ref generics, sized, ref supertraits, _) => { - (generics, sized, supertraits) + let (generics, unbound, supertraits) = match it.node { + ast::ItemTrait(ref generics, ref unbound, ref supertraits, _) => { + (generics, unbound, supertraits) } ref s => { tcx.sess.span_bug( @@ -711,7 +711,7 @@ pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> Rc<ty::TraitDef> { generics); let builtin_bounds = - ensure_supertraits(ccx, it.id, it.span, supertraits, sized); + ensure_supertraits(ccx, it.id, it.span, supertraits, unbound); let substs = mk_item_substs(ccx, &ty_generics); let trait_def = Rc::new(ty::TraitDef { @@ -759,7 +759,7 @@ pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> Rc<ty::TraitDef> { id: ast::NodeId, sp: codemap::Span, ast_trait_refs: &Vec<ast::TraitRef>, - sized: ast::Sized) + unbound: &Option<ast::TyParamBound>) -> ty::BuiltinBounds { let tcx = ccx.tcx; @@ -798,15 +798,7 @@ pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> Rc<ty::TraitDef> { } } - if sized == ast::StaticSize { - match tcx.lang_items.require(SizedTraitLangItem) { - Ok(def_id) => { - ty::try_add_builtin_trait(tcx, def_id, &mut bounds); - } - Err(s) => tcx.sess.err(s.as_slice()), - }; - } - + add_unsized_bound(ccx, unbound, &mut bounds, "trait", sp); tcx.supertraits.borrow_mut().insert(local_def(id), Rc::new(ty_trait_refs)); bounds @@ -844,7 +836,7 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) debug!("type of {} (id {}) is {}", token::get_ident(it.ident), it.id, - ppaux::ty_to_str(tcx, pty.ty)); + ppaux::ty_to_string(tcx, pty.ty)); ccx.tcx.tcache.borrow_mut().insert(local_def(it.id), pty.clone()); return pty; @@ -974,6 +966,43 @@ fn ty_generics_for_fn_or_method(ccx: &CrateCtxt, &generics.ty_params, base_generics) } +// Add the Sized bound, unless the type parameter is marked as `Sized?`. +fn add_unsized_bound(ccx: &CrateCtxt, + unbound: &Option<ast::TyParamBound>, + bounds: &mut ty::BuiltinBounds, + desc: &str, + span: Span) { + let kind_id = ccx.tcx.lang_items.require(SizedTraitLangItem); + match unbound { + &Some(TraitTyParamBound(ref tpb)) => { + // #FIXME(8559) currently requires the unbound to be built-in. + let trait_def_id = ty::trait_ref_to_def_id(ccx.tcx, tpb); + match kind_id { + Ok(kind_id) if trait_def_id != kind_id => { + ccx.tcx.sess.span_warn(span, + format!("default bound relaxed \ + for a {}, but this does \ + nothing because the given \ + bound is not a default. \ + Only `Sized?` is supported.", + desc).as_slice()); + ty::try_add_builtin_trait(ccx.tcx, + kind_id, + bounds); + } + _ => {} + } + } + _ if kind_id.is_ok() => { + ty::try_add_builtin_trait(ccx.tcx, + kind_id.unwrap(), + bounds); + } + // No lang item for Sized, so we can't add it as a bound. + _ => {} + } +} + fn ty_generics(ccx: &CrateCtxt, space: subst::ParamSpace, lifetimes: &Vec<ast::Lifetime>, @@ -1016,7 +1045,7 @@ fn ty_generics(ccx: &CrateCtxt, let bounds = Rc::new(compute_bounds(ccx, param_ty, ¶m.bounds, - param.sized, + ¶m.unbound, param.ident, param.span)); let default = param.default.map(|path| { @@ -1056,7 +1085,7 @@ fn ty_generics(ccx: &CrateCtxt, ccx: &CrateCtxt, param_ty: ty::ParamTy, ast_bounds: &OwnedSlice<ast::TyParamBound>, - sized: ast::Sized, + unbound: &Option<ast::TyParamBound>, ident: ast::Ident, span: Span) -> ty::ParamBounds { @@ -1113,15 +1142,11 @@ fn ty_generics(ccx: &CrateCtxt, } } - if sized == ast::StaticSize { - match ccx.tcx.lang_items.require(SizedTraitLangItem) { - Ok(def_id) => { ty::try_add_builtin_trait(ccx.tcx, - def_id, - &mut param_bounds.builtin_bounds); }, - // Fixme(13367) after `type` makes it into the snapshot, we can check this properly - Err(_s) => {}, //ccx.tcx.sess.err(s), - } - } + add_unsized_bound(ccx, + unbound, + &mut param_bounds.builtin_bounds, + "type parameter", + span); check_bounds_compatible(ccx.tcx, ¶m_bounds, ident, span); @@ -1144,7 +1169,7 @@ fn ty_generics(ccx: &CrateCtxt, format!("incompatible bounds on type parameter {}, \ bound {} does not allow unsized type", token::get_ident(ident), - ppaux::trait_ref_to_str(tcx, + ppaux::trait_ref_to_string(tcx, &*trait_ref)).as_slice()); } true diff --git a/src/librustc/middle/typeck/infer/error_reporting.rs b/src/librustc/middle/typeck/infer/error_reporting.rs index 053a75e7260..b0c9900be90 100644 --- a/src/librustc/middle/typeck/infer/error_reporting.rs +++ b/src/librustc/middle/typeck/infer/error_reporting.rs @@ -90,7 +90,7 @@ use syntax::codemap; use syntax::parse::token; use syntax::print::pprust; use util::ppaux::UserString; -use util::ppaux::bound_region_to_str; +use util::ppaux::bound_region_to_string; use util::ppaux::note_and_explain_region; pub trait ErrorReporting { @@ -442,7 +442,7 @@ impl<'a> ErrorReporting for InferCtxt<'a> { ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_str()).as_slice()); + .to_string()).as_slice()); note_and_explain_region( self.tcx, "...the borrowed pointer is valid for ", @@ -454,7 +454,7 @@ impl<'a> ErrorReporting for InferCtxt<'a> { ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_str()).as_slice(), + .to_string()).as_slice(), sup, ""); } @@ -500,7 +500,7 @@ impl<'a> ErrorReporting for InferCtxt<'a> { outlive the enclosing closure", ty::local_var_name_str(self.tcx, id).get() - .to_str()).as_slice()); + .to_string()).as_slice()); note_and_explain_region( self.tcx, "captured variable is valid for ", @@ -895,9 +895,9 @@ impl<'a> Rebuilder<'a> { ident: ty_param.ident, id: ty_param.id, bounds: bounds, + unbound: ty_param.unbound.clone(), default: ty_param.default, span: ty_param.span, - sized: ty_param.sized, } }) } @@ -947,16 +947,16 @@ impl<'a> Rebuilder<'a> { -> Option<ast::ExplicitSelf_> { match expl_self_opt { Some(expl_self) => match expl_self { - ast::SelfRegion(lt_opt, muta) => match lt_opt { + ast::SelfRegion(lt_opt, muta, id) => match lt_opt { Some(lt) => if region_names.contains(<.name) { - return Some(ast::SelfRegion(Some(lifetime), muta)); + return Some(ast::SelfRegion(Some(lifetime), muta, id)); }, None => { let anon = self.cur_anon.get(); self.inc_and_offset_cur_anon(1); if anon_nums.contains(&anon) { self.track_anon(anon); - return Some(ast::SelfRegion(Some(lifetime), muta)); + return Some(ast::SelfRegion(Some(lifetime), muta, id)); } } }, @@ -1046,7 +1046,7 @@ impl<'a> Rebuilder<'a> { .sess .fatal(format!( "unbound path {}", - pprust::path_to_str(path)).as_slice()) + pprust::path_to_string(path)).as_slice()) } Some(&d) => d }; @@ -1231,7 +1231,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { opt_explicit_self: Option<ast::ExplicitSelf_>, generics: &ast::Generics, span: codemap::Span) { - let suggested_fn = pprust::fun_to_str(decl, fn_style, ident, + let suggested_fn = pprust::fun_to_string(decl, fn_style, ident, opt_explicit_self, generics); let msg = format!("consider using an explicit lifetime \ parameter as shown: {}", suggested_fn); @@ -1249,11 +1249,11 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { infer::Coercion(_) => " for automatic coercion".to_string(), infer::LateBoundRegion(_, br) => { format!(" for {}in function call", - bound_region_to_str(self.tcx, "lifetime parameter ", true, br)) + bound_region_to_string(self.tcx, "lifetime parameter ", true, br)) } infer::BoundRegionInFnType(_, br) => { format!(" for {}in function type", - bound_region_to_str(self.tcx, "lifetime parameter ", true, br)) + bound_region_to_string(self.tcx, "lifetime parameter ", true, br)) } infer::EarlyBoundRegion(_, name) => { format!(" for lifetime parameter `{}", @@ -1265,7 +1265,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { } infer::UpvarRegion(ref upvar_id, _) => { format!(" for capture of `{}` by closure", - ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_str()) + ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string()) } }; @@ -1334,7 +1334,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { "...so that closure can access `{}`", ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_str()).as_slice()) + .to_string()).as_slice()) } infer::InfStackClosure(span) => { self.tcx.sess.span_note( @@ -1359,7 +1359,7 @@ impl<'a> ErrorReportingHelpers for InferCtxt<'a> { does not outlive the enclosing closure", ty::local_var_name_str( self.tcx, - id).get().to_str()).as_slice()); + id).get().to_string()).as_slice()); } infer::IndexSlice(span) => { self.tcx.sess.span_note( @@ -1508,7 +1508,7 @@ impl LifeGiver { let mut lifetime; loop { let mut s = String::from_str("'"); - s.push_str(num_to_str(self.counter.get()).as_slice()); + s.push_str(num_to_string(self.counter.get()).as_slice()); if !self.taken.contains(&s) { lifetime = name_to_dummy_lifetime( token::str_to_ident(s.as_slice()).name); @@ -1521,7 +1521,7 @@ impl LifeGiver { return lifetime; // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on - fn num_to_str(counter: uint) -> String { + fn num_to_string(counter: uint) -> String { let mut s = String::new(); let (n, r) = (counter/26 + 1, counter % 26); let letter: char = from_u32((r+97) as u32).unwrap(); diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/typeck/infer/glb.rs index d2c27330a94..b6628c22ae6 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/typeck/infer/glb.rs @@ -26,7 +26,7 @@ use syntax::ast::{NormalFn, UnsafeFn, NodeId}; use syntax::ast::{Onceness, FnStyle}; use std::collections::HashMap; use util::common::{indenter}; -use util::ppaux::mt_to_str; +use util::ppaux::mt_to_string; use util::ppaux::Repr; pub struct Glb<'f>(pub CombineFields<'f>); // "greatest lower bound" (common subtype) @@ -50,8 +50,8 @@ impl<'f> Combine for Glb<'f> { debug!("{}.mts({}, {})", self.tag(), - mt_to_str(tcx, a), - mt_to_str(tcx, b)); + mt_to_string(tcx, a), + mt_to_string(tcx, b)); match (a.mutbl, b.mutbl) { // If one side or both is mut, then the GLB must use diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/typeck/infer/lattice.rs index 1b3d96e474e..708eb498f84 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/typeck/infer/lattice.rs @@ -39,7 +39,7 @@ use middle::typeck::infer::*; use middle::typeck::infer::combine::*; use middle::typeck::infer::glb::Glb; use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::unify::{Root, UnifyKey}; +use middle::typeck::infer::unify::*; use middle::typeck::infer::sub::Sub; use util::ppaux::Repr; @@ -436,8 +436,7 @@ pub enum LatticeVarResult<K,T> { * - If the variables do not both have an upper bound, we will unify * the variables and return the unified variable, in which case the * result is a variable. This is indicated with a `VarResult` - * return. - */ + * return. */ pub fn lattice_vars<L:LatticeDir+Combine, T:LatticeValue, K:UnifyKey<Bounds<T>>>( diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/typeck/infer/lub.rs index 7ccffdfeb06..6a50038afe7 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/typeck/infer/lub.rs @@ -25,7 +25,7 @@ use syntax::ast::{Many, Once, NodeId}; use syntax::ast::{NormalFn, UnsafeFn}; use syntax::ast::{Onceness, FnStyle}; use syntax::ast::{MutMutable, MutImmutable}; -use util::ppaux::mt_to_str; +use util::ppaux::mt_to_string; use util::ppaux::Repr; pub struct Lub<'f>(pub CombineFields<'f>); // least-upper-bound: common supertype @@ -49,8 +49,8 @@ impl<'f> Combine for Lub<'f> { debug!("{}.mts({}, {})", self.tag(), - mt_to_str(tcx, a), - mt_to_str(tcx, b)); + mt_to_string(tcx, a), + mt_to_string(tcx, b)); if a.mutbl != b.mutbl { return Err(ty::terr_mutability) diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index b505536a59d..16e758df9db 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -44,7 +44,7 @@ use syntax::ast; use syntax::codemap; use syntax::codemap::Span; use util::common::indent; -use util::ppaux::{bound_region_to_str, ty_to_str, trait_ref_to_str, Repr}; +use util::ppaux::{bound_region_to_string, ty_to_string, trait_ref_to_string, Repr}; pub mod doc; pub mod macros; @@ -245,7 +245,7 @@ pub enum fixup_err { region_var_bound_by_region_var(RegionVid, RegionVid) } -pub fn fixup_err_to_str(f: fixup_err) -> String { +pub fn fixup_err_to_string(f: fixup_err) -> String { match f { unresolved_int_ty(_) => { "cannot determine the type of this integer; add a suffix to \ @@ -662,19 +662,19 @@ impl<'a> InferCtxt<'a> { self.report_region_errors(&errors); // see error_reporting.rs } - pub fn ty_to_str(&self, t: ty::t) -> String { - ty_to_str(self.tcx, + pub fn ty_to_string(&self, t: ty::t) -> String { + ty_to_string(self.tcx, self.resolve_type_vars_if_possible(t)) } - pub fn tys_to_str(&self, ts: &[ty::t]) -> String { - let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_str(*t)).collect(); + pub fn tys_to_string(&self, ts: &[ty::t]) -> String { + let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect(); format!("({})", tstrs.connect(", ")) } - pub fn trait_ref_to_str(&self, t: &ty::TraitRef) -> String { + pub fn trait_ref_to_string(&self, t: &ty::TraitRef) -> String { let t = self.resolve_type_vars_in_trait_ref_if_possible(t); - trait_ref_to_str(self.tcx, &t) + trait_ref_to_string(self.tcx, &t) } pub fn resolve_type_vars_if_possible(&self, typ: ty::t) -> ty::t { @@ -707,8 +707,8 @@ impl<'a> InferCtxt<'a> { self.tcx.sess.bug( format!("resolve_type_vars_if_possible() yielded {} \ when supplied with {}", - self.ty_to_str(dummy0), - self.ty_to_str(dummy1)).as_slice()); + self.ty_to_string(dummy0), + self.ty_to_string(dummy1)).as_slice()); } } } @@ -761,7 +761,7 @@ impl<'a> InferCtxt<'a> { Some(e) => { self.tcx.sess.span_err(sp, format!("{}{}", - mk_msg(Some(self.ty_to_str(e)), actual_ty), + mk_msg(Some(self.ty_to_string(e)), actual_ty), error_str).as_slice()); } } @@ -783,7 +783,7 @@ impl<'a> InferCtxt<'a> { return; } - self.type_error_message_str(sp, |_e, a| { mk_msg(a) }, self.ty_to_str(actual_ty), err); + self.type_error_message_str(sp, |_e, a| { mk_msg(a) }, self.ty_to_string(actual_ty), err); } pub fn report_mismatched_types(&self, @@ -800,7 +800,7 @@ impl<'a> InferCtxt<'a> { // if I leave out : String, it infers &str and complains |actual: String| { format!("mismatched types: expected `{}` but found `{}`", - self.ty_to_str(resolved_expected), + self.ty_to_string(resolved_expected), actual) } } @@ -819,7 +819,7 @@ impl<'a> InferCtxt<'a> { let rvar = self.next_region_var( BoundRegionInFnType(trace.origin.span(), br)); debug!("Bound region {} maps to {:?}", - bound_region_to_str(self.tcx, "", false, br), + bound_region_to_string(self.tcx, "", false, br), rvar); rvar }); diff --git a/src/librustc/middle/typeck/infer/resolve.rs b/src/librustc/middle/typeck/infer/resolve.rs index adfbe9de2d5..2ae95309d41 100644 --- a/src/librustc/middle/typeck/infer/resolve.rs +++ b/src/librustc/middle/typeck/infer/resolve.rs @@ -56,7 +56,7 @@ use middle::typeck::infer::{unresolved_float_ty, unresolved_int_ty}; use middle::typeck::infer::{unresolved_ty}; use syntax::codemap::Span; use util::common::indent; -use util::ppaux::{Repr, ty_to_str}; +use util::ppaux::{Repr, ty_to_string}; pub static resolve_nested_tvar: uint = 0b0000000001; pub static resolve_rvar: uint = 0b0000000010; @@ -121,7 +121,7 @@ impl<'a> ResolveState<'a> { self.err = None; debug!("Resolving {} (modes={:x})", - ty_to_str(self.infcx.tcx, typ), + ty_to_string(self.infcx.tcx, typ), self.modes); // n.b. This is a hokey mess because the current fold doesn't @@ -133,8 +133,8 @@ impl<'a> ResolveState<'a> { match self.err { None => { debug!("Resolved to {} + {} (modes={:x})", - ty_to_str(self.infcx.tcx, rty), - ty_to_str(self.infcx.tcx, rty), + ty_to_string(self.infcx.tcx, rty), + ty_to_string(self.infcx.tcx, rty), self.modes); return Ok(rty); } diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/typeck/infer/sub.rs index 856237c4bca..44c147bfe7f 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/typeck/infer/sub.rs @@ -22,7 +22,7 @@ use middle::typeck::infer::lub::Lub; use middle::typeck::infer::then; use middle::typeck::infer::{TypeTrace, Subtype}; use util::common::{indenter}; -use util::ppaux::{bound_region_to_str, Repr}; +use util::ppaux::{bound_region_to_string, Repr}; use syntax::ast::{Onceness, FnStyle, MutImmutable, MutMutable}; @@ -176,7 +176,7 @@ impl<'f> Combine for Sub<'f> { replace_late_bound_regions_in_fn_sig(self.get_ref().infcx.tcx, b, |br| { let skol = self.get_ref().infcx.region_vars.new_skolemized(br); debug!("Bound region {} skolemized to {:?}", - bound_region_to_str(self.get_ref().infcx.tcx, "", false, br), + bound_region_to_string(self.get_ref().infcx.tcx, "", false, br), skol); skol }) diff --git a/src/librustc/middle/typeck/infer/test.rs b/src/librustc/middle/typeck/infer/test.rs index ff9f855c987..e66dcd118c9 100644 --- a/src/librustc/middle/typeck/infer/test.rs +++ b/src/librustc/middle/typeck/infer/test.rs @@ -37,7 +37,7 @@ use syntax::codemap; use syntax::codemap::{Span, CodeMap, DUMMY_SP}; use syntax::diagnostic::{Level, RenderSpan, Bug, Fatal, Error, Warning, Note}; use syntax::ast; -use util::ppaux::{ty_to_str, UserString}; +use util::ppaux::{ty_to_string, UserString}; struct Env<'a> { krate: ast::Crate, @@ -225,16 +225,16 @@ impl<'a> Env<'a> { pub fn assert_subtype(&self, a: ty::t, b: ty::t) { if !self.is_subtype(a, b) { fail!("{} is not a subtype of {}, but it should be", - self.ty_to_str(a), - self.ty_to_str(b)); + self.ty_to_string(a), + self.ty_to_string(b)); } } pub fn assert_not_subtype(&self, a: ty::t, b: ty::t) { if self.is_subtype(a, b) { fail!("{} is a subtype of {}, but it shouldn't be", - self.ty_to_str(a), - self.ty_to_str(b)); + self.ty_to_string(a), + self.ty_to_string(b)); } } @@ -243,8 +243,8 @@ impl<'a> Env<'a> { self.assert_subtype(b, a); } - pub fn ty_to_str(&self, a: ty::t) -> String { - ty_to_str(self.tcx, a) + pub fn ty_to_string(&self, a: ty::t) -> String { + ty_to_string(self.tcx, a) } pub fn t_fn(&self, @@ -328,9 +328,9 @@ impl<'a> Env<'a> { /// Checks that `GLB(t1,t2) == t_glb` pub fn check_glb(&self, t1: ty::t, t2: ty::t, t_glb: ty::t) { debug!("check_glb(t1={}, t2={}, t_glb={})", - self.ty_to_str(t1), - self.ty_to_str(t2), - self.ty_to_str(t_glb)); + self.ty_to_string(t1), + self.ty_to_string(t2), + self.ty_to_string(t_glb)); match self.glb().tys(t1, t2) { Err(e) => { fail!("unexpected error computing LUB: {:?}", e) @@ -350,7 +350,7 @@ impl<'a> Env<'a> { match self.lub().tys(t1, t2) { Err(_) => {} Ok(t) => { - fail!("unexpected success computing LUB: {}", self.ty_to_str(t)) + fail!("unexpected success computing LUB: {}", self.ty_to_string(t)) } } } @@ -360,7 +360,7 @@ impl<'a> Env<'a> { match self.glb().tys(t1, t2) { Err(_) => {} Ok(t) => { - fail!("unexpected success computing GLB: {}", self.ty_to_str(t)) + fail!("unexpected success computing GLB: {}", self.ty_to_string(t)) } } } diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 7b6935df420..ad6864ba487 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -276,7 +276,7 @@ pub struct CrateCtxt<'a> { // Functions that write types into the node type table pub fn write_ty_to_tcx(tcx: &ty::ctxt, node_id: ast::NodeId, ty: ty::t) { - debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_str(tcx, ty)); + debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty)); assert!(!ty::type_needs_infer(ty)); tcx.node_types.borrow_mut().insert(node_id as uint, ty); } @@ -383,14 +383,14 @@ fn check_main_fn_ty(ccx: &CrateCtxt, require_same_types(tcx, None, false, main_span, main_t, se_ty, || { format!("main function expects type: `{}`", - ppaux::ty_to_str(ccx.tcx, se_ty)) + ppaux::ty_to_string(ccx.tcx, se_ty)) }); } _ => { tcx.sess.span_bug(main_span, format!("main has a non-function type: found \ `{}`", - ppaux::ty_to_str(tcx, + ppaux::ty_to_string(tcx, main_t)).as_slice()); } } @@ -436,7 +436,7 @@ fn check_start_fn_ty(ccx: &CrateCtxt, require_same_types(tcx, None, false, start_span, start_t, se_ty, || { format!("start function expects type: `{}`", - ppaux::ty_to_str(ccx.tcx, se_ty)) + ppaux::ty_to_string(ccx.tcx, se_ty)) }); } @@ -444,7 +444,7 @@ fn check_start_fn_ty(ccx: &CrateCtxt, tcx.sess.span_bug(start_span, format!("start has a non-function type: found \ `{}`", - ppaux::ty_to_str(tcx, + ppaux::ty_to_string(tcx, start_t)).as_slice()); } } diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index fb3ce391d8e..8b5d16620b0 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -547,7 +547,7 @@ impl<'a> ConstraintContext<'a> { None => { self.tcx().sess.bug(format!( "no inferred index entry for {}", - self.tcx().map.node_to_str(param_id)).as_slice()); + self.tcx().map.node_to_string(param_id)).as_slice()); } } } @@ -588,8 +588,8 @@ impl<'a> ConstraintContext<'a> { let is_inferred; macro_rules! cannot_happen { () => { { fail!("invalid parent: {:s} for {:s}", - tcx.map.node_to_str(parent_id), - tcx.map.node_to_str(param_id)); + tcx.map.node_to_string(parent_id), + tcx.map.node_to_string(param_id)); } } } match parent { @@ -658,7 +658,7 @@ impl<'a> ConstraintContext<'a> { InferredIndex(index): InferredIndex, variance: VarianceTermPtr<'a>) { debug!("add_constraint(index={}, variance={})", - index, variance.to_str()); + index, variance.to_string()); self.constraints.push(Constraint { inferred: InferredIndex(index), variance: variance }); } @@ -975,7 +975,7 @@ impl<'a> SolveContext<'a> { .param_id, old_value, new_value, - term.to_str()); + term.to_string()); *self.solutions.get_mut(inferred) = new_value; changed = true; diff --git a/src/librustc/plugin/registry.rs b/src/librustc/plugin/registry.rs index 587bedd502e..2581ba51c2e 100644 --- a/src/librustc/plugin/registry.rs +++ b/src/librustc/plugin/registry.rs @@ -13,7 +13,7 @@ use lint::LintPassObject; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT}; -use syntax::ext::base::{IdentTT, ItemDecorator, ItemModifier, BasicMacroExpander}; +use syntax::ext::base::{IdentTT, LetSyntaxTT, ItemDecorator, ItemModifier, BasicMacroExpander}; use syntax::ext::base::{MacroExpanderFn}; use syntax::codemap::Span; use syntax::parse::token; @@ -57,6 +57,8 @@ impl Registry { IdentTT(ext, _) => IdentTT(ext, Some(self.krate_span)), ItemDecorator(ext) => ItemDecorator(ext), ItemModifier(ext) => ItemModifier(ext), + // there's probably a nicer way to signal this: + LetSyntaxTT(_, _) => fail!("can't register a new LetSyntax!"), })); } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index f228ea32ae5..542bc68ef73 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -105,7 +105,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) BrFresh(_) => "an anonymous lifetime defined on".to_string(), _ => { format!("the lifetime {} as defined on", - bound_region_ptr_to_str(cx, fr.bound_region)) + bound_region_ptr_to_string(cx, fr.bound_region)) } }; @@ -145,11 +145,11 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) } } -pub fn bound_region_ptr_to_str(cx: &ctxt, br: BoundRegion) -> String { - bound_region_to_str(cx, "", false, br) +pub fn bound_region_ptr_to_string(cx: &ctxt, br: BoundRegion) -> String { + bound_region_to_string(cx, "", false, br) } -pub fn bound_region_to_str(cx: &ctxt, +pub fn bound_region_to_string(cx: &ctxt, prefix: &str, space: bool, br: BoundRegion) -> String { let space_str = if space { " " } else { "" }; @@ -170,11 +170,11 @@ pub fn bound_region_to_str(cx: &ctxt, // In general, if you are giving a region error message, // you should use `explain_region()` or, better yet, // `note_and_explain_region()` -pub fn region_ptr_to_str(cx: &ctxt, region: Region) -> String { - region_to_str(cx, "&", true, region) +pub fn region_ptr_to_string(cx: &ctxt, region: Region) -> String { + region_to_string(cx, "&", true, region) } -pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String { +pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String { let space_str = if space { " " } else { "" }; if cx.sess.verbose() { @@ -190,10 +190,10 @@ pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> St ty::ReEarlyBound(_, _, _, name) => { token::get_name(name).get().to_string() } - ty::ReLateBound(_, br) => bound_region_to_str(cx, prefix, space, br), - ty::ReFree(ref fr) => bound_region_to_str(cx, prefix, space, fr.bound_region), + ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br), + ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region), ty::ReInfer(ReSkolemized(_, br)) => { - bound_region_to_str(cx, prefix, space, br) + bound_region_to_string(cx, prefix, space, br) } ty::ReInfer(ReVar(_)) => prefix.to_string(), ty::ReStatic => format!("{}'static{}", prefix, space_str), @@ -201,45 +201,55 @@ pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> St } } -pub fn mutability_to_str(m: ast::Mutability) -> String { +pub fn mutability_to_string(m: ast::Mutability) -> String { match m { ast::MutMutable => "mut ".to_string(), ast::MutImmutable => "".to_string(), } } -pub fn mt_to_str(cx: &ctxt, m: &mt) -> String { - format!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty)) +pub fn mt_to_string(cx: &ctxt, m: &mt) -> String { + format!("{}{}", mutability_to_string(m.mutbl), ty_to_string(cx, m.ty)) } +#[cfg(stage0)] pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> String { + trait_store_to_string(cx, s) +} + +pub fn trait_store_to_string(cx: &ctxt, s: ty::TraitStore) -> String { match s { ty::UniqTraitStore => "Box ".to_string(), ty::RegionTraitStore(r, m) => { - format!("{}{}", region_ptr_to_str(cx, r), mutability_to_str(m)) + format!("{}{}", region_ptr_to_string(cx, r), mutability_to_string(m)) } } } -pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> String) -> String { +pub fn vec_map_to_string<T>(ts: &[T], f: |t: &T| -> String) -> String { let tstrs = ts.iter().map(f).collect::<Vec<String>>(); format!("[{}]", tstrs.connect(", ")) } -pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> String { +pub fn fn_sig_to_string(cx: &ctxt, typ: &ty::FnSig) -> String { format!("fn{}{} -> {}", typ.binder_id, typ.inputs.repr(cx), typ.output.repr(cx)) } -pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> String { +pub fn trait_ref_to_string(cx: &ctxt, trait_ref: &ty::TraitRef) -> String { trait_ref.user_string(cx).to_string() } +#[cfg(stage0)] pub fn ty_to_str(cx: &ctxt, typ: t) -> String { - fn fn_input_to_str(cx: &ctxt, input: ty::t) -> String { - ty_to_str(cx, input).to_string() + ty_to_string(cx, typ) +} + +pub fn ty_to_string(cx: &ctxt, typ: t) -> String { + fn fn_input_to_string(cx: &ctxt, input: ty::t) -> String { + ty_to_string(cx, input).to_string() } - fn bare_fn_to_str(cx: &ctxt, + fn bare_fn_to_string(cx: &ctxt, fn_style: ast::FnStyle, abi: abi::Abi, ident: Option<ast::Ident>, @@ -249,13 +259,13 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { match fn_style { ast::NormalFn => {} _ => { - s.push_str(fn_style.to_str().as_slice()); + s.push_str(fn_style.to_string().as_slice()); s.push_char(' '); } }; if abi != abi::Rust { - s.push_str(format!("extern {} ", abi.to_str()).as_slice()); + s.push_str(format!("extern {} ", abi.to_string()).as_slice()); }; s.push_str("fn"); @@ -268,25 +278,25 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { _ => { } } - push_sig_to_str(cx, &mut s, '(', ')', sig); + push_sig_to_string(cx, &mut s, '(', ')', sig); s } - fn closure_to_str(cx: &ctxt, cty: &ty::ClosureTy) -> String { + fn closure_to_string(cx: &ctxt, cty: &ty::ClosureTy) -> String { let mut s = String::new(); match cty.store { ty::UniqTraitStore => {} ty::RegionTraitStore(region, _) => { - s.push_str(region_to_str(cx, "", true, region).as_slice()); + s.push_str(region_to_string(cx, "", true, region).as_slice()); } } match cty.fn_style { ast::NormalFn => {} _ => { - s.push_str(cty.fn_style.to_str().as_slice()); + s.push_str(cty.fn_style.to_string().as_slice()); s.push_char(' '); } }; @@ -295,14 +305,14 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { ty::UniqTraitStore => { assert_eq!(cty.onceness, ast::Once); s.push_str("proc"); - push_sig_to_str(cx, &mut s, '(', ')', &cty.sig); + push_sig_to_string(cx, &mut s, '(', ')', &cty.sig); } ty::RegionTraitStore(..) => { match cty.onceness { ast::Many => {} ast::Once => s.push_str("once ") } - push_sig_to_str(cx, &mut s, '|', '|', &cty.sig); + push_sig_to_string(cx, &mut s, '|', '|', &cty.sig); } } @@ -314,13 +324,13 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { s } - fn push_sig_to_str(cx: &ctxt, + fn push_sig_to_string(cx: &ctxt, s: &mut String, bra: char, ket: char, sig: &ty::FnSig) { s.push_char(bra); - let strs: Vec<String> = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect(); + let strs: Vec<String> = sig.inputs.iter().map(|a| fn_input_to_string(cx, *a)).collect(); s.push_str(strs.connect(", ").as_slice()); if sig.variadic { s.push_str(", ..."); @@ -332,7 +342,7 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { if ty::type_is_bot(sig.output) { s.push_char('!'); } else { - s.push_str(ty_to_str(cx, sig.output).as_slice()); + s.push_str(ty_to_string(cx, sig.output).as_slice()); } } } @@ -349,33 +359,33 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { ty_bot => "!".to_string(), ty_bool => "bool".to_string(), ty_char => "char".to_string(), - ty_int(t) => ast_util::int_ty_to_str(t, None).to_string(), - ty_uint(t) => ast_util::uint_ty_to_str(t, None).to_string(), - ty_float(t) => ast_util::float_ty_to_str(t).to_string(), - ty_box(typ) => format!("Gc<{}>", ty_to_str(cx, typ)), - ty_uniq(typ) => format!("Box<{}>", ty_to_str(cx, typ)), + ty_int(t) => ast_util::int_ty_to_string(t, None).to_string(), + ty_uint(t) => ast_util::uint_ty_to_string(t, None).to_string(), + ty_float(t) => ast_util::float_ty_to_string(t).to_string(), + ty_box(typ) => format!("Gc<{}>", ty_to_string(cx, typ)), + ty_uniq(typ) => format!("Box<{}>", ty_to_string(cx, typ)), ty_ptr(ref tm) => { format!("*{} {}", match tm.mutbl { ast::MutMutable => "mut", ast::MutImmutable => "const", - }, ty_to_str(cx, tm.ty)) + }, ty_to_string(cx, tm.ty)) } ty_rptr(r, ref tm) => { - let mut buf = region_ptr_to_str(cx, r); - buf.push_str(mt_to_str(cx, tm).as_slice()); + let mut buf = region_ptr_to_string(cx, r); + buf.push_str(mt_to_string(cx, tm).as_slice()); buf } ty_tup(ref elems) => { - let strs: Vec<String> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect(); + let strs: Vec<String> = elems.iter().map(|elem| ty_to_string(cx, *elem)).collect(); format!("({})", strs.connect(",")) } ty_closure(ref f) => { - closure_to_str(cx, *f) + closure_to_string(cx, *f) } ty_bare_fn(ref f) => { - bare_fn_to_str(cx, f.fn_style, f.abi, None, &f.sig) + bare_fn_to_string(cx, f.fn_style, f.abi, None, &f.sig) } - ty_infer(infer_ty) => infer_ty.to_str(), + ty_infer(infer_ty) => infer_ty.to_string(), ty_err => "[type error]".to_string(), ty_param(ParamTy {idx: id, def_id: did, ..}) => { let ident = match cx.ty_param_defs.borrow().find(&did.node) { @@ -413,9 +423,9 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> String { ty_vec(ref mt, sz) => { match sz { Some(n) => { - format!("[{}, .. {}]", mt_to_str(cx, mt), n) + format!("[{}, .. {}]", mt_to_string(cx, mt), n) } - None => format!("[{}]", ty_to_str(cx, mt.ty)), + None => format!("[{}]", ty_to_string(cx, mt.ty)), } } } @@ -433,7 +443,7 @@ pub fn parameterized(cx: &ctxt, subst::ErasedRegions => { } subst::NonerasedRegions(ref regions) => { for &r in regions.iter() { - let s = region_to_str(cx, "", false, r); + let s = region_to_string(cx, "", false, r); if !s.is_empty() { strs.push(s) } else { @@ -463,7 +473,7 @@ pub fn parameterized(cx: &ctxt, }; for t in tps.slice_to(tps.len() - num_defaults).iter() { - strs.push(ty_to_str(cx, *t)) + strs.push(ty_to_string(cx, *t)) } if cx.sess.verbose() { @@ -530,7 +540,7 @@ impl<T:Repr> Repr for Box<T> { } fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String { - vec_map_to_str(v, |t| t.repr(tcx)) + vec_map_to_string(v, |t| t.repr(tcx)) } impl<'a, T:Repr> Repr for &'a [T] { @@ -576,13 +586,13 @@ impl Repr for ty::RegionParameterDef { impl Repr for ty::t { fn repr(&self, tcx: &ctxt) -> String { - ty_to_str(tcx, *self) + ty_to_string(tcx, *self) } } impl Repr for ty::mt { fn repr(&self, tcx: &ctxt) -> String { - mt_to_str(tcx, self) + mt_to_string(tcx, self) } } @@ -639,25 +649,25 @@ impl Repr for ty::ParamBounds { impl Repr for ty::TraitRef { fn repr(&self, tcx: &ctxt) -> String { - trait_ref_to_str(tcx, self) + trait_ref_to_string(tcx, self) } } impl Repr for ast::Expr { fn repr(&self, _tcx: &ctxt) -> String { - format!("expr({}: {})", self.id, pprust::expr_to_str(self)) + format!("expr({}: {})", self.id, pprust::expr_to_string(self)) } } impl Repr for ast::Path { fn repr(&self, _tcx: &ctxt) -> String { - format!("path({})", pprust::path_to_str(self)) + format!("path({})", pprust::path_to_string(self)) } } impl Repr for ast::Item { fn repr(&self, tcx: &ctxt) -> String { - format!("item({})", tcx.map.node_to_str(self.id)) + format!("item({})", tcx.map.node_to_string(self.id)) } } @@ -665,13 +675,13 @@ impl Repr for ast::Stmt { fn repr(&self, _tcx: &ctxt) -> String { format!("stmt({}: {})", ast_util::stmt_id(self), - pprust::stmt_to_str(self)) + pprust::stmt_to_string(self)) } } impl Repr for ast::Pat { fn repr(&self, _tcx: &ctxt) -> String { - format!("pat({}: {})", self.id, pprust::pat_to_str(self)) + format!("pat({}: {})", self.id, pprust::pat_to_string(self)) } } @@ -787,10 +797,10 @@ impl Repr for ty::ItemVariances { impl Repr for ty::Variance { fn repr(&self, _: &ctxt) -> String { - // The first `.to_str()` returns a &'static str (it is not an implementation - // of the ToStr trait). Because of that, we need to call `.to_str()` again + // The first `.to_string()` returns a &'static str (it is not an implementation + // of the ToString trait). Because of that, we need to call `.to_string()` again // if we want to have a `String`. - self.to_str().to_str() + self.to_string().to_string() } } @@ -835,14 +845,14 @@ impl Repr for ty::BareFnTy { fn repr(&self, tcx: &ctxt) -> String { format!("BareFnTy {{fn_style: {:?}, abi: {}, sig: {}}}", self.fn_style, - self.abi.to_str(), + self.abi.to_string(), self.sig.repr(tcx)) } } impl Repr for ty::FnSig { fn repr(&self, tcx: &ctxt) -> String { - fn_sig_to_str(tcx, self) + fn_sig_to_string(tcx, self) } } @@ -892,7 +902,7 @@ impl Repr for typeck::MethodObject { impl Repr for ty::TraitStore { fn repr(&self, tcx: &ctxt) -> String { - trait_store_to_str(tcx, *self) + trait_store_to_string(tcx, *self) } } @@ -922,7 +932,7 @@ impl Repr for ty::BuiltinBounds { impl Repr for Span { fn repr(&self, tcx: &ctxt) -> String { - tcx.sess.codemap().span_to_str(*self).to_string() + tcx.sess.codemap().span_to_string(*self).to_string() } } @@ -953,7 +963,7 @@ impl UserString for ty::TraitRef { impl UserString for ty::t { fn user_string(&self, tcx: &ctxt) -> String { - ty_to_str(tcx, *self) + ty_to_string(tcx, *self) } } @@ -965,13 +975,13 @@ impl UserString for ast::Ident { impl Repr for abi::Abi { fn repr(&self, _tcx: &ctxt) -> String { - self.to_str() + self.to_string() } } impl UserString for abi::Abi { fn user_string(&self, _tcx: &ctxt) -> String { - self.to_str() + self.to_string() } } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 2d498e7f302..b3891432e21 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -99,7 +99,7 @@ fn try_inline_def(cx: &core::DocContext, cx.inlined.borrow_mut().get_mut_ref().insert(did); ret.push(clean::Item { source: clean::Span::empty(), - name: Some(fqn.last().unwrap().to_str()), + name: Some(fqn.last().unwrap().to_string()), attrs: load_attrs(tcx, did), inner: inner, visibility: Some(ast::Public), @@ -136,7 +136,7 @@ pub fn record_extern_fqn(cx: &core::DocContext, match cx.maybe_typed { core::Typed(ref tcx) => { let fqn = csearch::get_item_path(tcx, did); - let fqn = fqn.move_iter().map(|i| i.to_str()).collect(); + let fqn = fqn.move_iter().map(|i| i.to_string()).collect(); cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind)); } core::NotTyped(..) => {} diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 1ddd97e2ed4..af0b6a1cb21 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -408,7 +408,7 @@ impl Clean<Attribute> for ast::MetaItem { List(s.get().to_string(), l.clean().move_iter().collect()) } ast::MetaNameValue(ref s, ref v) => { - NameValue(s.get().to_string(), lit_to_str(v)) + NameValue(s.get().to_string(), lit_to_string(v)) } } } @@ -539,7 +539,7 @@ impl Clean<TyParamBound> for ty::BuiltinBound { external_path("Share", &empty)), }; let fqn = csearch::get_item_path(tcx, did); - let fqn = fqn.move_iter().map(|i| i.to_str()).collect(); + let fqn = fqn.move_iter().map(|i| i.to_string()).collect(); cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, TypeTrait)); TraitBound(ResolvedPath { @@ -558,7 +558,7 @@ impl Clean<TyParamBound> for ty::TraitRef { core::NotTyped(_) => return RegionBound, }; let fqn = csearch::get_item_path(tcx, self.def_id); - let fqn = fqn.move_iter().map(|i| i.to_str()) + let fqn = fqn.move_iter().map(|i| i.to_string()) .collect::<Vec<String>>(); let path = external_path(fqn.last().unwrap().as_slice(), &self.substs); @@ -775,9 +775,9 @@ impl Clean<SelfTy> for ast::ExplicitSelf_ { fn clean(&self) -> SelfTy { match *self { ast::SelfStatic => SelfStatic, - ast::SelfValue => SelfValue, - ast::SelfUniq => SelfOwned, - ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()), + ast::SelfValue(_) => SelfValue, + ast::SelfUniq(_) => SelfOwned, + ast::SelfRegion(lt, mt, _) => SelfBorrowed(lt.clean(), mt.clean()), } } } @@ -1137,7 +1137,7 @@ impl Primitive { return None } - pub fn to_str(&self) -> &'static str { + pub fn to_string(&self) -> &'static str { match *self { Int => "int", I8 => "i8", @@ -1163,7 +1163,7 @@ impl Primitive { pub fn to_url_str(&self) -> &'static str { match *self { Unit => "unit", - other => other.to_str(), + other => other.to_string(), } } @@ -1242,7 +1242,7 @@ impl Clean<Type> for ty::t { lifetimes: Vec::new(), type_params: Vec::new() }, decl: (ast_util::local_def(0), &fty.sig).clean(), - abi: fty.abi.to_str(), + abi: fty.abi.to_string(), }), ty::ty_closure(ref fty) => { let decl = box ClosureDecl { @@ -1262,14 +1262,14 @@ impl Clean<Type> for ty::t { ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => { let fqn = csearch::get_item_path(get_cx().tcx(), did); let fqn: Vec<String> = fqn.move_iter().map(|i| { - i.to_str() + i.to_string() }).collect(); let kind = match ty::get(*self).sty { ty::ty_struct(..) => TypeStruct, ty::ty_trait(..) => TypeTrait, _ => TypeEnum, }; - let path = external_path(fqn.last().unwrap().to_str().as_slice(), + let path = external_path(fqn.last().unwrap().to_string().as_slice(), substs); get_cx().external_paths.borrow_mut().get_mut_ref() .insert(did, (fqn, kind)); @@ -1577,7 +1577,7 @@ impl Clean<PathSegment> for ast::PathSegment { } } -fn path_to_str(p: &ast::Path) -> String { +fn path_to_string(p: &ast::Path) -> String { let mut s = String::new(); let mut first = true; for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) { @@ -1643,7 +1643,7 @@ impl Clean<BareFunctionDecl> for ast::BareFnTy { type_params: Vec::new(), }, decl: self.decl.clean(), - abi: self.abi.to_str(), + abi: self.abi.to_string(), } } } @@ -1916,7 +1916,7 @@ impl ToSource for syntax::codemap::Span { } } -fn lit_to_str(lit: &ast::Lit) -> String { +fn lit_to_string(lit: &ast::Lit) -> String { match lit.node { ast::LitStr(ref st, _) => st.get().to_string(), ast::LitBinary(ref data) => format!("{:?}", data.as_slice()), @@ -1929,12 +1929,12 @@ fn lit_to_str(lit: &ast::Lit) -> String { res }, ast::LitChar(c) => format!("'{}'", c), - ast::LitInt(i, _t) => i.to_str(), - ast::LitUint(u, _t) => u.to_str(), - ast::LitIntUnsuffixed(i) => i.to_str(), + ast::LitInt(i, _t) => i.to_string(), + ast::LitUint(u, _t) => u.to_string(), + ast::LitIntUnsuffixed(i) => i.to_string(), ast::LitFloat(ref f, _t) => f.get().to_string(), ast::LitFloatUnsuffixed(ref f) => f.get().to_string(), - ast::LitBool(b) => b.to_str(), + ast::LitBool(b) => b.to_string(), ast::LitNil => "".to_string(), } } @@ -1947,7 +1947,7 @@ fn name_from_pat(p: &ast::Pat) -> String { PatWild => "_".to_string(), PatWildMulti => "..".to_string(), PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(), - PatEnum(ref p, _) => path_to_str(p), + PatEnum(ref p, _) => path_to_string(p), PatStruct(..) => fail!("tried to get argument name from pat_struct, \ which is not allowed in function arguments"), PatTup(..) => "(tuple arg NYI)".to_string(), diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index cec665768d1..382e299d28d 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -351,7 +351,7 @@ impl fmt::Show for clean::Type { tybounds(f, typarams) } clean::Self(..) => f.write("Self".as_bytes()), - clean::Primitive(prim) => primitive_link(f, prim, prim.to_str()), + clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()), clean::Closure(ref decl, ref region) => { write!(f, "{style}{lifetimes}|{args}|{bounds}{arrow}", style = FnStyleSpace(decl.fn_style), @@ -405,7 +405,7 @@ impl fmt::Show for clean::Type { } else { let mut m = decl.bounds .iter() - .map(|s| s.to_str()); + .map(|s| s.to_string()); format!( ": {}", m.collect::<Vec<String>>().connect(" + ")) @@ -607,7 +607,7 @@ impl<'a> fmt::Show for Stability<'a> { match *stab { Some(ref stability) => { write!(f, "<a class='stability {lvl}' title='{reason}'>{lvl}</a>", - lvl = stability.level.to_str(), + lvl = stability.level.to_string(), reason = stability.text) } None => Ok(()) @@ -621,7 +621,7 @@ impl<'a> fmt::Show for ConciseStability<'a> { match *stab { Some(ref stability) => { write!(f, "<a class='stability {lvl}' title='{lvl}{colon}{reason}'></a>", - lvl = stability.level.to_str(), + lvl = stability.level.to_string(), colon = if stability.text.len() > 0 { ": " } else { "" }, reason = stability.text) } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index daa9ee3da84..3cb5cdc0439 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -18,7 +18,6 @@ use std::io; use syntax::parse; use syntax::parse::lexer; -use syntax::codemap::{BytePos, Span}; use html::escape::Escape; @@ -59,38 +58,30 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, None => {} } try!(write!(out, "class='rust {}'>\n", class.unwrap_or(""))); - let mut last = BytePos(0); let mut is_attribute = false; let mut is_macro = false; let mut is_macro_nonterminal = false; loop { let next = lexer.next_token(); - let test = if next.tok == t::EOF {lexer.pos} else {next.sp.lo}; - - // The lexer consumes all whitespace and non-doc-comments when iterating - // between tokens. If this token isn't directly adjacent to our last - // token, then we need to emit the whitespace/comment. - // - // If the gap has any '/' characters then we consider the whole thing a - // comment. This will classify some whitespace as a comment, but that - // doesn't matter too much for syntax highlighting purposes. - if test > last { - let snip = sess.span_diagnostic.cm.span_to_snippet(Span { - lo: last, - hi: test, - expn_info: None, - }).unwrap(); - if snip.as_slice().contains("/") { - try!(write!(out, "<span class='comment'>{}</span>", - Escape(snip.as_slice()))); - } else { - try!(write!(out, "{}", Escape(snip.as_slice()))); - } - } - last = next.sp.hi; + + let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap(); + if next.tok == t::EOF { break } let klass = match next.tok { + t::WS => { + try!(write!(out, "{}", Escape(snip(next.sp).as_slice()))); + continue + }, + t::COMMENT => { + try!(write!(out, "<span class='comment'>{}</span>", + Escape(snip(next.sp).as_slice()))); + continue + }, + t::SHEBANG(s) => { + try!(write!(out, "{}", Escape(s.as_str()))); + continue + }, // If this '&' token is directly adjacent to another token, assume // that it's the address-of operator instead of the and-operator. // This allows us to give all pointers their own class (`Box` and @@ -110,7 +101,7 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, // miscellaneous, no highlighting t::DOT | t::DOTDOT | t::DOTDOTDOT | t::COMMA | t::SEMI | t::COLON | t::MOD_SEP | t::LARROW | t::LPAREN | - t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE => "", + t::RPAREN | t::LBRACKET | t::LBRACE | t::RBRACE | t::QUESTION => "", t::DOLLAR => { if t::is_ident(&lexer.peek().tok) { is_macro_nonterminal = true; @@ -144,8 +135,7 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader, t::LIT_CHAR(..) | t::LIT_STR(..) | t::LIT_STR_RAW(..) => "string", // number literals - t::LIT_INT(..) | t::LIT_UINT(..) | t::LIT_INT_UNSUFFIXED(..) | - t::LIT_FLOAT(..) | t::LIT_FLOAT_UNSUFFIXED(..) => "number", + t::LIT_INTEGER(..) | t::LIT_FLOAT(..) => "number", // keywords are also included in the identifier set t::IDENT(ident, _is_mod_sep) => { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index de4bbeb6e30..19a9bcb9a17 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -229,7 +229,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { // Transform the contents of the header into a hyphenated string let id = s.as_slice().words().map(|s| { match s.to_ascii_opt() { - Some(s) => s.to_lower().into_str(), + Some(s) => s.to_lower().into_string(), None => s.to_string() } }).collect::<Vec<String>>().connect("-"); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 891b15d164c..70edbcf86e1 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -428,7 +428,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String> } try!(write!(&mut w, r#"[{:u},"{}","{}",{}"#, item.ty, item.name, path, - item.desc.to_json().to_str())); + item.desc.to_json().to_string())); match item.parent { Some(nodeid) => { let pathid = *nodeid_to_pathid.find(&nodeid).unwrap(); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 7d6f44f5d16..b53363738ac 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -367,7 +367,7 @@ fn json_input(input: &str) -> Result<Output, String> { } }; match json::from_reader(&mut input) { - Err(s) => Err(s.to_str()), + Err(s) => Err(s.to_string()), Ok(json::Object(obj)) => { let mut obj = obj; // Make sure the schema is what we expect diff --git a/src/librustrt/c_str.rs b/src/librustrt/c_str.rs index 161d3ed5e65..06f4e71871d 100644 --- a/src/librustrt/c_str.rs +++ b/src/librustrt/c_str.rs @@ -804,7 +804,7 @@ mod bench { Mary had a little lamb, Little lamb Mary had a little lamb, Little lamb"; - fn bench_to_str(b: &mut Bencher, s: &str) { + fn bench_to_string(b: &mut Bencher, s: &str) { b.iter(|| { let c_str = s.to_c_str(); check(s, c_str.as_ptr()); @@ -813,17 +813,17 @@ mod bench { #[bench] fn bench_to_c_str_short(b: &mut Bencher) { - bench_to_str(b, s_short) + bench_to_string(b, s_short) } #[bench] fn bench_to_c_str_medium(b: &mut Bencher) { - bench_to_str(b, s_medium) + bench_to_string(b, s_medium) } #[bench] fn bench_to_c_str_long(b: &mut Bencher) { - bench_to_str(b, s_long) + bench_to_string(b, s_long) } fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) { diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index a9e6a6a4a9a..972a28dda62 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -393,7 +393,7 @@ impl fmt::Show for UvError { #[test] fn error_smoke_test() { let err: UvError = UvError(uvll::EOF); - assert_eq!(err.to_str(), "EOF: end of file".to_string()); + assert_eq!(err.to_string(), "EOF: end of file".to_string()); } #[cfg(unix)] diff --git a/src/librustuv/net.rs b/src/librustuv/net.rs index ddcaeccbc19..45f93d9d128 100644 --- a/src/librustuv/net.rs +++ b/src/librustuv/net.rs @@ -676,7 +676,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { fn join_multicast(&mut self, multi: rtio::IpAddr) -> Result<(), IoError> { let _m = self.fire_homing_missile(); status_to_io_result(unsafe { - multi.to_str().with_c_str(|m_addr| { + multi.to_string().with_c_str(|m_addr| { uvll::uv_udp_set_membership(self.handle, m_addr, ptr::null(), uvll::UV_JOIN_GROUP) @@ -687,7 +687,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { fn leave_multicast(&mut self, multi: rtio::IpAddr) -> Result<(), IoError> { let _m = self.fire_homing_missile(); status_to_io_result(unsafe { - multi.to_str().with_c_str(|m_addr| { + multi.to_string().with_c_str(|m_addr| { uvll::uv_udp_set_membership(self.handle, m_addr, ptr::null(), uvll::UV_LEAVE_GROUP) diff --git a/src/libsemver/lib.rs b/src/libsemver/lib.rs index 31a065a1449..95eac25ab5b 100644 --- a/src/libsemver/lib.rs +++ b/src/libsemver/lib.rs @@ -270,7 +270,7 @@ pub fn parse(s: &str) -> Option<Version> { let v = parse_iter(&mut s.chars()); match v { Some(v) => { - if v.to_str().equiv(&s) { + if v.to_string().equiv(&s) { Some(v) } else { None @@ -391,11 +391,11 @@ fn test_show() { } #[test] -fn test_to_str() { - assert_eq!(parse("1.2.3").unwrap().to_str(), "1.2.3".to_string()); - assert_eq!(parse("1.2.3-alpha1").unwrap().to_str(), "1.2.3-alpha1".to_string()); - assert_eq!(parse("1.2.3+build.42").unwrap().to_str(), "1.2.3+build.42".to_string()); - assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_str(), "1.2.3-alpha1+42".to_string()); +fn test_to_string() { + assert_eq!(parse("1.2.3").unwrap().to_string(), "1.2.3".to_string()); + assert_eq!(parse("1.2.3-alpha1").unwrap().to_string(), "1.2.3-alpha1".to_string()); + assert_eq!(parse("1.2.3+build.42").unwrap().to_string(), "1.2.3+build.42".to_string()); + assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_string(), "1.2.3-alpha1+42".to_string()); } #[test] diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index f4e5c27a14b..df4d3437b1c 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -130,7 +130,7 @@ fn main() { // Serialize using `ToJson` let test2 = TestStruct1 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]}; let tjson: json::Json = test2.to_json(); - let json_str: String = tjson.to_str(); + let json_str: String = tjson.to_string(); // Deserialize like before let decoded: TestStruct1 = json::decode(json_str.as_slice()).unwrap(); @@ -2202,59 +2202,59 @@ mod tests { #[test] fn test_write_null() { - assert_eq!(Null.to_str().into_string(), "null".to_string()); + assert_eq!(Null.to_string().into_string(), "null".to_string()); assert_eq!(Null.to_pretty_str().into_string(), "null".to_string()); } #[test] fn test_write_number() { - assert_eq!(Number(3.0).to_str().into_string(), "3".to_string()); + assert_eq!(Number(3.0).to_string().into_string(), "3".to_string()); assert_eq!(Number(3.0).to_pretty_str().into_string(), "3".to_string()); - assert_eq!(Number(3.1).to_str().into_string(), "3.1".to_string()); + assert_eq!(Number(3.1).to_string().into_string(), "3.1".to_string()); assert_eq!(Number(3.1).to_pretty_str().into_string(), "3.1".to_string()); - assert_eq!(Number(-1.5).to_str().into_string(), "-1.5".to_string()); + assert_eq!(Number(-1.5).to_string().into_string(), "-1.5".to_string()); assert_eq!(Number(-1.5).to_pretty_str().into_string(), "-1.5".to_string()); - assert_eq!(Number(0.5).to_str().into_string(), "0.5".to_string()); + assert_eq!(Number(0.5).to_string().into_string(), "0.5".to_string()); assert_eq!(Number(0.5).to_pretty_str().into_string(), "0.5".to_string()); - assert_eq!(Number(f64::NAN).to_str().into_string(), "null".to_string()); + assert_eq!(Number(f64::NAN).to_string().into_string(), "null".to_string()); assert_eq!(Number(f64::NAN).to_pretty_str().into_string(), "null".to_string()); - assert_eq!(Number(f64::INFINITY).to_str().into_string(), "null".to_string()); + assert_eq!(Number(f64::INFINITY).to_string().into_string(), "null".to_string()); assert_eq!(Number(f64::INFINITY).to_pretty_str().into_string(), "null".to_string()); - assert_eq!(Number(f64::NEG_INFINITY).to_str().into_string(), "null".to_string()); + assert_eq!(Number(f64::NEG_INFINITY).to_string().into_string(), "null".to_string()); assert_eq!(Number(f64::NEG_INFINITY).to_pretty_str().into_string(), "null".to_string()); } #[test] fn test_write_str() { - assert_eq!(String("".to_string()).to_str().into_string(), "\"\"".to_string()); + assert_eq!(String("".to_string()).to_string().into_string(), "\"\"".to_string()); assert_eq!(String("".to_string()).to_pretty_str().into_string(), "\"\"".to_string()); - assert_eq!(String("foo".to_string()).to_str().into_string(), "\"foo\"".to_string()); + assert_eq!(String("foo".to_string()).to_string().into_string(), "\"foo\"".to_string()); assert_eq!(String("foo".to_string()).to_pretty_str().into_string(), "\"foo\"".to_string()); } #[test] fn test_write_bool() { - assert_eq!(Boolean(true).to_str().into_string(), "true".to_string()); + assert_eq!(Boolean(true).to_string().into_string(), "true".to_string()); assert_eq!(Boolean(true).to_pretty_str().into_string(), "true".to_string()); - assert_eq!(Boolean(false).to_str().into_string(), "false".to_string()); + assert_eq!(Boolean(false).to_string().into_string(), "false".to_string()); assert_eq!(Boolean(false).to_pretty_str().into_string(), "false".to_string()); } #[test] fn test_write_list() { - assert_eq!(List(vec![]).to_str().into_string(), "[]".to_string()); + assert_eq!(List(vec![]).to_string().into_string(), "[]".to_string()); assert_eq!(List(vec![]).to_pretty_str().into_string(), "[]".to_string()); - assert_eq!(List(vec![Boolean(true)]).to_str().into_string(), "[true]".to_string()); + assert_eq!(List(vec![Boolean(true)]).to_string().into_string(), "[true]".to_string()); assert_eq!( List(vec![Boolean(true)]).to_pretty_str().into_string(), "\ @@ -2268,7 +2268,7 @@ mod tests { Null, List(vec![String("foo\nbar".to_string()), Number(3.5)])]); - assert_eq!(long_test_list.to_str().into_string(), + assert_eq!(long_test_list.to_string().into_string(), "[false,null,[\"foo\\nbar\",3.5]]".to_string()); assert_eq!( long_test_list.to_pretty_str().into_string(), @@ -2286,13 +2286,13 @@ mod tests { #[test] fn test_write_object() { - assert_eq!(mk_object([]).to_str().into_string(), "{}".to_string()); + assert_eq!(mk_object([]).to_string().into_string(), "{}".to_string()); assert_eq!(mk_object([]).to_pretty_str().into_string(), "{}".to_string()); assert_eq!( mk_object([ ("a".to_string(), Boolean(true)) - ]).to_str().into_string(), + ]).to_string().into_string(), "{\"a\":true}".to_string() ); assert_eq!( @@ -2311,7 +2311,7 @@ mod tests { ]); assert_eq!( - complex_obj.to_str().into_string(), + complex_obj.to_string().into_string(), "{\ \"b\":[\ {\"c\":\"\\f\\r\"},\ @@ -2344,7 +2344,7 @@ mod tests { // We can't compare the strings directly because the object fields be // printed in a different order. - assert_eq!(a.clone(), from_str(a.to_str().as_slice()).unwrap()); + assert_eq!(a.clone(), from_str(a.to_string().as_slice()).unwrap()); assert_eq!(a.clone(), from_str(a.to_pretty_str().as_slice()).unwrap()); } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index fae1b933210..796147ce7a0 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -345,10 +345,10 @@ impl<'a> AsciiStr for &'a [Ascii] { impl IntoStr for Vec<Ascii> { #[inline] - fn into_str(self) -> String { + fn into_string(self) -> String { unsafe { let s: &str = mem::transmute(self.as_slice()); - s.to_string() + String::from_str(s) } } } @@ -438,12 +438,12 @@ unsafe fn str_map_bytes(string: String, map: &'static [u8]) -> String { *b = map[*b as uint]; } - str::from_utf8(bytes.as_slice()).unwrap().to_string() + String::from_str(str::from_utf8(bytes.as_slice()).unwrap()) } #[inline] unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> String { - let mut s = string.to_string(); + let mut s = String::from_str(string); for b in s.as_mut_bytes().mut_iter() { *b = map[*b as uint]; } @@ -578,12 +578,12 @@ mod tests { assert_eq!(v.as_slice().to_ascii(), v2ascii!([40, 32, 59])); assert_eq!("( ;".to_string().as_slice().to_ascii(), v2ascii!([40, 32, 59])); - assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_string()); - assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_string()); + assert_eq!("abCDef&?#".to_ascii().to_lower().into_string(), "abcdef&?#".to_string()); + assert_eq!("abCDef&?#".to_ascii().to_upper().into_string(), "ABCDEF&?#".to_string()); - assert_eq!("".to_ascii().to_lower().into_str(), "".to_string()); - assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_string()); - assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_string()); + assert_eq!("".to_ascii().to_lower().into_string(), "".to_string()); + assert_eq!("YMCA".to_ascii().to_lower().into_string(), "ymca".to_string()); + assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_string(), "ABCDEFXYZ:.;".to_string()); assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii())); @@ -595,11 +595,11 @@ mod tests { #[test] fn test_ascii_vec_ng() { - assert_eq!("abCDef&?#".to_ascii().to_lower().into_str(), "abcdef&?#".to_string()); - assert_eq!("abCDef&?#".to_ascii().to_upper().into_str(), "ABCDEF&?#".to_string()); - assert_eq!("".to_ascii().to_lower().into_str(), "".to_string()); - assert_eq!("YMCA".to_ascii().to_lower().into_str(), "ymca".to_string()); - assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_str(), "ABCDEFXYZ:.;".to_string()); + assert_eq!("abCDef&?#".to_ascii().to_lower().into_string(), "abcdef&?#".to_string()); + assert_eq!("abCDef&?#".to_ascii().to_upper().into_string(), "ABCDEF&?#".to_string()); + assert_eq!("".to_ascii().to_lower().into_string(), "".to_string()); + assert_eq!("YMCA".to_ascii().to_lower().into_string(), "ymca".to_string()); + assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().into_string(), "ABCDEFXYZ:.;".to_string()); } #[test] @@ -615,9 +615,9 @@ mod tests { } #[test] - fn test_ascii_into_str() { - assert_eq!(vec2ascii![40, 32, 59].into_str(), "( ;".to_string()); - assert_eq!(vec2ascii!(40, 32, 59).into_str(), "( ;".to_string()); + fn test_ascii_into_string() { + assert_eq!(vec2ascii![40, 32, 59].into_string(), "( ;".to_string()); + assert_eq!(vec2ascii!(40, 32, 59).into_string(), "( ;".to_string()); } #[test] @@ -757,8 +757,8 @@ mod tests { } #[test] - fn test_to_str() { - let s = Ascii{ chr: 't' as u8 }.to_str(); + fn test_to_string() { + let s = Ascii{ chr: 't' as u8 }.to_string(); assert_eq!(s, "t".to_string()); } diff --git a/src/libstd/collections/lru_cache.rs b/src/libstd/collections/lru_cache.rs index 08f11581e83..a02402271d0 100644 --- a/src/libstd/collections/lru_cache.rs +++ b/src/libstd/collections/lru_cache.rs @@ -319,20 +319,20 @@ mod tests { } #[test] - fn test_to_str() { + fn test_to_string() { let mut cache: LruCache<int, int> = LruCache::new(3); cache.put(1, 10); cache.put(2, 20); cache.put(3, 30); - assert_eq!(cache.to_str(), "{3: 30, 2: 20, 1: 10}".to_string()); + assert_eq!(cache.to_string(), "{3: 30, 2: 20, 1: 10}".to_string()); cache.put(2, 22); - assert_eq!(cache.to_str(), "{2: 22, 3: 30, 1: 10}".to_string()); + assert_eq!(cache.to_string(), "{2: 22, 3: 30, 1: 10}".to_string()); cache.put(6, 60); - assert_eq!(cache.to_str(), "{6: 60, 2: 22, 3: 30}".to_string()); + assert_eq!(cache.to_string(), "{6: 60, 2: 22, 3: 30}".to_string()); cache.get(&3); - assert_eq!(cache.to_str(), "{3: 30, 6: 60, 2: 22}".to_string()); + assert_eq!(cache.to_string(), "{3: 30, 6: 60, 2: 22}".to_string()); cache.change_capacity(2); - assert_eq!(cache.to_str(), "{3: 30, 6: 60}".to_string()); + assert_eq!(cache.to_string(), "{3: 30, 6: 60}".to_string()); } #[test] @@ -343,6 +343,6 @@ mod tests { cache.clear(); assert!(cache.get(&1).is_none()); assert!(cache.get(&2).is_none()); - assert_eq!(cache.to_str(), "{}".to_string()); + assert_eq!(cache.to_string(), "{}".to_string()); } } diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index 728875ce260..86283f03381 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -209,13 +209,11 @@ mod test { #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] pub mod dl { - use prelude::*; use c_str::{CString, ToCStr}; use libc; use ptr; use result::*; - use str::StrAllocating; use string::String; pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 { @@ -243,9 +241,8 @@ pub mod dl { let ret = if ptr::null() == last_error { Ok(result) } else { - Err(CString::new(last_error, false).as_str() - .unwrap() - .to_string()) + Err(String::from_str(CString::new(last_error, false).as_str() + .unwrap())) }; ret diff --git a/src/libstd/from_str.rs b/src/libstd/from_str.rs index 1ca72bca20b..21b1e0560a5 100644 --- a/src/libstd/from_str.rs +++ b/src/libstd/from_str.rs @@ -14,7 +14,6 @@ use option::{Option, Some, None}; use string::String; -use str::StrAllocating; /// A trait to abstract the idea of creating a new instance of a type from a /// string. @@ -55,7 +54,7 @@ impl FromStr for bool { impl FromStr for String { #[inline] fn from_str(s: &str) -> Option<String> { - Some(s.to_string()) + Some(String::from_str(s)) } } diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index e7f26c7bd91..ed183cbf3bc 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -915,7 +915,7 @@ mod test { macro_rules! error( ($e:expr, $s:expr) => ( match $e { Ok(val) => fail!("Should have been an error, was {:?}", val), - Err(ref err) => assert!(err.to_str().as_slice().contains($s.as_slice()), + Err(ref err) => assert!(err.to_string().as_slice().contains($s.as_slice()), format!("`{}` did not contain `{}`", err, $s)) } ) ) @@ -1167,7 +1167,7 @@ mod test { for n in range(0i,3) { let f = dir.join(format!("{}.txt", n)); let mut w = check!(File::create(&f)); - let msg_str = format!("{}{}", prefix, n.to_str()); + let msg_str = format!("{}{}", prefix, n.to_string()); let msg = msg_str.as_slice().as_bytes(); check!(w.write(msg)); } diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 3443a85b468..7d293f363f0 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -532,7 +532,7 @@ mod test { writer.write_line("testing").unwrap(); writer.write_str("testing").unwrap(); let mut r = BufReader::new(writer.get_ref()); - assert_eq!(r.read_to_str().unwrap(), "testingtesting\ntesting".to_string()); + assert_eq!(r.read_to_string().unwrap(), "testingtesting\ntesting".to_string()); } #[test] @@ -542,14 +542,14 @@ mod test { writer.write_char('\n').unwrap(); writer.write_char('ệ').unwrap(); let mut r = BufReader::new(writer.get_ref()); - assert_eq!(r.read_to_str().unwrap(), "a\nệ".to_string()); + assert_eq!(r.read_to_string().unwrap(), "a\nệ".to_string()); } #[test] fn test_read_whole_string_bad() { let buf = [0xff]; let mut r = BufReader::new(buf); - match r.read_to_str() { + match r.read_to_string() { Ok(..) => fail!(), Err(..) => {} } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 1d339b03af6..fe9016453f7 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -233,7 +233,7 @@ use owned::Box; use result::{Ok, Err, Result}; use rt::rtio; use slice::{Vector, MutableVector, ImmutableVector}; -use str::{Str, StrSlice, StrAllocating}; +use str::{Str, StrSlice}; use str; use string::String; use uint; @@ -566,7 +566,7 @@ pub trait Reader { fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> { if min > buf.len() { return Err(IoError { - detail: Some("the buffer is too short".to_string()), + detail: Some(String::from_str("the buffer is too short")), ..standard_error(InvalidInput) }); } @@ -634,7 +634,7 @@ pub trait Reader { fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> { if min > len { return Err(IoError { - detail: Some("the buffer is too short".to_string()), + detail: Some(String::from_str("the buffer is too short")), ..standard_error(InvalidInput) }); } @@ -702,10 +702,10 @@ pub trait Reader { /// This function returns all of the same errors as `read_to_end` with an /// additional error if the reader's contents are not a valid sequence of /// UTF-8 bytes. - fn read_to_str(&mut self) -> IoResult<String> { + fn read_to_string(&mut self) -> IoResult<String> { self.read_to_end().and_then(|s| { match str::from_utf8(s.as_slice()) { - Some(s) => Ok(s.to_string()), + Some(s) => Ok(String::from_str(s)), None => Err(standard_error(InvalidInput)), } }) @@ -1440,7 +1440,7 @@ pub trait Buffer: Reader { fn read_line(&mut self) -> IoResult<String> { self.read_until('\n' as u8).and_then(|line| match str::from_utf8(line.as_slice()) { - Some(s) => Ok(s.to_string()), + Some(s) => Ok(String::from_str(s)), None => Err(standard_error(InvalidInput)), } ) diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index ca59849202b..79caded6711 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -443,10 +443,11 @@ mod test { } #[test] - fn ipv6_addr_to_str() { + fn ipv6_addr_to_string() { let a1 = Ipv6Addr(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280); - assert!(a1.to_str() == "::ffff:192.0.2.128".to_string() || - a1.to_str() == "::FFFF:192.0.2.128".to_string()); - assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_str(), "8:9:a:b:c:d:e:f".to_string()); + assert!(a1.to_string() == "::ffff:192.0.2.128".to_string() || + a1.to_string() == "::FFFF:192.0.2.128".to_string()); + assert_eq!(Ipv6Addr(8, 9, 10, 11, 12, 13, 14, 15).to_string(), + "8:9:a:b:c:d:e:f".to_string()); } } diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index baf53251fbe..49322098348 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -467,7 +467,7 @@ mod test { iotest!(fn listen_ip4_localhost() { let socket_addr = next_test_ip4(); - let ip_str = socket_addr.ip.to_str(); + let ip_str = socket_addr.ip.to_string(); let port = socket_addr.port; let listener = TcpListener::bind(ip_str.as_slice(), port); let mut acceptor = listener.listen(); @@ -485,7 +485,7 @@ mod test { iotest!(fn connect_localhost() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -502,7 +502,7 @@ mod test { iotest!(fn connect_ip4_loopback() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -519,7 +519,7 @@ mod test { iotest!(fn connect_ip6_loopback() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -536,7 +536,7 @@ mod test { iotest!(fn smoke_test_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -553,7 +553,7 @@ mod test { iotest!(fn smoke_test_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -570,7 +570,7 @@ mod test { iotest!(fn read_eof_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -587,7 +587,7 @@ mod test { iotest!(fn read_eof_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -604,7 +604,7 @@ mod test { iotest!(fn read_eof_twice_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -629,7 +629,7 @@ mod test { iotest!(fn read_eof_twice_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -654,7 +654,7 @@ mod test { iotest!(fn write_close_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -681,7 +681,7 @@ mod test { iotest!(fn write_close_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -708,7 +708,7 @@ mod test { iotest!(fn multiple_connect_serial_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let max = 10u; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -729,7 +729,7 @@ mod test { iotest!(fn multiple_connect_serial_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let max = 10u; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -750,7 +750,7 @@ mod test { iotest!(fn multiple_connect_interleaved_greedy_schedule_ip4() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; static MAX: int = 10; let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -772,7 +772,7 @@ mod test { connect(0, addr); fn connect(i: int, addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; if i == MAX { return } @@ -789,7 +789,7 @@ mod test { iotest!(fn multiple_connect_interleaved_greedy_schedule_ip6() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; static MAX: int = 10; let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -811,7 +811,7 @@ mod test { connect(0, addr); fn connect(i: int, addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; if i == MAX { return } @@ -829,7 +829,7 @@ mod test { iotest!(fn multiple_connect_interleaved_lazy_schedule_ip4() { static MAX: int = 10; let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -850,7 +850,7 @@ mod test { connect(0, addr); fn connect(i: int, addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; if i == MAX { return } @@ -868,7 +868,7 @@ mod test { iotest!(fn multiple_connect_interleaved_lazy_schedule_ip6() { static MAX: int = 10; let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -889,7 +889,7 @@ mod test { connect(0, addr); fn connect(i: int, addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; if i == MAX { return } @@ -905,7 +905,7 @@ mod test { }) pub fn socket_name(addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut listener = TcpListener::bind(ip_str.as_slice(), port).unwrap(); @@ -917,7 +917,7 @@ mod test { } pub fn peer_name(addr: SocketAddr) { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); spawn(proc() { @@ -954,7 +954,7 @@ mod test { let port = addr.port; let (tx, rx) = channel(); spawn(proc() { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let mut srv = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); tx.send(()); let mut cl = srv.accept().unwrap(); @@ -965,7 +965,7 @@ mod test { }); rx.recv(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let mut c = TcpStream::connect(ip_str.as_slice(), port).unwrap(); let mut b = [0, ..10]; assert_eq!(c.read(b), Ok(1)); @@ -975,7 +975,7 @@ mod test { iotest!(fn double_bind() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let listener = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen(); assert!(listener.is_ok()); @@ -994,7 +994,7 @@ mod test { let (tx, rx) = channel(); spawn(proc() { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); rx.recv(); let _stream = TcpStream::connect(ip_str.as_slice(), port).unwrap(); // Close @@ -1002,7 +1002,7 @@ mod test { }); { - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); tx.send(()); { @@ -1012,12 +1012,12 @@ mod test { } // Close listener } - let _listener = TcpListener::bind(addr.ip.to_str().as_slice(), port); + let _listener = TcpListener::bind(addr.ip.to_string().as_slice(), port); }) iotest!(fn tcp_clone_smoke() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -1048,7 +1048,7 @@ mod test { iotest!(fn tcp_clone_two_read() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); let (tx1, rx) = channel(); @@ -1082,7 +1082,7 @@ mod test { iotest!(fn tcp_clone_two_write() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen(); @@ -1111,7 +1111,7 @@ mod test { use rt::rtio::RtioTcpStream; let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let a = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen(); spawn(proc() { @@ -1129,7 +1129,7 @@ mod test { iotest!(fn accept_timeout() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut a = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen().unwrap(); @@ -1150,7 +1150,7 @@ mod test { if !cfg!(target_os = "freebsd") { let (tx, rx) = channel(); spawn(proc() { - tx.send(TcpStream::connect(addr.ip.to_str().as_slice(), + tx.send(TcpStream::connect(addr.ip.to_string().as_slice(), port).unwrap()); }); let _l = rx.recv(); @@ -1168,7 +1168,7 @@ mod test { // Unset the timeout and make sure that this always blocks. a.set_timeout(None); spawn(proc() { - drop(TcpStream::connect(addr.ip.to_str().as_slice(), + drop(TcpStream::connect(addr.ip.to_string().as_slice(), port).unwrap()); }); a.accept().unwrap(); @@ -1176,7 +1176,7 @@ mod test { iotest!(fn close_readwrite_smoke() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (_tx, rx) = channel::<()>(); @@ -1214,7 +1214,7 @@ mod test { iotest!(fn close_read_wakes_up() { let addr = next_test_ip4(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (_tx, rx) = channel::<()>(); @@ -1241,7 +1241,7 @@ mod test { iotest!(fn readwrite_timeouts() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); @@ -1275,7 +1275,7 @@ mod test { iotest!(fn read_timeouts() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); @@ -1305,7 +1305,7 @@ mod test { iotest!(fn write_timeouts() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); @@ -1334,7 +1334,7 @@ mod test { iotest!(fn timeout_concurrent_read() { let addr = next_test_ip6(); - let ip_str = addr.ip.to_str(); + let ip_str = addr.ip.to_string(); let port = addr.port; let mut a = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap(); let (tx, rx) = channel::<()>(); @@ -1363,7 +1363,7 @@ mod test { iotest!(fn clone_while_reading() { let addr = next_test_ip6(); - let listen = TcpListener::bind(addr.ip.to_str().as_slice(), addr.port); + let listen = TcpListener::bind(addr.ip.to_string().as_slice(), addr.port); let mut accept = listen.listen().unwrap(); // Enqueue a task to write to a socket @@ -1371,7 +1371,7 @@ mod test { let (txdone, rxdone) = channel(); let txdone2 = txdone.clone(); spawn(proc() { - let mut tcp = TcpStream::connect(addr.ip.to_str().as_slice(), + let mut tcp = TcpStream::connect(addr.ip.to_string().as_slice(), addr.port).unwrap(); rx.recv(); tcp.write_u8(0).unwrap(); diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 8e1747146e4..8f1046b62fd 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -615,7 +615,7 @@ mod tests { }) pub fn read_all(input: &mut Reader) -> String { - input.read_to_str().unwrap() + input.read_to_string().unwrap() } pub fn run_output(cmd: Command) -> String { diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index e5a64f785ce..cdd083202e0 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -391,7 +391,7 @@ mod tests { set_stdout(box w); println!("hello!"); }); - assert_eq!(r.read_to_str().unwrap(), "hello!\n".to_string()); + assert_eq!(r.read_to_string().unwrap(), "hello!\n".to_string()); }) iotest!(fn capture_stderr() { @@ -404,7 +404,7 @@ mod tests { ::realstd::io::stdio::set_stderr(box w); fail!("my special message"); }); - let s = r.read_to_str().unwrap(); + let s = r.read_to_string().unwrap(); assert!(s.as_slice().contains("my special message")); }) } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 83a01feee90..2acf12b76c0 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -379,21 +379,21 @@ mod test { let mut r = BufReader::new(data.as_bytes()); { let mut r = LimitReader::new(r.by_ref(), 3); - assert_eq!(r.read_line(), Ok("012".to_str())); + assert_eq!(r.read_line(), Ok("012".to_string())); assert_eq!(r.limit(), 0); assert_eq!(r.read_line().err().unwrap().kind, io::EndOfFile); } { let mut r = LimitReader::new(r.by_ref(), 9); - assert_eq!(r.read_line(), Ok("3456789\n".to_str())); + assert_eq!(r.read_line(), Ok("3456789\n".to_string())); assert_eq!(r.limit(), 1); - assert_eq!(r.read_line(), Ok("0".to_str())); + assert_eq!(r.read_line(), Ok("0".to_string())); } { let mut r = LimitReader::new(r.by_ref(), 100); assert_eq!(r.read_char(), Ok('1')); assert_eq!(r.limit(), 99); - assert_eq!(r.read_line(), Ok("23456789\n".to_str())); + assert_eq!(r.read_line(), Ok("23456789\n".to_string())); } } diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index 2b2ffb9f4e2..680620f5a75 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -245,7 +245,7 @@ impl FloatMath for f32 { /// /// * num - The float value #[inline] -pub fn to_str(num: f32) -> String { +pub fn to_string(num: f32) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index e156d2ce553..3180ee28c6f 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -253,7 +253,7 @@ impl FloatMath for f64 { /// /// * num - The float value #[inline] -pub fn to_str(num: f64) -> String { +pub fn to_string(num: f64) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); r diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index a4200b55a59..3c01edf2339 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -55,7 +55,7 @@ impl FromStrRadix for $T { /// Convert to a string as a byte slice in a given base. /// -/// Use in place of x.to_str() when you do not need to store the string permanently +/// Use in place of x.to_string() when you do not need to store the string permanently /// /// # Examples /// @@ -143,7 +143,7 @@ mod tests { } #[test] - fn test_to_str() { + fn test_to_string() { assert_eq!((0 as $T).to_str_radix(10u), "0".to_string()); assert_eq!((1 as $T).to_str_radix(10u), "1".to_string()); assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_string()); @@ -155,28 +155,28 @@ mod tests { #[test] fn test_int_to_str_overflow() { let mut i8_val: i8 = 127_i8; - assert_eq!(i8_val.to_str(), "127".to_string()); + assert_eq!(i8_val.to_string(), "127".to_string()); i8_val += 1 as i8; - assert_eq!(i8_val.to_str(), "-128".to_string()); + assert_eq!(i8_val.to_string(), "-128".to_string()); let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16_val.to_str(), "32767".to_string()); + assert_eq!(i16_val.to_string(), "32767".to_string()); i16_val += 1 as i16; - assert_eq!(i16_val.to_str(), "-32768".to_string()); + assert_eq!(i16_val.to_string(), "-32768".to_string()); let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32_val.to_str(), "2147483647".to_string()); + assert_eq!(i32_val.to_string(), "2147483647".to_string()); i32_val += 1 as i32; - assert_eq!(i32_val.to_str(), "-2147483648".to_string()); + assert_eq!(i32_val.to_string(), "-2147483648".to_string()); let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64_val.to_str(), "9223372036854775807".to_string()); + assert_eq!(i64_val.to_string(), "9223372036854775807".to_string()); i64_val += 1 as i64; - assert_eq!(i64_val.to_str(), "-9223372036854775808".to_string()); + assert_eq!(i64_val.to_string(), "-9223372036854775808".to_string()); } #[test] diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 5028987f44f..88fc6e1ffd8 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -146,7 +146,7 @@ static NAN_BUF: [u8, ..3] = ['N' as u8, 'a' as u8, 'N' as u8]; /** * Converts an integral number to its string representation as a byte vector. * This is meant to be a common base implementation for all integral string - * conversion functions like `to_str()` or `to_str_radix()`. + * conversion functions like `to_string()` or `to_str_radix()`. * * # Arguments * - `num` - The number to convert. Accepts any number that @@ -226,7 +226,7 @@ pub fn int_to_str_bytes_common<T: Int>(num: T, radix: uint, sign: SignFormat, f: /** * Converts a number to its string representation as a byte vector. * This is meant to be a common base implementation for all numeric string - * conversion functions like `to_str()` or `to_str_radix()`. + * conversion functions like `to_string()` or `to_str_radix()`. * * # Arguments * - `num` - The number to convert. Accepts any number that @@ -894,9 +894,9 @@ mod bench { use f64; #[bench] - fn float_to_str(b: &mut Bencher) { + fn float_to_string(b: &mut Bencher) { let mut rng = weak_rng(); - b.iter(|| { f64::to_str(rng.gen()); }) + b.iter(|| { f64::to_string(rng.gen()); }) } } } diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index 7f2efe034a2..cfcaf0fa8da 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -56,7 +56,7 @@ impl FromStrRadix for $T { /// Convert to a string as a byte slice in a given base. /// -/// Use in place of x.to_str() when you do not need to store the string permanently +/// Use in place of x.to_string() when you do not need to store the string permanently /// /// # Examples /// @@ -101,7 +101,7 @@ mod tests { use u16; #[test] - pub fn test_to_str() { + pub fn test_to_string() { assert_eq!((0 as $T).to_str_radix(10u), "0".to_string()); assert_eq!((1 as $T).to_str_radix(10u), "1".to_string()); assert_eq!((2 as $T).to_str_radix(10u), "2".to_string()); @@ -141,28 +141,28 @@ mod tests { #[test] fn test_uint_to_str_overflow() { let mut u8_val: u8 = 255_u8; - assert_eq!(u8_val.to_str(), "255".to_string()); + assert_eq!(u8_val.to_string(), "255".to_string()); u8_val += 1 as u8; - assert_eq!(u8_val.to_str(), "0".to_string()); + assert_eq!(u8_val.to_string(), "0".to_string()); let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16_val.to_str(), "65535".to_string()); + assert_eq!(u16_val.to_string(), "65535".to_string()); u16_val += 1 as u16; - assert_eq!(u16_val.to_str(), "0".to_string()); + assert_eq!(u16_val.to_string(), "0".to_string()); let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32_val.to_str(), "4294967295".to_string()); + assert_eq!(u32_val.to_string(), "4294967295".to_string()); u32_val += 1 as u32; - assert_eq!(u32_val.to_str(), "0".to_string()); + assert_eq!(u32_val.to_string(), "0".to_string()); let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64_val.to_str(), "18446744073709551615".to_string()); + assert_eq!(u64_val.to_string(), "18446744073709551615".to_string()); u64_val += 1 as u64; - assert_eq!(u64_val.to_str(), "0".to_string()); + assert_eq!(u64_val.to_string(), "0".to_string()); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index b3f25914c8f..db56b387f8d 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -223,8 +223,8 @@ fn with_env_lock<T>(f: || -> T) -> T { /// ``` pub fn env() -> Vec<(String,String)> { env_as_bytes().move_iter().map(|(k,v)| { - let k = str::from_utf8_lossy(k.as_slice()).to_string(); - let v = str::from_utf8_lossy(v.as_slice()).to_string(); + let k = String::from_str(str::from_utf8_lossy(k.as_slice()).as_slice()); + let v = String::from_str(str::from_utf8_lossy(v.as_slice()).as_slice()); (k,v) }).collect() } @@ -334,7 +334,7 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> { /// } /// ``` pub fn getenv(n: &str) -> Option<String> { - getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_string()) + getenv_as_bytes(n).map(|v| String::from_str(str::from_utf8_lossy(v.as_slice()).as_slice())) } #[cfg(unix)] diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index d98cfb7d8ee..5c6e140bd29 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -545,7 +545,7 @@ mod tests { ($path:expr, $disp:ident, $exp:expr) => ( { let path = Path::new($path); - assert!(path.$disp().to_str().as_slice() == $exp); + assert!(path.$disp().to_string().as_slice() == $exp); } ) ) diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 113b0410875..206f75739e8 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -1314,9 +1314,9 @@ mod tests { #[test] fn test_display_str() { let path = Path::new("foo"); - assert_eq!(path.display().to_str(), "foo".to_string()); + assert_eq!(path.display().to_string(), "foo".to_string()); let path = Path::new(b"\\"); - assert_eq!(path.filename_display().to_str(), "".to_string()); + assert_eq!(path.filename_display().to_string(), "".to_string()); let path = Path::new("foo"); let mo = path.display().as_maybe_owned(); diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index 28cd7223b0a..6d60fc19d5d 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -78,7 +78,7 @@ #[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek}; #[doc(no_inline)] pub use str::{Str, StrVector, StrSlice, OwnedStr}; #[doc(no_inline)] pub use str::{IntoMaybeOwned, StrAllocating}; -#[doc(no_inline)] pub use to_str::{ToStr, IntoStr}; +#[doc(no_inline)] pub use to_str::{ToString, IntoStr}; #[doc(no_inline)] pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4}; #[doc(no_inline)] pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8}; #[doc(no_inline)] pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12}; diff --git a/src/libstd/task.rs b/src/libstd/task.rs index c20cbea0ae7..72cc596085e 100644 --- a/src/libstd/task.rs +++ b/src/libstd/task.rs @@ -638,7 +638,7 @@ mod test { }); assert!(r.is_ok()); - let output = reader.read_to_str().unwrap(); + let output = reader.read_to_string().unwrap(); assert_eq!(output, "Hello, world!".to_string()); } diff --git a/src/libstd/to_str.rs b/src/libstd/to_str.rs index e51e2c4d9ce..c19fd81b570 100644 --- a/src/libstd/to_str.rs +++ b/src/libstd/to_str.rs @@ -10,7 +10,7 @@ /*! -The `ToStr` trait for converting to strings +The `ToString` trait for converting to strings */ @@ -20,19 +20,19 @@ use fmt; use string::String; /// A generic trait for converting a value to a string -pub trait ToStr { +pub trait ToString { /// Converts the value of `self` to an owned string - fn to_str(&self) -> String; + fn to_string(&self) -> String; } /// Trait for converting a type to a string, consuming it in the process. pub trait IntoStr { /// Consume and convert to a string. - fn into_str(self) -> String; + fn into_string(self) -> String; } -impl<T: fmt::Show> ToStr for T { - fn to_str(&self) -> String { +impl<T: fmt::Show> ToString for T { + fn to_string(&self) -> String { format!("{}", *self) } } @@ -44,23 +44,23 @@ mod tests { #[test] fn test_simple_types() { - assert_eq!(1i.to_str(), "1".to_string()); - assert_eq!((-1i).to_str(), "-1".to_string()); - assert_eq!(200u.to_str(), "200".to_string()); - assert_eq!(2u8.to_str(), "2".to_string()); - assert_eq!(true.to_str(), "true".to_string()); - assert_eq!(false.to_str(), "false".to_string()); - assert_eq!(().to_str(), "()".to_string()); - assert_eq!(("hi".to_string()).to_str(), "hi".to_string()); + assert_eq!(1i.to_string(), "1".to_string()); + assert_eq!((-1i).to_string(), "-1".to_string()); + assert_eq!(200u.to_string(), "200".to_string()); + assert_eq!(2u8.to_string(), "2".to_string()); + assert_eq!(true.to_string(), "true".to_string()); + assert_eq!(false.to_string(), "false".to_string()); + assert_eq!(().to_string(), "()".to_string()); + assert_eq!(("hi".to_string()).to_string(), "hi".to_string()); } #[test] fn test_vectors() { let x: Vec<int> = vec![]; - assert_eq!(x.to_str(), "[]".to_string()); - assert_eq!((vec![1i]).to_str(), "[1]".to_string()); - assert_eq!((vec![1i, 2, 3]).to_str(), "[1, 2, 3]".to_string()); - assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_str() == + assert_eq!(x.to_string(), "[]".to_string()); + assert_eq!((vec![1i]).to_string(), "[1]".to_string()); + assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]".to_string()); + assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() == "[[], [1], [1, 1]]".to_string()); } } diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 9771bc9386b..5aaf7ed3dba 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -60,9 +60,12 @@ pub struct AbiData { } pub enum AbiArchitecture { - RustArch, // Not a real ABI (e.g., intrinsic) - AllArch, // An ABI that specifies cross-platform defaults (e.g., "C") - Archs(u32) // Multiple architectures (bitset) + /// Not a real ABI (e.g., intrinsic) + RustArch, + /// An ABI that specifies cross-platform defaults (e.g., "C") + AllArch, + /// Multiple architectures (bitset) + Archs(u32) } static AbiDatas: &'static [AbiData] = &[ @@ -84,21 +87,13 @@ static AbiDatas: &'static [AbiData] = &[ AbiData {abi: RustIntrinsic, name: "rust-intrinsic", abi_arch: RustArch}, ]; +/// Iterates through each of the defined ABIs. fn each_abi(op: |abi: Abi| -> bool) -> bool { - /*! - * - * Iterates through each of the defined ABIs. - */ - AbiDatas.iter().advance(|abi_data| op(abi_data.abi)) } +/// Returns the ABI with the given name (if any). pub fn lookup(name: &str) -> Option<Abi> { - /*! - * - * Returns the ABI with the given name (if any). - */ - let mut res = None; each_abi(|abi| { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index ce1302c8db8..ebfc45d22ce 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -14,7 +14,7 @@ use codemap::{Span, Spanned, DUMMY_SP}; use abi::Abi; use ast_util; use owned_slice::OwnedSlice; -use parse::token::{InternedString, special_idents, str_to_ident}; +use parse::token::{InternedString, str_to_ident}; use parse::token; use std::fmt; @@ -24,7 +24,8 @@ use std::rc::Rc; use std::gc::{Gc, GC}; use serialize::{Encodable, Decodable, Encoder, Decoder}; -/// A pointer abstraction. FIXME(eddyb) #10676 use Rc<T> in the future. +/// A pointer abstraction. +// FIXME(eddyb) #10676 use Rc<T> in the future. pub type P<T> = Gc<T>; #[allow(non_snake_case_functions)] @@ -36,11 +37,11 @@ pub fn P<T: 'static>(value: T) -> P<T> { // FIXME #6993: in librustc, uses of "ident" should be replaced // by just "Name". -// an identifier contains a Name (index into the interner -// table) and a SyntaxContext to track renaming and -// macro expansion per Flatt et al., "Macros -// That Work Together" -#[deriving(Clone, Hash, PartialOrd, Eq, Ord, Show)] +/// An identifier contains a Name (index into the interner +/// table) and a SyntaxContext to track renaming and +/// macro expansion per Flatt et al., "Macros +/// That Work Together" +#[deriving(Clone, Hash, PartialOrd, Eq, Ord)] pub struct Ident { pub name: Name, pub ctxt: SyntaxContext @@ -49,6 +50,16 @@ pub struct Ident { impl Ident { /// Construct an identifier with the given name and an empty context: pub fn new(name: Name) -> Ident { Ident {name: name, ctxt: EMPTY_CTXT}} + + pub fn as_str<'a>(&'a self) -> &'a str { + self.name.as_str() + } +} + +impl Show for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "\"{}\"#{}", token::get_ident(*self).get(), self.ctxt) + } } impl PartialEq for Ident { @@ -95,7 +106,26 @@ pub static ILLEGAL_CTXT : SyntaxContext = 1; /// A name is a part of an identifier, representing a string or gensym. It's /// the result of interning. -pub type Name = u32; +#[deriving(Eq, Ord, PartialEq, PartialOrd, Hash, Encodable, Decodable, Clone, Show)] +pub struct Name(pub u32); + +impl Name { + pub fn as_str<'a>(&'a self) -> &'a str { + unsafe { + // FIXME #12938: can't use copy_lifetime since &str isn't a &T + ::std::mem::transmute(token::get_name(*self).get()) + } + } + + pub fn uint(&self) -> uint { + let Name(nm) = *self; + nm as uint + } + + pub fn ident(&self) -> Ident { + Ident { name: *self, ctxt: 0 } + } +} /// A mark represents a unique id associated with a macro expansion pub type Mrk = u32; @@ -122,10 +152,9 @@ pub struct Lifetime { pub name: Name } -// a "Path" is essentially Rust's notion of a name; -// for instance: std::cmp::PartialEq . It's represented -// as a sequence of identifiers, along with a bunch -// of supporting information. +/// A "Path" is essentially Rust's notion of a name; for instance: +/// std::cmp::PartialEq . It's represented as a sequence of identifiers, +/// along with a bunch of supporting information. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct Path { pub span: Span, @@ -163,15 +192,15 @@ pub struct DefId { pub static LOCAL_CRATE: CrateNum = 0; pub static CRATE_NODE_ID: NodeId = 0; -// When parsing and doing expansions, we initially give all AST nodes this AST -// node value. Then later, in the renumber pass, we renumber them to have -// small, positive ids. +/// When parsing and doing expansions, we initially give all AST nodes this AST +/// node value. Then later, in the renumber pass, we renumber them to have +/// small, positive ids. pub static DUMMY_NODE_ID: NodeId = -1; -// The AST represents all type param bounds as types. -// typeck::collect::compute_bounds matches these against -// the "special" built-in traits (see middle::lang_items) and -// detects Copy, Send and Share. +/// The AST represents all type param bounds as types. +/// typeck::collect::compute_bounds matches these against +/// the "special" built-in traits (see middle::lang_items) and +/// detects Copy, Send and Share. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum TyParamBound { TraitTyParamBound(TraitRef), @@ -184,8 +213,8 @@ pub enum TyParamBound { pub struct TyParam { pub ident: Ident, pub id: NodeId, - pub sized: Sized, pub bounds: OwnedSlice<TyParamBound>, + pub unbound: Option<TyParamBound>, pub default: Option<P<Ty>>, pub span: Span } @@ -210,9 +239,9 @@ impl Generics { } } -// The set of MetaItems that define the compilation environment of the crate, -// used to drive conditional compilation -pub type CrateConfig = Vec<Gc<MetaItem>>; +/// The set of MetaItems that define the compilation environment of the crate, +/// used to drive conditional compilation +pub type CrateConfig = Vec<Gc<MetaItem>> ; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct Crate { @@ -289,13 +318,13 @@ pub enum BindingMode { pub enum Pat_ { PatWild, PatWildMulti, - // A PatIdent may either be a new bound variable, - // or a nullary enum (in which case the third field - // is None). - // In the nullary enum case, the parser can't determine - // which it is. The resolver determines this, and - // records this pattern's NodeId in an auxiliary - // set (of "PatIdents that refer to nullary enums") + /// A PatIdent may either be a new bound variable, + /// or a nullary enum (in which case the third field + /// is None). + /// In the nullary enum case, the parser can't determine + /// which it is. The resolver determines this, and + /// records this pattern's NodeId in an auxiliary + /// set (of "PatIdents that refer to nullary enums") PatIdent(BindingMode, SpannedIdent, Option<Gc<Pat>>), PatEnum(Path, Option<Vec<Gc<Pat>>>), /* "none" means a * pattern where * we don't bind the fields to names */ @@ -305,8 +334,8 @@ pub enum Pat_ { PatRegion(Gc<Pat>), // reference pattern PatLit(Gc<Expr>), PatRange(Gc<Expr>, Gc<Expr>), - // [a, b, ..i, y, z] is represented as - // PatVec(~[a, b], Some(i), ~[y, z]) + /// [a, b, ..i, y, z] is represented as: + /// PatVec(~[a, b], Some(i), ~[y, z]) PatVec(Vec<Gc<Pat>>, Option<Gc<Pat>>, Vec<Gc<Pat>>), PatMac(Mac), } @@ -319,9 +348,12 @@ pub enum Mutability { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum ExprVstore { - ExprVstoreUniq, // ~[1,2,3,4] - ExprVstoreSlice, // &[1,2,3,4] - ExprVstoreMutSlice, // &mut [1,2,3,4] + /// ~[1, 2, 3, 4] + ExprVstoreUniq, + /// &[1, 2, 3, 4] + ExprVstoreSlice, + /// &mut [1, 2, 3, 4] + ExprVstoreMutSlice, } #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] @@ -359,16 +391,16 @@ pub type Stmt = Spanned<Stmt_>; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum Stmt_ { - // could be an item or a local (let) binding: + /// Could be an item or a local (let) binding: StmtDecl(Gc<Decl>, NodeId), - // expr without trailing semi-colon (must have unit type): + /// Expr without trailing semi-colon (must have unit type): StmtExpr(Gc<Expr>, NodeId), - // expr with trailing semi-colon (may have any type): + /// Expr with trailing semi-colon (may have any type): StmtSemi(Gc<Expr>, NodeId), - // bool: is there a trailing sem-colon? + /// bool: is there a trailing sem-colon? StmtMac(Mac, bool), } @@ -397,9 +429,9 @@ pub type Decl = Spanned<Decl_>; #[deriving(PartialEq, Eq, Encodable, Decodable, Hash)] pub enum Decl_ { - // a local (let) binding: + /// A local (let) binding: DeclLocal(Gc<Local>), - // an item binding: + /// An item binding: DeclItem(Gc<Item>), } @@ -443,7 +475,7 @@ pub struct Expr { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum Expr_ { ExprVstore(Gc<Expr>, ExprVstore), - // First expr is the place; second expr is the value. + /// First expr is the place; second expr is the value. ExprBox(Gc<Expr>, Gc<Expr>), ExprVec(Vec<Gc<Expr>>), ExprCall(Gc<Expr>, Vec<Gc<Expr>>), @@ -483,130 +515,127 @@ pub enum Expr_ { ExprMac(Mac), - // A struct literal expression. + /// A struct literal expression. ExprStruct(Path, Vec<Field> , Option<Gc<Expr>> /* base */), - // A vector literal constructed from one repeated element. + /// A vector literal constructed from one repeated element. ExprRepeat(Gc<Expr> /* element */, Gc<Expr> /* count */), - // No-op: used solely so we can pretty-print faithfully + /// No-op: used solely so we can pretty-print faithfully ExprParen(Gc<Expr>) } -// When the main rust parser encounters a syntax-extension invocation, it -// parses the arguments to the invocation as a token-tree. This is a very -// loose structure, such that all sorts of different AST-fragments can -// be passed to syntax extensions using a uniform type. -// -// If the syntax extension is an MBE macro, it will attempt to match its -// LHS "matchers" against the provided token tree, and if it finds a -// match, will transcribe the RHS token tree, splicing in any captured -// macro_parser::matched_nonterminals into the TTNonterminals it finds. -// -// The RHS of an MBE macro is the only place a TTNonterminal or TTSeq -// makes any real sense. You could write them elsewhere but nothing -// else knows what to do with them, so you'll probably get a syntax -// error. -// +/// When the main rust parser encounters a syntax-extension invocation, it +/// parses the arguments to the invocation as a token-tree. This is a very +/// loose structure, such that all sorts of different AST-fragments can +/// be passed to syntax extensions using a uniform type. +/// +/// If the syntax extension is an MBE macro, it will attempt to match its +/// LHS "matchers" against the provided token tree, and if it finds a +/// match, will transcribe the RHS token tree, splicing in any captured +/// macro_parser::matched_nonterminals into the TTNonterminals it finds. +/// +/// The RHS of an MBE macro is the only place a TTNonterminal or TTSeq +/// makes any real sense. You could write them elsewhere but nothing +/// else knows what to do with them, so you'll probably get a syntax +/// error. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] #[doc="For macro invocations; parsing is delegated to the macro"] pub enum TokenTree { - // a single token + /// A single token TTTok(Span, ::parse::token::Token), - // a delimited sequence (the delimiters appear as the first - // and last elements of the vector) + /// A delimited sequence (the delimiters appear as the first + /// and last elements of the vector) // FIXME(eddyb) #6308 Use Rc<[TokenTree]> after DST. TTDelim(Rc<Vec<TokenTree>>), // These only make sense for right-hand-sides of MBE macros: - // a kleene-style repetition sequence with a span, a TTForest, - // an optional separator, and a boolean where true indicates - // zero or more (..), and false indicates one or more (+). + /// A kleene-style repetition sequence with a span, a TTForest, + /// an optional separator, and a boolean where true indicates + /// zero or more (..), and false indicates one or more (+). // FIXME(eddyb) #6308 Use Rc<[TokenTree]> after DST. TTSeq(Span, Rc<Vec<TokenTree>>, Option<::parse::token::Token>, bool), - // a syntactic variable that will be filled in by macro expansion. + /// A syntactic variable that will be filled in by macro expansion. TTNonterminal(Span, Ident) } -// -// Matchers are nodes defined-by and recognized-by the main rust parser and -// language, but they're only ever found inside syntax-extension invocations; -// indeed, the only thing that ever _activates_ the rules in the rust parser -// for parsing a matcher is a matcher looking for the 'matchers' nonterminal -// itself. Matchers represent a small sub-language for pattern-matching -// token-trees, and are thus primarily used by the macro-defining extension -// itself. -// -// MatchTok -// -------- -// -// A matcher that matches a single token, denoted by the token itself. So -// long as there's no $ involved. -// -// -// MatchSeq -// -------- -// -// A matcher that matches a sequence of sub-matchers, denoted various -// possible ways: -// -// $(M)* zero or more Ms -// $(M)+ one or more Ms -// $(M),+ one or more comma-separated Ms -// $(A B C);* zero or more semi-separated 'A B C' seqs -// -// -// MatchNonterminal -// ----------------- -// -// A matcher that matches one of a few interesting named rust -// nonterminals, such as types, expressions, items, or raw token-trees. A -// black-box matcher on expr, for example, binds an expr to a given ident, -// and that ident can re-occur as an interpolation in the RHS of a -// macro-by-example rule. For example: -// -// $foo:expr => 1 + $foo // interpolate an expr -// $foo:tt => $foo // interpolate a token-tree -// $foo:tt => bar! $foo // only other valid interpolation -// // is in arg position for another -// // macro -// -// As a final, horrifying aside, note that macro-by-example's input is -// also matched by one of these matchers. Holy self-referential! It is matched -// by a MatchSeq, specifically this one: -// -// $( $lhs:matchers => $rhs:tt );+ -// -// If you understand that, you have closed to loop and understand the whole -// macro system. Congratulations. -// +/// Matchers are nodes defined-by and recognized-by the main rust parser and +/// language, but they're only ever found inside syntax-extension invocations; +/// indeed, the only thing that ever _activates_ the rules in the rust parser +/// for parsing a matcher is a matcher looking for the 'matchers' nonterminal +/// itself. Matchers represent a small sub-language for pattern-matching +/// token-trees, and are thus primarily used by the macro-defining extension +/// itself. +/// +/// MatchTok +/// -------- +/// +/// A matcher that matches a single token, denoted by the token itself. So +/// long as there's no $ involved. +/// +/// +/// MatchSeq +/// -------- +/// +/// A matcher that matches a sequence of sub-matchers, denoted various +/// possible ways: +/// +/// $(M)* zero or more Ms +/// $(M)+ one or more Ms +/// $(M),+ one or more comma-separated Ms +/// $(A B C);* zero or more semi-separated 'A B C' seqs +/// +/// +/// MatchNonterminal +/// ----------------- +/// +/// A matcher that matches one of a few interesting named rust +/// nonterminals, such as types, expressions, items, or raw token-trees. A +/// black-box matcher on expr, for example, binds an expr to a given ident, +/// and that ident can re-occur as an interpolation in the RHS of a +/// macro-by-example rule. For example: +/// +/// $foo:expr => 1 + $foo // interpolate an expr +/// $foo:tt => $foo // interpolate a token-tree +/// $foo:tt => bar! $foo // only other valid interpolation +/// // is in arg position for another +/// // macro +/// +/// As a final, horrifying aside, note that macro-by-example's input is +/// also matched by one of these matchers. Holy self-referential! It is matched +/// by a MatchSeq, specifically this one: +/// +/// $( $lhs:matchers => $rhs:tt );+ +/// +/// If you understand that, you have closed the loop and understand the whole +/// macro system. Congratulations. pub type Matcher = Spanned<Matcher_>; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum Matcher_ { - // match one token + /// Match one token MatchTok(::parse::token::Token), - // match repetitions of a sequence: body, separator, zero ok?, - // lo, hi position-in-match-array used: + /// Match repetitions of a sequence: body, separator, zero ok?, + /// lo, hi position-in-match-array used: MatchSeq(Vec<Matcher> , Option<::parse::token::Token>, bool, uint, uint), - // parse a Rust NT: name to bind, name of NT, position in match array: + /// Parse a Rust NT: name to bind, name of NT, position in match array: MatchNonterminal(Ident, Ident, uint) } pub type Mac = Spanned<Mac_>; -// represents a macro invocation. The Path indicates which macro -// is being invoked, and the vector of token-trees contains the source -// of the macro invocation. -// There's only one flavor, now, so this could presumably be simplified. +/// Represents a macro invocation. The Path indicates which macro +/// is being invoked, and the vector of token-trees contains the source +/// of the macro invocation. +/// There's only one flavor, now, so this could presumably be simplified. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum Mac_ { MacInvocTT(Path, Vec<TokenTree> , SyntaxContext), // new macro-invocation } -#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub enum StrStyle { CookedStr, RawStr(uint) @@ -614,7 +643,7 @@ pub enum StrStyle { pub type Lit = Spanned<Lit_>; -#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub enum Lit_ { LitStr(InternedString, StrStyle), LitBinary(Rc<Vec<u8> >), @@ -659,11 +688,10 @@ pub struct TypeMethod { pub vis: Visibility, } -/// Represents a method declaration in a trait declaration, possibly -/// including a default implementation -// A trait method is either required (meaning it doesn't have an -// implementation, just a signature) or provided (meaning it has a default -// implementation). +/// Represents a method declaration in a trait declaration, possibly including +/// a default implementation A trait method is either required (meaning it +/// doesn't have an implementation, just a signature) or provided (meaning it +/// has a default implementation). #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum TraitMethod { Required(TypeMethod), @@ -681,7 +709,17 @@ pub enum IntTy { impl fmt::Show for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", ast_util::int_ty_to_str(*self, None)) + write!(f, "{}", ast_util::int_ty_to_string(*self, None)) + } +} + +impl IntTy { + pub fn suffix_len(&self) -> uint { + match *self { + TyI => 1, + TyI8 => 2, + TyI16 | TyI32 | TyI64 => 3, + } } } @@ -694,9 +732,19 @@ pub enum UintTy { TyU64, } +impl UintTy { + pub fn suffix_len(&self) -> uint { + match *self { + TyU => 1, + TyU8 => 2, + TyU16 | TyU32 | TyU64 => 3, + } + } +} + impl fmt::Show for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", ast_util::uint_ty_to_str(*self, None)) + write!(f, "{}", ast_util::uint_ty_to_string(*self, None)) } } @@ -708,7 +756,15 @@ pub enum FloatTy { impl fmt::Show for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", ast_util::float_ty_to_str(*self)) + write!(f, "{}", ast_util::float_ty_to_string(*self)) + } +} + +impl FloatTy { + pub fn suffix_len(&self) -> uint { + match *self { + TyF32 | TyF64 => 3, // add F128 handling here + } } } @@ -720,7 +776,7 @@ pub struct Ty { pub span: Span, } -// Not represented directly in the AST, referred to by name through a ty_path. +/// Not represented directly in the AST, referred to by name through a ty_path. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum PrimTy { TyInt(IntTy), @@ -753,10 +809,10 @@ pub struct ClosureTy { pub fn_style: FnStyle, pub onceness: Onceness, pub decl: P<FnDecl>, - // Optional optvec distinguishes between "fn()" and "fn:()" so we can - // implement issue #7264. None means "fn()", which means infer a default - // bound based on pointer sigil during typeck. Some(Empty) means "fn:()", - // which means use no bounds (e.g., not even Owned on a ~fn()). + /// Optional optvec distinguishes between "fn()" and "fn:()" so we can + /// implement issue #7264. None means "fn()", which means infer a default + /// bound based on pointer sigil during typeck. Some(Empty) means "fn:()", + /// which means use no bounds (e.g., not even Owned on a ~fn()). pub bounds: Option<OwnedSlice<TyParamBound>>, } @@ -789,11 +845,11 @@ pub enum Ty_ { TyUnboxedFn(Gc<UnboxedFnTy>), TyTup(Vec<P<Ty>> ), TyPath(Path, Option<OwnedSlice<TyParamBound>>, NodeId), // for #7264; see above - // No-op; kept solely so that we can pretty-print faithfully + /// No-op; kept solely so that we can pretty-print faithfully TyParen(P<Ty>), TyTypeof(Gc<Expr>), - // TyInfer means the type should be inferred instead of it having been - // specified. This can appear anywhere in a type. + /// TyInfer means the type should be inferred instead of it having been + /// specified. This can appear anywhere in a type. TyInfer, } @@ -824,8 +880,8 @@ pub struct Arg { } impl Arg { - pub fn new_self(span: Span, mutability: Mutability) -> Arg { - let path = Spanned{span:span,node:special_idents::self_}; + pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg { + let path = Spanned{span:span,node:self_ident}; Arg { // HACK(eddyb) fake type for the self argument. ty: P(Ty { @@ -854,8 +910,10 @@ pub struct FnDecl { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum FnStyle { - UnsafeFn, // declared with "unsafe fn" - NormalFn, // declared with "fn" + /// Declared with "unsafe fn" + UnsafeFn, + /// Declared with "fn" + NormalFn, } impl fmt::Show for FnStyle { @@ -869,21 +927,29 @@ impl fmt::Show for FnStyle { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum RetStyle { - NoReturn, // functions with return type _|_ that always - // raise an error or exit (i.e. never return to the caller) - Return, // everything else + /// Functions with return type ! that always + /// raise an error or exit (i.e. never return to the caller) + NoReturn, + /// Everything else + Return, } +/// Represents the kind of 'self' associated with a method #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum ExplicitSelf_ { - SelfStatic, // no self - SelfValue, // `self` - SelfRegion(Option<Lifetime>, Mutability), // `&'lt self`, `&'lt mut self` - SelfUniq // `~self` + /// No self + SelfStatic, + /// `self + SelfValue(Ident), + /// `&'lt self`, `&'lt mut self` + SelfRegion(Option<Lifetime>, Mutability, Ident), + /// `~self` + SelfUniq(Ident) } pub type ExplicitSelf = Spanned<ExplicitSelf_>; +// Represents a method declaration #[deriving(PartialEq, Eq, Encodable, Decodable, Hash)] pub struct Method { pub ident: Ident, @@ -957,17 +1023,17 @@ pub type ViewPath = Spanned<ViewPath_>; #[deriving(PartialEq, Eq, Encodable, Decodable, Hash)] pub enum ViewPath_ { - // quux = foo::bar::baz - // - // or just - // - // foo::bar::baz (with 'baz =' implicitly on the left) + /// `quux = foo::bar::baz` + /// + /// or just + /// + /// `foo::bar::baz ` (with 'baz =' implicitly on the left) ViewPathSimple(Ident, Path, NodeId), - // foo::bar::* + /// `foo::bar::*` ViewPathGlob(Path, NodeId), - // foo::bar::{a,b,c} + /// `foo::bar::{a,b,c}` ViewPathList(Path, Vec<PathListIdent> , NodeId) } @@ -981,20 +1047,20 @@ pub struct ViewItem { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum ViewItem_ { - // ident: name used to refer to this crate in the code - // optional (InternedString,StrStyle): if present, this is a location - // (containing arbitrary characters) from which to fetch the crate sources - // For example, extern crate whatever = "github.com/rust-lang/rust" + /// Ident: name used to refer to this crate in the code + /// optional (InternedString,StrStyle): if present, this is a location + /// (containing arbitrary characters) from which to fetch the crate sources + /// For example, extern crate whatever = "github.com/rust-lang/rust" ViewItemExternCrate(Ident, Option<(InternedString,StrStyle)>, NodeId), ViewItemUse(Gc<ViewPath>), } -// Meta-data associated with an item +/// Meta-data associated with an item pub type Attribute = Spanned<Attribute_>; -// Distinguishes between Attributes that decorate items and Attributes that -// are contained as statements within items. These two cases need to be -// distinguished for pretty-printing. +/// Distinguishes between Attributes that decorate items and Attributes that +/// are contained as statements within items. These two cases need to be +/// distinguished for pretty-printing. #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum AttrStyle { AttrOuter, @@ -1004,7 +1070,7 @@ pub enum AttrStyle { #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct AttrId(pub uint); -// doc-comments are promoted to attributes that have is_sugared_doc = true +/// Doc-comments are promoted to attributes that have is_sugared_doc = true #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct Attribute_ { pub id: AttrId, @@ -1013,13 +1079,12 @@ pub struct Attribute_ { pub is_sugared_doc: bool, } -/* - TraitRef's appear in impls. - resolve maps each TraitRef's ref_id to its defining trait; that's all - that the ref_id is for. The impl_id maps to the "self type" of this impl. - If this impl is an ItemImpl, the impl_id is redundant (it could be the - same as the impl's node id). - */ + +/// TraitRef's appear in impls. +/// resolve maps each TraitRef's ref_id to its defining trait; that's all +/// that the ref_id is for. The impl_id maps to the "self type" of this impl. +/// If this impl is an ItemImpl, the impl_id is redundant (it could be the +/// same as the impl's node id). #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct TraitRef { pub path: Path, @@ -1042,12 +1107,6 @@ impl Visibility { } #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] -pub enum Sized { - DynSize, - StaticSize, -} - -#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct StructField_ { pub kind: StructFieldKind, pub id: NodeId, @@ -1069,7 +1128,8 @@ pub type StructField = Spanned<StructField_>; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub enum StructFieldKind { NamedField(Ident, Visibility), - UnnamedField(Visibility), // element of a tuple-like struct + /// Element of a tuple-like struct + UnnamedField(Visibility), } impl StructFieldKind { @@ -1083,12 +1143,15 @@ impl StructFieldKind { #[deriving(PartialEq, Eq, Encodable, Decodable, Hash)] pub struct StructDef { - pub fields: Vec<StructField>, /* fields, not including ctor */ - /* ID of the constructor. This is only used for tuple- or enum-like - * structs. */ + /// Fields, not including ctor + pub fields: Vec<StructField>, + /// ID of the constructor. This is only used for tuple- or enum-like + /// structs. pub ctor_id: Option<NodeId>, - pub super_struct: Option<P<Ty>>, // Super struct, if specified. - pub is_virtual: bool, // True iff the struct may be inherited from. + /// Super struct, if specified. + pub super_struct: Option<P<Ty>>, + /// True iff the struct may be inherited from. + pub is_virtual: bool, } /* @@ -1115,12 +1178,16 @@ pub enum Item_ { ItemEnum(EnumDef, Generics), ItemStruct(Gc<StructDef>, Generics), /// Represents a Trait Declaration - ItemTrait(Generics, Sized, Vec<TraitRef> , Vec<TraitMethod> ), + ItemTrait(Generics, + Option<TyParamBound>, // (optional) default bound not required for Self. + // Currently, only Sized makes sense here. + Vec<TraitRef> , + Vec<TraitMethod>), ItemImpl(Generics, Option<TraitRef>, // (optional) trait this impl implements P<Ty>, // self Vec<Gc<Method>>), - // a macro invocation (which includes macro definition) + /// A macro invocation (which includes macro definition) ItemMac(Mac), } @@ -1140,9 +1207,9 @@ pub enum ForeignItem_ { ForeignItemStatic(P<Ty>, /* is_mutbl */ bool), } -// The data we save and restore about an inlined item or method. This is not -// part of the AST that we parse from a file, but it becomes part of the tree -// that we trans. +/// The data we save and restore about an inlined item or method. This is not +/// part of the AST that we parse from a file, but it becomes part of the tree +/// that we trans. #[deriving(PartialEq, Eq, Encodable, Decodable, Hash)] pub enum InlinedItem { IIItem(Gc<Item>), diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 1a9a910f38c..25c8e81bdbc 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -79,7 +79,7 @@ impl<'a, T: Copy> Iterator<T> for Values<'a, T> { /// The type of the iterator used by with_path. pub type PathElems<'a, 'b> = iter::Chain<Values<'a, PathElem>, LinkedPath<'b>>; -pub fn path_to_str<PI: Iterator<PathElem>>(mut path: PI) -> String { +pub fn path_to_string<PI: Iterator<PathElem>>(mut path: PI) -> String { let itr = token::get_ident_interner(); path.fold(String::new(), |mut s, e| { @@ -112,13 +112,13 @@ pub enum Node { NodeLifetime(Gc<Lifetime>), } -// The odd layout is to bring down the total size. +/// The odd layout is to bring down the total size. #[deriving(Clone)] enum MapEntry { - // Placeholder for holes in the map. + /// Placeholder for holes in the map. NotPresent, - // All the node types, with a parent ID. + /// All the node types, with a parent ID. EntryItem(NodeId, Gc<Item>), EntryForeignItem(NodeId, Gc<ForeignItem>), EntryTraitMethod(NodeId, Gc<TraitMethod>), @@ -133,14 +133,14 @@ enum MapEntry { EntryStructCtor(NodeId, Gc<StructDef>), EntryLifetime(NodeId, Gc<Lifetime>), - // Roots for node trees. + /// Roots for node trees. RootCrate, RootInlinedParent(P<InlinedParent>) } struct InlinedParent { path: Vec<PathElem> , - // Required by NodeTraitMethod and NodeMethod. + /// Required by NodeTraitMethod and NodeMethod. def_id: DefId } @@ -243,14 +243,14 @@ impl Map { ItemForeignMod(ref nm) => Some(nm.abi), _ => None }, - // Wrong but OK, because the only inlined foreign items are intrinsics. + /// Wrong but OK, because the only inlined foreign items are intrinsics. Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic), _ => None }; match abi { Some(abi) => abi, None => fail!("expected foreign mod or inlined parent, found {}", - self.node_to_str(parent)) + self.node_to_string(parent)) } } @@ -265,7 +265,7 @@ impl Map { pub fn expect_item(&self, id: NodeId) -> Gc<Item> { match self.find(id) { Some(NodeItem(item)) => item, - _ => fail!("expected item, found {}", self.node_to_str(id)) + _ => fail!("expected item, found {}", self.node_to_string(id)) } } @@ -283,21 +283,21 @@ impl Map { _ => fail!("struct ID bound to enum variant that isn't struct-like"), } } - _ => fail!(format!("expected struct, found {}", self.node_to_str(id))), + _ => fail!(format!("expected struct, found {}", self.node_to_string(id))), } } pub fn expect_variant(&self, id: NodeId) -> P<Variant> { match self.find(id) { Some(NodeVariant(variant)) => variant, - _ => fail!(format!("expected variant, found {}", self.node_to_str(id))), + _ => fail!(format!("expected variant, found {}", self.node_to_string(id))), } } pub fn expect_foreign_item(&self, id: NodeId) -> Gc<ForeignItem> { match self.find(id) { Some(NodeForeignItem(item)) => item, - _ => fail!("expected foreign item, found {}", self.node_to_str(id)) + _ => fail!("expected foreign item, found {}", self.node_to_string(id)) } } @@ -326,13 +326,13 @@ impl Map { self.with_path_next(id, None, f) } - pub fn path_to_str(&self, id: NodeId) -> String { - self.with_path(id, |path| path_to_str(path)) + pub fn path_to_string(&self, id: NodeId) -> String { + self.with_path(id, |path| path_to_string(path)) } fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String { self.with_path(id, |path| { - path_to_str(path.chain(Some(PathName(i.name)).move_iter())) + path_to_string(path.chain(Some(PathName(i.name)).move_iter())) }) } @@ -416,8 +416,8 @@ impl Map { .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id)) } - pub fn node_to_str(&self, id: NodeId) -> String { - node_id_to_str(self, id) + pub fn node_to_string(&self, id: NodeId) -> String { + node_id_to_string(self, id) } } @@ -432,8 +432,8 @@ pub trait FoldOps { pub struct Ctx<'a, F> { map: &'a Map, - // The node in which we are currently mapping (an item or a method). - // When equal to DUMMY_NODE_ID, the next mapped node becomes the parent. + /// The node in which we are currently mapping (an item or a method). + /// When equal to DUMMY_NODE_ID, the next mapped node becomes the parent. parent: NodeId, fold_ops: F } @@ -618,9 +618,9 @@ pub fn map_crate<F: FoldOps>(krate: Crate, fold_ops: F) -> (Crate, Map) { (krate, map) } -// Used for items loaded from external crate that are being inlined into this -// crate. The `path` should be the path to the item but should not include -// the item itself. +/// Used for items loaded from external crate that are being inlined into this +/// crate. The `path` should be the path to the item but should not include +/// the item itself. pub fn map_decoded_item<F: FoldOps>(map: &Map, path: Vec<PathElem> , fold_ops: F, @@ -664,7 +664,7 @@ pub fn map_decoded_item<F: FoldOps>(map: &Map, ii } -fn node_id_to_str(map: &Map, id: NodeId) -> String { +fn node_id_to_string(map: &Map, id: NodeId) -> String { match map.find(id) { Some(NodeItem(item)) => { let path_str = map.path_to_str_with_ident(id, item.ident); @@ -689,43 +689,43 @@ fn node_id_to_str(map: &Map, id: NodeId) -> String { Some(NodeMethod(m)) => { format!("method {} in {} (id={})", token::get_ident(m.ident), - map.path_to_str(id), id) + map.path_to_string(id), id) } Some(NodeTraitMethod(ref tm)) => { let m = ast_util::trait_method_to_ty_method(&**tm); format!("method {} in {} (id={})", token::get_ident(m.ident), - map.path_to_str(id), id) + map.path_to_string(id), id) } Some(NodeVariant(ref variant)) => { format!("variant {} in {} (id={})", token::get_ident(variant.node.name), - map.path_to_str(id), id) + map.path_to_string(id), id) } Some(NodeExpr(ref expr)) => { - format!("expr {} (id={})", pprust::expr_to_str(&**expr), id) + format!("expr {} (id={})", pprust::expr_to_string(&**expr), id) } Some(NodeStmt(ref stmt)) => { - format!("stmt {} (id={})", pprust::stmt_to_str(&**stmt), id) + format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id) } Some(NodeArg(ref pat)) => { - format!("arg {} (id={})", pprust::pat_to_str(&**pat), id) + format!("arg {} (id={})", pprust::pat_to_string(&**pat), id) } Some(NodeLocal(ref pat)) => { - format!("local {} (id={})", pprust::pat_to_str(&**pat), id) + format!("local {} (id={})", pprust::pat_to_string(&**pat), id) } Some(NodePat(ref pat)) => { - format!("pat {} (id={})", pprust::pat_to_str(&**pat), id) + format!("pat {} (id={})", pprust::pat_to_string(&**pat), id) } Some(NodeBlock(ref block)) => { - format!("block {} (id={})", pprust::block_to_str(&**block), id) + format!("block {} (id={})", pprust::block_to_string(&**block), id) } Some(NodeStructCtor(_)) => { - format!("struct_ctor {} (id={})", map.path_to_str(id), id) + format!("struct_ctor {} (id={})", map.path_to_string(id), id) } Some(NodeLifetime(ref l)) => { format!("lifetime {} (id={})", - pprust::lifetime_to_str(&**l), id) + pprust::lifetime_to_string(&**l), id) } None => { format!("unknown node (id={})", id) diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 036d6b4b43a..13fe8a15064 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -48,7 +48,7 @@ pub fn stmt_id(s: &Stmt) -> NodeId { } } -pub fn binop_to_str(op: BinOp) -> &'static str { +pub fn binop_to_string(op: BinOp) -> &'static str { match op { BiAdd => "+", BiSub => "-", @@ -87,7 +87,7 @@ pub fn is_shift_binop(b: BinOp) -> bool { } } -pub fn unop_to_str(op: UnOp) -> &'static str { +pub fn unop_to_string(op: UnOp) -> &'static str { match op { UnBox => "box(GC) ", UnUniq => "box() ", @@ -101,9 +101,9 @@ pub fn is_path(e: Gc<Expr>) -> bool { return match e.node { ExprPath(_) => true, _ => false }; } -// Get a string representation of a signed int type, with its value. -// We want to avoid "45int" and "-3int" in favor of "45" and "-3" -pub fn int_ty_to_str(t: IntTy, val: Option<i64>) -> String { +/// Get a string representation of a signed int type, with its value. +/// We want to avoid "45int" and "-3int" in favor of "45" and "-3" +pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { TyI if val.is_some() => "i", TyI => "int", @@ -131,9 +131,9 @@ pub fn int_ty_max(t: IntTy) -> u64 { } } -// Get a string representation of an unsigned int type, with its value. -// We want to avoid "42uint" in favor of "42u" -pub fn uint_ty_to_str(t: UintTy, val: Option<u64>) -> String { +/// Get a string representation of an unsigned int type, with its value. +/// We want to avoid "42uint" in favor of "42u" +pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String { let s = match t { TyU if val.is_some() => "u", TyU => "uint", @@ -158,7 +158,7 @@ pub fn uint_ty_max(t: UintTy) -> u64 { } } -pub fn float_ty_to_str(t: FloatTy) -> String { +pub fn float_ty_to_string(t: FloatTy) -> String { match t { TyF32 => "f32".to_string(), TyF64 => "f64".to_string(), @@ -229,11 +229,11 @@ pub fn unguarded_pat(a: &Arm) -> Option<Vec<Gc<Pat>>> { /// listed as `__extensions__::method_name::hash`, with no indication /// of the type). pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident { - let mut pretty = pprust::ty_to_str(ty); + let mut pretty = pprust::ty_to_string(ty); match *trait_ref { Some(ref trait_ref) => { pretty.push_char('.'); - pretty.push_str(pprust::path_to_str(&trait_ref.path).as_slice()); + pretty.push_str(pprust::path_to_string(&trait_ref.path).as_slice()); } None => {} } @@ -249,8 +249,8 @@ pub fn public_methods(ms: Vec<Gc<Method>> ) -> Vec<Gc<Method>> { }).collect() } -// extract a TypeMethod from a TraitMethod. if the TraitMethod is -// a default, pull out the useful fields to make a TypeMethod +/// extract a TypeMethod from a TraitMethod. if the TraitMethod is +/// a default, pull out the useful fields to make a TypeMethod pub fn trait_method_to_ty_method(method: &TraitMethod) -> TypeMethod { match *method { Required(ref m) => (*m).clone(), @@ -705,7 +705,7 @@ pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> boo } } -// Returns true if this literal is a string and false otherwise. +/// Returns true if this literal is a string and false otherwise. pub fn lit_is_str(lit: Gc<Lit>) -> bool { match lit.node { LitStr(..) => true, @@ -754,14 +754,14 @@ mod test { #[test] fn idents_name_eq_test() { assert!(segments_name_eq( - [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}] + [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(), - [Ident{name:3,ctxt:104}, Ident{name:78,ctxt:182}] + [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice())); assert!(!segments_name_eq( - [Ident{name:3,ctxt:4}, Ident{name:78,ctxt:82}] + [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice(), - [Ident{name:3,ctxt:104}, Ident{name:77,ctxt:182}] + [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().as_slice())); } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 3b2ee4e2a61..e8b9ec9628f 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -46,10 +46,8 @@ pub trait AttrMetaMethods { /// #[foo="bar"] and #[foo(bar)] fn name(&self) -> InternedString; - /** - * Gets the string value if self is a MetaNameValue variant - * containing a string, otherwise None. - */ + /// Gets the string value if self is a MetaNameValue variant + /// containing a string, otherwise None. fn value_str(&self) -> Option<InternedString>; /// Gets a list of inner meta items from a list MetaItem type. fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<MetaItem>]>; @@ -420,18 +418,16 @@ pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[Gc<MetaItem>]) { } -/** - * Fold this over attributes to parse #[repr(...)] forms. - * - * Valid repr contents: any of the primitive integral type names (see - * `int_type_of_word`, below) to specify the discriminant type; and `C`, to use - * the same discriminant size that the corresponding C enum would. These are - * not allowed on univariant or zero-variant enums, which have no discriminant. - * - * If a discriminant type is so specified, then the discriminant will be - * present (before fields, if any) with that type; reprensentation - * optimizations which would remove it will not be done. - */ +/// Fold this over attributes to parse #[repr(...)] forms. +/// +/// Valid repr contents: any of the primitive integral type names (see +/// `int_type_of_word`, below) to specify the discriminant type; and `C`, to use +/// the same discriminant size that the corresponding C enum would. These are +/// not allowed on univariant or zero-variant enums, which have no discriminant. +/// +/// If a discriminant type is so specified, then the discriminant will be +/// present (before fields, if any) with that type; reprensentation +/// optimizations which would remove it will not be done. pub fn find_repr_attr(diagnostic: &SpanHandler, attr: &Attribute, acc: ReprAttr) -> ReprAttr { let mut acc = acc; diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index c917198e7d4..ef4024a8f83 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -96,7 +96,7 @@ pub struct Span { pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; -#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub struct Spanned<T> { pub node: T, pub span: Span, @@ -252,15 +252,15 @@ pub struct FileMap { } impl FileMap { - // EFFECT: register a start-of-line offset in the - // table of line-beginnings. - // UNCHECKED INVARIANT: these offsets must be added in the right - // order and must be in the right places; there is shared knowledge - // about what ends a line between this file and parse.rs - // WARNING: pos param here is the offset relative to start of CodeMap, - // and CodeMap will append a newline when adding a filemap without a newline at the end, - // so the safe way to call this is with value calculated as - // filemap.start_pos + newline_offset_relative_to_the_start_of_filemap. + /// EFFECT: register a start-of-line offset in the + /// table of line-beginnings. + /// UNCHECKED INVARIANT: these offsets must be added in the right + /// order and must be in the right places; there is shared knowledge + /// about what ends a line between this file and parse.rs + /// WARNING: pos param here is the offset relative to start of CodeMap, + /// and CodeMap will append a newline when adding a filemap without a newline at the end, + /// so the safe way to call this is with value calculated as + /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap. pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let mut lines = self.lines.borrow_mut();; @@ -269,7 +269,7 @@ impl FileMap { lines.push(pos); } - // get a line from the list of pre-computed line-beginnings + /// get a line from the list of pre-computed line-beginnings pub fn get_line(&self, line: int) -> String { let mut lines = self.lines.borrow_mut(); let begin: BytePos = *lines.get(line as uint) - self.start_pos; @@ -367,7 +367,7 @@ impl CodeMap { } } - pub fn span_to_str(&self, sp: Span) -> String { + pub fn span_to_string(&self, sp: Span) -> String { if self.files.borrow().len() == 0 && sp == DUMMY_SP { return "no-location".to_string(); } @@ -428,9 +428,8 @@ impl CodeMap { FileMapAndBytePos {fm: fm, pos: offset} } - // Converts an absolute BytePos to a CharPos relative to the filemap and above. + /// Converts an absolute BytePos to a CharPos relative to the filemap and above. pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { - debug!("codemap: converting {:?} to char pos", bpos); let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); let map = files.get(idx); @@ -439,7 +438,7 @@ impl CodeMap { let mut total_extra_bytes = 0; for mbc in map.multibyte_chars.borrow().iter() { - debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos); + debug!("{}-byte char at {}", mbc.bytes, mbc.pos); if mbc.pos < bpos { // every character is at least one byte, so we only // count the actual extra bytes. @@ -514,11 +513,11 @@ impl CodeMap { let chpos = self.bytepos_to_file_charpos(pos); let linebpos = *f.lines.borrow().get(a); let linechpos = self.bytepos_to_file_charpos(linebpos); - debug!("codemap: byte pos {:?} is on the line at byte pos {:?}", + debug!("byte pos {} is on the line at byte pos {}", pos, linebpos); - debug!("codemap: char pos {:?} is on the line at char pos {:?}", + debug!("char pos {} is on the line at char pos {}", chpos, linechpos); - debug!("codemap: byte is on line: {:?}", line); + debug!("byte is on line: {}", line); assert!(chpos >= linechpos); Loc { file: f, @@ -687,7 +686,7 @@ mod test { // Test span_to_str for a span ending at the end of filemap let cm = init_code_map(); let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None}; - let sstr = cm.span_to_str(span); + let sstr = cm.span_to_string(span); assert_eq!(sstr, "blork.rs:2:1: 2:12".to_string()); } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index dfaa9fb5fcb..e469f327ae8 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -21,7 +21,7 @@ use std::string::String; use term::WriterWrapper; use term; -// maximum number of lines we will print for each error; arbitrary. +/// maximum number of lines we will print for each error; arbitrary. static MAX_LINES: uint = 6u; #[deriving(Clone)] @@ -73,9 +73,9 @@ pub struct FatalError; /// or `.span_bug` rather than a failed assertion, etc. pub struct ExplicitBug; -// a span-handler is like a handler but also -// accepts span information for source-location -// reporting. +/// A span-handler is like a handler but also +/// accepts span information for source-location +/// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, @@ -114,9 +114,9 @@ impl SpanHandler { } } -// a handler deals with errors; certain errors -// (fatal, bug, unimpl) may cause immediate exit, -// others log errors for later reporting. +/// A handler deals with errors; certain errors +/// (fatal, bug, unimpl) may cause immediate exit, +/// others log errors for later reporting. pub struct Handler { err_count: Cell<uint>, emit: RefCell<Box<Emitter + Send>>, @@ -269,7 +269,7 @@ fn print_diagnostic(dst: &mut EmitterWriter, } try!(print_maybe_styled(dst, - format!("{}: ", lvl.to_str()).as_slice(), + format!("{}: ", lvl.to_string()).as_slice(), term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, format!("{}\n", msg).as_slice(), @@ -349,14 +349,14 @@ impl Emitter for EmitterWriter { fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); - let ss = cm.span_to_str(sp); + let ss = cm.span_to_string(sp); let lines = cm.span_to_lines(sp); if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info}; - let ses = cm.span_to_str(span_end); + let ses = cm.span_to_string(span_end); try!(print_diagnostic(dst, ses.as_slice(), lvl, msg)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, lines)); @@ -442,12 +442,12 @@ fn highlight_lines(err: &mut EmitterWriter, Ok(()) } -// Here are the differences between this and the normal `highlight_lines`: -// `custom_highlight_lines` will always put arrow on the last byte of the -// span (instead of the first byte). Also, when the span is too long (more -// than 6 lines), `custom_highlight_lines` will print the first line, then -// dot dot dot, then last line, whereas `highlight_lines` prints the first -// six lines. +/// Here are the differences between this and the normal `highlight_lines`: +/// `custom_highlight_lines` will always put arrow on the last byte of the +/// span (instead of the first byte). Also, when the span is too long (more +/// than 6 lines), `custom_highlight_lines` will print the first line, then +/// dot dot dot, then last line, whereas `highlight_lines` prints the first +/// six lines. fn custom_highlight_lines(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span, @@ -493,7 +493,7 @@ fn print_macro_backtrace(w: &mut EmitterWriter, let ss = ei.callee .span .as_ref() - .map_or("".to_string(), |span| cm.span_to_str(*span)); + .map_or("".to_string(), |span| cm.span_to_string(*span)); let (pre, post) = match ei.callee.format { codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") @@ -502,7 +502,7 @@ fn print_macro_backtrace(w: &mut EmitterWriter, format!("in expansion of {}{}{}", pre, ei.callee.name, post).as_slice())); - let ss = cm.span_to_str(ei.call_site); + let ss = cm.span_to_string(ei.call_site); try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site")); try!(print_macro_backtrace(w, cm, ei.call_site)); } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index f0494e18120..13738e658e9 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -64,7 +64,7 @@ pub fn expand_asm(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) 'statement: loop { match state { Asm => { - let (s, style) = match expr_to_str(cx, p.parse_expr(), + let (s, style) = match expr_to_string(cx, p.parse_expr(), "inline assembly must be a string literal.") { Some((s, st)) => (s, st), // let compilation continue @@ -205,7 +205,7 @@ pub fn expand_asm(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // Append an input operand, with the form of ("0", expr) // that links to an output operand. for &(i, out) in read_write_operands.iter() { - inputs.push((token::intern_and_get_ident(i.to_str().as_slice()), + inputs.push((token::intern_and_get_ident(i.to_string().as_slice()), out)); } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 673ae31ef77..9a5c7e86d21 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -264,16 +264,23 @@ pub enum SyntaxExtension { /// A function-like syntax extension that has an extra ident before /// the block. /// - /// `macro_rules!` is an `IdentTT`. IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>), + + /// An ident macro that has two properties: + /// - it adds a macro definition to the environment, and + /// - the definition it adds doesn't introduce any new + /// identifiers. + /// + /// `macro_rules!` is a LetSyntaxTT + LetSyntaxTT(Box<IdentMacroExpander + 'static>, Option<Span>), } pub type NamedSyntaxExtension = (Name, SyntaxExtension); pub struct BlockInfo { - // should macros escape from this scope? + /// Should macros escape from this scope? pub macros_escape: bool, - // what are the pending renames? + /// What are the pending renames? pub pending_renames: mtwt::RenameList, } @@ -286,8 +293,8 @@ impl BlockInfo { } } -// The base map of methods for expanding syntax extension -// AST nodes into full ASTs +/// The base map of methods for expanding syntax extension +/// AST nodes into full ASTs pub fn syntax_expander_table() -> SyntaxEnv { // utility function to simplify creating NormalTT syntax extensions fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension { @@ -300,7 +307,7 @@ pub fn syntax_expander_table() -> SyntaxEnv { let mut syntax_expanders = SyntaxEnv::new(); syntax_expanders.insert(intern("macro_rules"), - IdentTT(box BasicIdentMacroExpander { + LetSyntaxTT(box BasicIdentMacroExpander { expander: ext::tt::macro_rules::add_new_extension, span: None, }, @@ -391,9 +398,9 @@ pub fn syntax_expander_table() -> SyntaxEnv { syntax_expanders } -// One of these is made during expansion and incrementally updated as we go; -// when a macro expansion occurs, the resulting nodes have the backtrace() -// -> expn_info of their expansion context stored into their span. +/// One of these is made during expansion and incrementally updated as we go; +/// when a macro expansion occurs, the resulting nodes have the backtrace() +/// -> expn_info of their expansion context stored into their span. pub struct ExtCtxt<'a> { pub parse_sess: &'a parse::ParseSess, pub cfg: ast::CrateConfig, @@ -528,12 +535,15 @@ impl<'a> ExtCtxt<'a> { pub fn ident_of(&self, st: &str) -> ast::Ident { str_to_ident(st) } + pub fn name_of(&self, st: &str) -> ast::Name { + token::intern(st) + } } /// Extract a string literal from the macro expanded version of `expr`, /// emitting `err_msg` if `expr` is not a string literal. This does not stop /// compilation on error, merely emits a non-fatal error and returns None. -pub fn expr_to_str(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str) +pub fn expr_to_string(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str) -> Option<(InternedString, ast::StrStyle)> { // we want to be able to handle e.g. concat("foo", "bar") let expr = cx.expand_expr(expr); @@ -572,9 +582,9 @@ pub fn get_single_str_from_tts(cx: &ExtCtxt, cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice()); } else { match tts[0] { - ast::TTTok(_, token::LIT_STR(ident)) - | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => { - return Some(token::get_ident(ident).get().to_string()) + ast::TTTok(_, token::LIT_STR(ident)) => return Some(parse::str_lit(ident.as_str())), + ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => { + return Some(parse::raw_str_lit(ident.as_str())) } _ => { cx.span_err(sp, @@ -605,11 +615,11 @@ pub fn get_exprs_from_tts(cx: &mut ExtCtxt, Some(es) } -// in order to have some notion of scoping for macros, -// we want to implement the notion of a transformation -// environment. +/// In order to have some notion of scoping for macros, +/// we want to implement the notion of a transformation +/// environment. -// This environment maps Names to SyntaxExtensions. +/// This environment maps Names to SyntaxExtensions. //impl question: how to implement it? Initially, the // env will contain only macros, so it might be painful @@ -626,7 +636,6 @@ struct MapChainFrame { map: HashMap<Name, SyntaxExtension>, } -// Only generic to make it easy to test pub struct SyntaxEnv { chain: Vec<MapChainFrame> , } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 46bc4ec11ce..4d79ff3257a 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -66,8 +66,8 @@ pub trait AstBuilder { fn typaram(&self, span: Span, id: ast::Ident, - sized: ast::Sized, bounds: OwnedSlice<ast::TyParamBound>, + unbound: Option<ast::TyParamBound>, default: Option<P<ast::Ty>>) -> ast::TyParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; @@ -396,14 +396,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn typaram(&self, span: Span, id: ast::Ident, - sized: ast::Sized, bounds: OwnedSlice<ast::TyParamBound>, + unbound: Option<ast::TyParamBound>, default: Option<P<ast::Ty>>) -> ast::TyParam { ast::TyParam { ident: id, id: ast::DUMMY_NODE_ID, - sized: sized, bounds: bounds, + unbound: unbound, default: default, span: span } @@ -423,7 +423,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn strip_bounds(&self, generics: &Generics) -> Generics { let new_params = generics.ty_params.map(|ty_param| { - ast::TyParam { bounds: OwnedSlice::empty(), ..*ty_param } + ast::TyParam { bounds: OwnedSlice::empty(), unbound: None, ..*ty_param } }); Generics { ty_params: new_params, diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 0c23d65fde0..6da5f1e2700 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -13,7 +13,6 @@ The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more. */ -use ast; use ast::{MetaItem, Item, Expr, MutMutable, Ident}; use codemap::Span; use ext::base::ExtCtxt; @@ -39,10 +38,10 @@ pub fn expand_deriving_decodable(cx: &mut ExtCtxt, additional_bounds: Vec::new(), generics: LifetimeBounds { lifetimes: Vec::new(), - bounds: vec!(("__D", ast::StaticSize, vec!(Path::new_( + bounds: vec!(("__D", None, vec!(Path::new_( vec!("serialize", "Decoder"), None, vec!(box Literal(Path::new_local("__E"))), true))), - ("__E", ast::StaticSize, vec!())) + ("__E", None, vec!())) }, methods: vec!( MethodDef { diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index f57670af199..3b34407edfe 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -8,81 +8,77 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! +//! The compiler code necessary to implement the `#[deriving(Encodable)]` +//! (and `Decodable`, in decodable.rs) extension. The idea here is that +//! type-defining items may be tagged with `#[deriving(Encodable, Decodable)]`. +//! +//! For example, a type like: +//! +//! ```ignore +//! #[deriving(Encodable, Decodable)] +//! struct Node { id: uint } +//! ``` +//! +//! would generate two implementations like: +//! +//! ```ignore +//! impl<S:serialize::Encoder> Encodable<S> for Node { +//! fn encode(&self, s: &S) { +//! s.emit_struct("Node", 1, || { +//! s.emit_field("id", 0, || s.emit_uint(self.id)) +//! }) +//! } +//! } +//! +//! impl<D:Decoder> Decodable for node_id { +//! fn decode(d: &D) -> Node { +//! d.read_struct("Node", 1, || { +//! Node { +//! id: d.read_field("x".to_string(), 0, || decode(d)) +//! } +//! }) +//! } +//! } +//! ``` +//! +//! Other interesting scenarios are whe the item has type parameters or +//! references other non-built-in types. A type definition like: +//! +//! ```ignore +//! #[deriving(Encodable, Decodable)] +//! struct spanned<T> { node: T, span: Span } +//! ``` +//! +//! would yield functions like: +//! +//! ```ignore +//! impl< +//! S: Encoder, +//! T: Encodable<S> +//! > spanned<T>: Encodable<S> { +//! fn encode<S:Encoder>(s: &S) { +//! s.emit_rec(|| { +//! s.emit_field("node", 0, || self.node.encode(s)); +//! s.emit_field("span", 1, || self.span.encode(s)); +//! }) +//! } +//! } +//! +//! impl< +//! D: Decoder, +//! T: Decodable<D> +//! > spanned<T>: Decodable<D> { +//! fn decode(d: &D) -> spanned<T> { +//! d.read_rec(|| { +//! { +//! node: d.read_field("node".to_string(), 0, || decode(d)), +//! span: d.read_field("span".to_string(), 1, || decode(d)), +//! } +//! }) +//! } +//! } +//! ``` -The compiler code necessary to implement the `#[deriving(Encodable)]` -(and `Decodable`, in decodable.rs) extension. The idea here is that -type-defining items may be tagged with `#[deriving(Encodable, Decodable)]`. - -For example, a type like: - -```ignore -#[deriving(Encodable, Decodable)] -struct Node { id: uint } -``` - -would generate two implementations like: - -```ignore -impl<S:serialize::Encoder> Encodable<S> for Node { - fn encode(&self, s: &S) { - s.emit_struct("Node", 1, || { - s.emit_field("id", 0, || s.emit_uint(self.id)) - }) - } -} - -impl<D:Decoder> Decodable for node_id { - fn decode(d: &D) -> Node { - d.read_struct("Node", 1, || { - Node { - id: d.read_field("x".to_string(), 0, || decode(d)) - } - }) - } -} -``` - -Other interesting scenarios are whe the item has type parameters or -references other non-built-in types. A type definition like: - -```ignore -#[deriving(Encodable, Decodable)] -struct spanned<T> { node: T, span: Span } -``` - -would yield functions like: - -```ignore - impl< - S: Encoder, - T: Encodable<S> - > spanned<T>: Encodable<S> { - fn encode<S:Encoder>(s: &S) { - s.emit_rec(|| { - s.emit_field("node", 0, || self.node.encode(s)); - s.emit_field("span", 1, || self.span.encode(s)); - }) - } - } - - impl< - D: Decoder, - T: Decodable<D> - > spanned<T>: Decodable<D> { - fn decode(d: &D) -> spanned<T> { - d.read_rec(|| { - { - node: d.read_field("node".to_string(), 0, || decode(d)), - span: d.read_field("span".to_string(), 1, || decode(d)), - } - }) - } - } -``` -*/ - -use ast; use ast::{MetaItem, Item, Expr, ExprRet, MutMutable, LitNil}; use codemap::Span; use ext::base::ExtCtxt; @@ -107,10 +103,10 @@ pub fn expand_deriving_encodable(cx: &mut ExtCtxt, additional_bounds: Vec::new(), generics: LifetimeBounds { lifetimes: Vec::new(), - bounds: vec!(("__S", ast::StaticSize, vec!(Path::new_( + bounds: vec!(("__S", None, vec!(Path::new_( vec!("serialize", "Encoder"), None, vec!(box Literal(Path::new_local("__E"))), true))), - ("__E", ast::StaticSize, vec!())) + ("__E", None, vec!())) }, methods: vec!( MethodDef { diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 157b64fb47c..c9f5936a9bb 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -8,174 +8,170 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! - -Some code that abstracts away much of the boilerplate of writing -`deriving` instances for traits. Among other things it manages getting -access to the fields of the 4 different sorts of structs and enum -variants, as well as creating the method and impl ast instances. - -Supported features (fairly exhaustive): - -- Methods taking any number of parameters of any type, and returning - any type, other than vectors, bottom and closures. -- Generating `impl`s for types with type parameters and lifetimes - (e.g. `Option<T>`), the parameters are automatically given the - current trait as a bound. (This includes separate type parameters - and lifetimes for methods.) -- Additional bounds on the type parameters, e.g. the `Ord` instance - requires an explicit `PartialEq` bound at the - moment. (`TraitDef.additional_bounds`) - -Unsupported: FIXME #6257: calling methods on reference fields, -e.g. deriving Eq/Ord/Clone don't work on `struct A(&int)`, -because of how the auto-dereferencing happens. - -The most important thing for implementers is the `Substructure` and -`SubstructureFields` objects. The latter groups 5 possibilities of the -arguments: - -- `Struct`, when `Self` is a struct (including tuple structs, e.g - `struct T(int, char)`). -- `EnumMatching`, when `Self` is an enum and all the arguments are the - same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`) -- `EnumNonMatching` when `Self` is an enum and the arguments are not - the same variant (e.g. `None`, `Some(1)` and `None`). If - `const_nonmatching` is true, this will contain an empty list. -- `StaticEnum` and `StaticStruct` for static methods, where the type - being derived upon is either an enum or struct respectively. (Any - argument with type Self is just grouped among the non-self - arguments.) - -In the first two cases, the values from the corresponding fields in -all the arguments are grouped together. In the `EnumNonMatching` case -this isn't possible (different variants have different fields), so the -fields are grouped by which argument they come from. There are no -fields with values in the static cases, so these are treated entirely -differently. - -The non-static cases have `Option<ident>` in several places associated -with field `expr`s. This represents the name of the field it is -associated with. It is only not `None` when the associated field has -an identifier in the source code. For example, the `x`s in the -following snippet - -```rust -struct A { x : int } - -struct B(int); - -enum C { - C0(int), - C1 { x: int } -} -``` - -The `int`s in `B` and `C0` don't have an identifier, so the -`Option<ident>`s would be `None` for them. - -In the static cases, the structure is summarised, either into the just -spans of the fields or a list of spans and the field idents (for tuple -structs and record structs, respectively), or a list of these, for -enums (one for each variant). For empty struct and empty enum -variants, it is represented as a count of 0. - -# Examples - -The following simplified `PartialEq` is used for in-code examples: - -```rust -trait PartialEq { - fn eq(&self, other: &Self); -} -impl PartialEq for int { - fn eq(&self, other: &int) -> bool { - *self == *other - } -} -``` - -Some examples of the values of `SubstructureFields` follow, using the -above `PartialEq`, `A`, `B` and `C`. - -## Structs - -When generating the `expr` for the `A` impl, the `SubstructureFields` is - -~~~text -Struct(~[FieldInfo { - span: <span of x> - name: Some(<ident of x>), - self_: <expr for &self.x>, - other: ~[<expr for &other.x] - }]) -~~~ - -For the `B` impl, called with `B(a)` and `B(b)`, - -~~~text -Struct(~[FieldInfo { - span: <span of `int`>, - name: None, - <expr for &a> - ~[<expr for &b>] - }]) -~~~ - -## Enums - -When generating the `expr` for a call with `self == C0(a)` and `other -== C0(b)`, the SubstructureFields is - -~~~text -EnumMatching(0, <ast::Variant for C0>, - ~[FieldInfo { - span: <span of int> - name: None, - self_: <expr for &a>, - other: ~[<expr for &b>] - }]) -~~~ - -For `C1 {x}` and `C1 {x}`, - -~~~text -EnumMatching(1, <ast::Variant for C1>, - ~[FieldInfo { - span: <span of x> - name: Some(<ident of x>), - self_: <expr for &self.x>, - other: ~[<expr for &other.x>] - }]) -~~~ - -For `C0(a)` and `C1 {x}` , - -~~~text -EnumNonMatching(~[(0, <ast::Variant for B0>, - ~[(<span of int>, None, <expr for &a>)]), - (1, <ast::Variant for B1>, - ~[(<span of x>, Some(<ident of x>), - <expr for &other.x>)])]) -~~~ - -(and vice versa, but with the order of the outermost list flipped.) - -## Static - -A static method on the above would result in, - -~~~text -StaticStruct(<ast::StructDef of A>, Named(~[(<ident of x>, <span of x>)])) - -StaticStruct(<ast::StructDef of B>, Unnamed(~[<span of x>])) - -StaticEnum(<ast::EnumDef of C>, ~[(<ident of C0>, <span of C0>, Unnamed(~[<span of int>])), - (<ident of C1>, <span of C1>, - Named(~[(<ident of x>, <span of x>)]))]) -~~~ - -*/ +//! Some code that abstracts away much of the boilerplate of writing +//! `deriving` instances for traits. Among other things it manages getting +//! access to the fields of the 4 different sorts of structs and enum +//! variants, as well as creating the method and impl ast instances. +//! +//! Supported features (fairly exhaustive): +//! +//! - Methods taking any number of parameters of any type, and returning +//! any type, other than vectors, bottom and closures. +//! - Generating `impl`s for types with type parameters and lifetimes +//! (e.g. `Option<T>`), the parameters are automatically given the +//! current trait as a bound. (This includes separate type parameters +//! and lifetimes for methods.) +//! - Additional bounds on the type parameters, e.g. the `Ord` instance +//! requires an explicit `PartialEq` bound at the +//! moment. (`TraitDef.additional_bounds`) +//! +//! Unsupported: FIXME #6257: calling methods on reference fields, +//! e.g. deriving Eq/Ord/Clone don't work on `struct A(&int)`, +//! because of how the auto-dereferencing happens. +//! +//! The most important thing for implementers is the `Substructure` and +//! `SubstructureFields` objects. The latter groups 5 possibilities of the +//! arguments: +//! +//! - `Struct`, when `Self` is a struct (including tuple structs, e.g +//! `struct T(int, char)`). +//! - `EnumMatching`, when `Self` is an enum and all the arguments are the +//! same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`) +//! - `EnumNonMatching` when `Self` is an enum and the arguments are not +//! the same variant (e.g. `None`, `Some(1)` and `None`). If +//! `const_nonmatching` is true, this will contain an empty list. +//! - `StaticEnum` and `StaticStruct` for static methods, where the type +//! being derived upon is either an enum or struct respectively. (Any +//! argument with type Self is just grouped among the non-self +//! arguments.) +//! +//! In the first two cases, the values from the corresponding fields in +//! all the arguments are grouped together. In the `EnumNonMatching` case +//! this isn't possible (different variants have different fields), so the +//! fields are grouped by which argument they come from. There are no +//! fields with values in the static cases, so these are treated entirely +//! differently. +//! +//! The non-static cases have `Option<ident>` in several places associated +//! with field `expr`s. This represents the name of the field it is +//! associated with. It is only not `None` when the associated field has +//! an identifier in the source code. For example, the `x`s in the +//! following snippet +//! +//! ```rust +//! struct A { x : int } +//! +//! struct B(int); +//! +//! enum C { +//! C0(int), +//! C1 { x: int } +//! } +//! ``` +//! +//! The `int`s in `B` and `C0` don't have an identifier, so the +//! `Option<ident>`s would be `None` for them. +//! +//! In the static cases, the structure is summarised, either into the just +//! spans of the fields or a list of spans and the field idents (for tuple +//! structs and record structs, respectively), or a list of these, for +//! enums (one for each variant). For empty struct and empty enum +//! variants, it is represented as a count of 0. +//! +//! # Examples +//! +//! The following simplified `PartialEq` is used for in-code examples: +//! +//! ```rust +//! trait PartialEq { +//! fn eq(&self, other: &Self); +//! } +//! impl PartialEq for int { +//! fn eq(&self, other: &int) -> bool { +//! *self == *other +//! } +//! } +//! ``` +//! +//! Some examples of the values of `SubstructureFields` follow, using the +//! above `PartialEq`, `A`, `B` and `C`. +//! +//! ## Structs +//! +//! When generating the `expr` for the `A` impl, the `SubstructureFields` is +//! +//! ~~~text +//! Struct(~[FieldInfo { +//! span: <span of x> +//! name: Some(<ident of x>), +//! self_: <expr for &self.x>, +//! other: ~[<expr for &other.x] +//! }]) +//! ~~~ +//! +//! For the `B` impl, called with `B(a)` and `B(b)`, +//! +//! ~~~text +//! Struct(~[FieldInfo { +//! span: <span of `int`>, +//! name: None, +//! <expr for &a> +//! ~[<expr for &b>] +//! }]) +//! ~~~ +//! +//! ## Enums +//! +//! When generating the `expr` for a call with `self == C0(a)` and `other +//! == C0(b)`, the SubstructureFields is +//! +//! ~~~text +//! EnumMatching(0, <ast::Variant for C0>, +//! ~[FieldInfo { +//! span: <span of int> +//! name: None, +//! self_: <expr for &a>, +//! other: ~[<expr for &b>] +//! }]) +//! ~~~ +//! +//! For `C1 {x}` and `C1 {x}`, +//! +//! ~~~text +//! EnumMatching(1, <ast::Variant for C1>, +//! ~[FieldInfo { +//! span: <span of x> +//! name: Some(<ident of x>), +//! self_: <expr for &self.x>, +//! other: ~[<expr for &other.x>] +//! }]) +//! ~~~ +//! +//! For `C0(a)` and `C1 {x}` , +//! +//! ~~~text +//! EnumNonMatching(~[(0, <ast::Variant for B0>, +//! ~[(<span of int>, None, <expr for &a>)]), +//! (1, <ast::Variant for B1>, +//! ~[(<span of x>, Some(<ident of x>), +//! <expr for &other.x>)])]) +//! ~~~ +//! +//! (and vice versa, but with the order of the outermost list flipped.) +//! +//! ## Static +//! +//! A static method on the above would result in, +//! +//! ~~~text +//! StaticStruct(<ast::StructDef of A>, Named(~[(<ident of x>, <span of x>)])) +//! +//! StaticStruct(<ast::StructDef of B>, Unnamed(~[<span of x>])) +//! +//! StaticEnum(<ast::EnumDef of C>, ~[(<ident of C0>, <span of C0>, Unnamed(~[<span of int>])), +//! (<ident of C1>, <span of C1>, +//! Named(~[(<ident of x>, <span of x>)]))]) +//! ~~~ use std::cell::RefCell; use std::gc::{Gc, GC}; @@ -191,6 +187,7 @@ use codemap; use codemap::Span; use owned_slice::OwnedSlice; use parse::token::InternedString; +use parse::token::special_idents; use self::ty::*; @@ -406,8 +403,8 @@ impl<'a> TraitDef<'a> { cx.typaram(self.span, ty_param.ident, - ty_param.sized, OwnedSlice::from_vec(bounds), + ty_param.unbound.clone(), None) })); let trait_generics = Generics { @@ -617,7 +614,8 @@ impl<'a> MethodDef<'a> { let self_arg = match explicit_self.node { ast::SelfStatic => None, - _ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable)) + // creating fresh self id + _ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable, special_idents::self_)) }; let args = { let args = arg_types.move_iter().map(|(name, ty)| { diff --git a/src/libsyntax/ext/deriving/generic/ty.rs b/src/libsyntax/ext/deriving/generic/ty.rs index 7501b950770..f6a39d7b2e6 100644 --- a/src/libsyntax/ext/deriving/generic/ty.rs +++ b/src/libsyntax/ext/deriving/generic/ty.rs @@ -19,13 +19,16 @@ use ext::base::ExtCtxt; use ext::build::AstBuilder; use codemap::{Span,respan}; use owned_slice::OwnedSlice; +use parse::token::special_idents; use std::gc::Gc; /// The types of pointers pub enum PtrTy<'a> { - Send, // ~ - Borrowed(Option<&'a str>, ast::Mutability), // &['lifetime] [mut] + /// ~ + Send, + /// &'lifetime mut + Borrowed(Option<&'a str>, ast::Mutability), } /// A path, e.g. `::std::option::Option::<int>` (global). Has support @@ -82,12 +85,12 @@ impl<'a> Path<'a> { /// A type. Supports pointers (except for *), Self, and literals pub enum Ty<'a> { Self, - // &/Box/ Ty + /// &/Box/ Ty Ptr(Box<Ty<'a>>, PtrTy<'a>), - // mod::mod::Type<[lifetime], [Params...]>, including a plain type - // parameter, and things like `int` + /// mod::mod::Type<[lifetime], [Params...]>, including a plain type + /// parameter, and things like `int` Literal(Path<'a>), - // includes nil + /// includes unit Tuple(Vec<Ty<'a>> ) } @@ -188,17 +191,18 @@ impl<'a> Ty<'a> { } -fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str, sized: ast::Sized, bounds: &[Path], +fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str, + bounds: &[Path], unbound: Option<ast::TyParamBound>, self_ident: Ident, self_generics: &Generics) -> ast::TyParam { let bounds = bounds.iter().map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); cx.typarambound(path) }).collect(); - cx.typaram(span, cx.ident_of(name), sized, bounds, None) + cx.typaram(span, cx.ident_of(name), bounds, unbound, None) } -fn mk_generics(lifetimes: Vec<ast::Lifetime> , ty_params: Vec<ast::TyParam> ) -> Generics { +fn mk_generics(lifetimes: Vec<ast::Lifetime>, ty_params: Vec<ast::TyParam> ) -> Generics { Generics { lifetimes: lifetimes, ty_params: OwnedSlice::from_vec(ty_params) @@ -208,7 +212,7 @@ fn mk_generics(lifetimes: Vec<ast::Lifetime> , ty_params: Vec<ast::TyParam> ) - /// Lifetimes and bounds on type parameters pub struct LifetimeBounds<'a> { pub lifetimes: Vec<&'a str>, - pub bounds: Vec<(&'a str, ast::Sized, Vec<Path<'a>>)>, + pub bounds: Vec<(&'a str, Option<ast::TyParamBound>, Vec<Path<'a>>)>, } impl<'a> LifetimeBounds<'a> { @@ -228,12 +232,12 @@ impl<'a> LifetimeBounds<'a> { }).collect(); let ty_params = self.bounds.iter().map(|t| { match t { - &(ref name, sized, ref bounds) => { + &(ref name, ref unbound, ref bounds) => { mk_ty_param(cx, span, *name, - sized, bounds.as_slice(), + unbound.clone(), self_ty, self_generics) } @@ -243,22 +247,23 @@ impl<'a> LifetimeBounds<'a> { } } - pub fn get_explicit_self(cx: &ExtCtxt, span: Span, self_ptr: &Option<PtrTy>) -> (Gc<Expr>, ast::ExplicitSelf) { + // this constructs a fresh `self` path, which will match the fresh `self` binding + // created below. let self_path = cx.expr_self(span); match *self_ptr { None => { - (self_path, respan(span, ast::SelfValue)) + (self_path, respan(span, ast::SelfValue(special_idents::self_))) } Some(ref ptr) => { let self_ty = respan( span, match *ptr { - Send => ast::SelfUniq, + Send => ast::SelfUniq(special_idents::self_), Borrowed(ref lt, mutbl) => { let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(s).name)); - ast::SelfRegion(lt, mutbl) + ast::SelfRegion(lt, mutbl, special_idents::self_) } }); let self_expr = cx.expr_deref(span, self_path); diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 77fb013b269..1b3ac47092a 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use ast; use ast::{MetaItem, Item, Expr, MutMutable}; use codemap::Span; use ext::base::ExtCtxt; @@ -30,7 +29,7 @@ pub fn expand_deriving_hash(cx: &mut ExtCtxt, vec!(box Literal(Path::new_local("__S"))), true), LifetimeBounds { lifetimes: Vec::new(), - bounds: vec!(("__S", ast::StaticSize, + bounds: vec!(("__S", None, vec!(Path::new(vec!("std", "hash", "Writer"))))), }, Path::new_local("__S")) diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index f6a15ea917e..34b5f120d6a 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -35,7 +35,7 @@ pub fn expand_deriving_rand(cx: &mut ExtCtxt, generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("R", - ast::StaticSize, + None, vec!( Path::new(vec!("std", "rand", "Rng")) ))) }, explicit_self: None, diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index 8e673ff2465..05b5131d7e4 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -55,8 +55,8 @@ pub fn expand_deriving_show(cx: &mut ExtCtxt, trait_def.expand(cx, mitem, item, push) } -// we construct a format string and then defer to std::fmt, since that -// knows what's up with formatting at so on. +/// We construct a format string and then defer to std::fmt, since that +/// knows what's up with formatting and so on. fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> { // build `<name>`, `<name>({}, {}, ...)` or `<name> { <field>: {}, diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9ef7241ca24..b24cfb85794 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -70,7 +70,7 @@ pub fn expand_env(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(exprs) => exprs }; - let var = match expr_to_str(cx, + let var = match expr_to_string(cx, *exprs.get(0), "expected string literal") { None => return DummyResult::expr(sp), @@ -83,7 +83,7 @@ pub fn expand_env(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) var).as_slice()) } 2 => { - match expr_to_str(cx, *exprs.get(1), "expected string literal") { + match expr_to_string(cx, *exprs.get(1), "expected string literal") { None => return DummyResult::expr(sp), Some((s, _style)) => s } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 752b3a09e65..b7d72ae4deb 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -246,11 +246,11 @@ pub fn expand_expr(e: Gc<ast::Expr>, fld: &mut MacroExpander) -> Gc<ast::Expr> { } } -// Rename loop label and expand its loop body -// -// The renaming procedure for loop is different in the sense that the loop -// body is in a block enclosed by loop head so the renaming of loop label -// must be propagated to the enclosed context. +/// Rename loop label and expand its loop body +/// +/// The renaming procedure for loop is different in the sense that the loop +/// body is in a block enclosed by loop head so the renaming of loop label +/// must be propagated to the enclosed context. fn expand_loop_block(loop_block: P<Block>, opt_ident: Option<Ident>, fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) { @@ -484,6 +484,24 @@ fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander) let marked_tts = mark_tts(tts.as_slice(), fm); expander.expand(fld.cx, it.span, it.ident, marked_tts) } + Some(&LetSyntaxTT(ref expander, span)) => { + if it.ident.name == parse::token::special_idents::invalid.name { + fld.cx.span_err(pth.span, + format!("macro {}! expects an ident argument", + extnamestr.get()).as_slice()); + return SmallVector::zero(); + } + fld.cx.bt_push(ExpnInfo { + call_site: it.span, + callee: NameAndSpan { + name: extnamestr.get().to_string(), + format: MacroBang, + span: span + } + }); + // DON'T mark before expansion: + expander.expand(fld.cx, it.span, it.ident, tts) + } _ => { fld.cx.span_err(it.span, format!("{}! is not legal in item position", @@ -494,8 +512,10 @@ fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander) let items = match expanded.make_def() { Some(MacroDef { name, ext }) => { - // yikes... no idea how to apply the mark to this. I'm afraid - // we're going to have to wait-and-see on this one. + // hidden invariant: this should only be possible as the + // result of expanding a LetSyntaxTT, and thus doesn't + // need to be marked. Not that it could be marked anyway. + // create issue to recommend refactoring here? fld.extsbox.insert(intern(name.as_slice()), ext); if attr::contains_name(it.attrs.as_slice(), "macro_export") { SmallVector::one(it) @@ -914,6 +934,27 @@ impl<'a> Folder for PatIdentRenamer<'a> { } } +// expand a method +fn expand_method(m: &ast::Method, fld: &mut MacroExpander) -> Gc<ast::Method> { + let id = fld.new_id(m.id); + let (rewritten_fn_decl, rewritten_body) + = expand_and_rename_fn_decl_and_block(m.decl,m.body,fld); + + // all of the other standard stuff: + box(GC) ast::Method { + id: id, + ident: fld.fold_ident(m.ident), + attrs: m.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(), + generics: fold_generics(&m.generics, fld), + explicit_self: fld.fold_explicit_self(&m.explicit_self), + fn_style: m.fn_style, + decl: rewritten_fn_decl, + body: rewritten_body, + span: fld.new_span(m.span), + vis: m.vis + } +} + /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the /// PatIdents in its arguments to perform renaming in the FnDecl and /// the block, returning both the new FnDecl and the new Block. @@ -968,6 +1009,10 @@ impl<'a, 'b> Folder for MacroExpander<'a, 'b> { expand_arm(arm, self) } + fn fold_method(&mut self, method: Gc<ast::Method>) -> Gc<ast::Method> { + expand_method(method, self) + } + fn new_span(&mut self, span: Span) -> Span { new_span(self.cx, span) } @@ -1105,7 +1150,7 @@ mod test { use super::{pattern_bindings, expand_crate, contains_macro_escape}; use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer}; use ast; - use ast::{Attribute_, AttrOuter, MetaWord}; + use ast::{Attribute_, AttrOuter, MetaWord, Name}; use attr; use codemap; use codemap::Spanned; @@ -1183,7 +1228,7 @@ mod test { // should fail: let cfg = ::syntax::ext::expand::ExpansionConfig { deriving_hash_type_parameter: false, - crate_name: "test".to_str(), + crate_name: "test".to_string(), }; expand_crate(&sess,cfg,vec!(),vec!(),crate_ast); } @@ -1200,7 +1245,7 @@ mod test { Vec::new(), &sess); let cfg = ::syntax::ext::expand::ExpansionConfig { deriving_hash_type_parameter: false, - crate_name: "test".to_str(), + crate_name: "test".to_string(), }; expand_crate(&sess,cfg,vec!(),vec!(),crate_ast); } @@ -1216,7 +1261,7 @@ mod test { Vec::new(), &sess); let cfg = ::syntax::ext::expand::ExpansionConfig { deriving_hash_type_parameter: false, - crate_name: "test".to_str(), + crate_name: "test".to_string(), }; expand_crate(&sess, cfg, vec!(), vec!(), crate_ast); } @@ -1253,7 +1298,7 @@ mod test { // the cfg argument actually does matter, here... let cfg = ::syntax::ext::expand::ExpansionConfig { deriving_hash_type_parameter: false, - crate_name: "test".to_str(), + crate_name: "test".to_string(), }; expand_crate(&ps,cfg,vec!(),vec!(),crate_ast) } @@ -1272,7 +1317,7 @@ mod test { //} //fn expand_and_resolve_and_pretty_print (crate_str: @str) -> String { //let resolved_ast = expand_and_resolve(crate_str); - //pprust::to_str(&resolved_ast,fake_print_crate,get_ident_interner()) + //pprust::to_string(&resolved_ast,fake_print_crate,get_ident_interner()) //} #[test] fn macro_tokens_should_match(){ @@ -1280,6 +1325,14 @@ mod test { "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_string()); } + // should be able to use a bound identifier as a literal in a macro definition: + #[test] fn self_macro_parsing(){ + expand_crate_str( + "macro_rules! foo ((zz) => (287u;)) + fn f(zz : int) {foo!(zz);}".to_string() + ); + } + // renaming tests expand a crate and then check that the bindings match // the right varrefs. The specification of the test case includes the // text of the crate, and also an array of arrays. Each element in the @@ -1390,6 +1443,32 @@ mod test { // but *shouldn't* bind because it was inserted by a different macro.... // can't write this test case until we have macro-generating macros. + // method arg hygiene + // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1} + #[test] fn method_arg_hygiene(){ + run_renaming_test( + &("macro_rules! inject_x (()=>(x)) + macro_rules! inject_self (()=>(self)) + struct A; + impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }", + vec!(vec!(0),vec!(3)), + true), + 0) + } + + // ooh, got another bite? + // expands to struct A; impl A {fn thingy(&self_1) {self_1;}} + #[test] fn method_arg_hygiene_2(){ + run_renaming_test( + &("struct A; + macro_rules! add_method (($T:ty) => + (impl $T { fn thingy(&self) {self;} })) + add_method!(A)", + vec!(vec!(0)), + true), + 0) + } + // item fn hygiene // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};} #[test] fn issue_9383(){ @@ -1422,6 +1501,28 @@ mod test { 0) } + // macro_rules in method position. Sadly, unimplemented. + #[ignore] #[test] fn macro_in_method_posn(){ + expand_crate_str( + "macro_rules! my_method (() => fn thirteen(&self) -> int {13}) + struct A; + impl A{ my_method!()} + fn f(){A.thirteen;}".to_string()); + } + + // another nested macro + // expands to impl Entries {fn size_hint(&self_1) {self_1;} + #[test] fn item_macro_workaround(){ + run_renaming_test( + &("macro_rules! item { ($i:item) => {$i}} + struct Entries; + macro_rules! iterator_impl { + () => { item!( impl Entries { fn size_hint(&self) { self;}})}} + iterator_impl! { }", + vec!(vec!(0)), true), + 0) + } + // run one of the renaming tests fn run_renaming_test(t: &RenamingTest, test_idx: uint) { let invalid_name = token::special_idents::invalid.name; @@ -1441,27 +1542,36 @@ mod test { assert!((shouldmatch.len() == 0) || (varrefs.len() > *shouldmatch.iter().max().unwrap())); for (idx,varref) in varrefs.iter().enumerate() { + let print_hygiene_debug_info = || { + // good lord, you can't make a path with 0 segments, can you? + let final_varref_ident = match varref.segments.last() { + Some(pathsegment) => pathsegment.identifier, + None => fail!("varref with 0 path segments?") + }; + let varref_name = mtwt::resolve(final_varref_ident); + let varref_idents : Vec<ast::Ident> + = varref.segments.iter().map(|s| s.identifier) + .collect(); + println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name); + let string = token::get_ident(final_varref_ident); + println!("varref's first segment's string: \"{}\"", string.get()); + println!("binding #{}: {}, resolves to {}", + binding_idx, *bindings.get(binding_idx), binding_name); + mtwt::with_sctable(|x| mtwt::display_sctable(x)); + }; if shouldmatch.contains(&idx) { // it should be a path of length 1, and it should // be free-identifier=? or bound-identifier=? to the given binding assert_eq!(varref.segments.len(),1); - let varref_name = mtwt::resolve(varref.segments - .get(0) - .identifier); + let varref_name = mtwt::resolve(varref.segments.get(0).identifier); let varref_marks = mtwt::marksof(varref.segments .get(0) .identifier .ctxt, invalid_name); if !(varref_name==binding_name) { - let varref_idents : Vec<ast::Ident> - = varref.segments.iter().map(|s| - s.identifier) - .collect(); println!("uh oh, should match but doesn't:"); - println!("varref #{}: {}",idx, varref_idents); - println!("binding #{}: {}", binding_idx, *bindings.get(binding_idx)); - mtwt::with_sctable(|x| mtwt::display_sctable(x)); + print_hygiene_debug_info(); } assert_eq!(varref_name,binding_name); if bound_ident_check { @@ -1475,27 +1585,11 @@ mod test { && (varref_name == binding_name); // temp debugging: if fail { - let varref_idents : Vec<ast::Ident> - = varref.segments.iter().map(|s| - s.identifier) - .collect(); println!("failure on test {}",test_idx); println!("text of test case: \"{}\"", teststr); println!(""); println!("uh oh, matches but shouldn't:"); - println!("varref #{}: {}, resolves to {}",idx, varref_idents, - varref_name); - // good lord, you can't make a path with 0 segments, can you? - let string = token::get_ident(varref.segments - .get(0) - .identifier); - println!("varref's first segment's uint: {}, and string: \"{}\"", - varref.segments.get(0).identifier.name, - string.get()); - println!("binding #{}: {}, resolves to {}", - binding_idx, *bindings.get(binding_idx), - binding_name); - mtwt::with_sctable(|x| mtwt::display_sctable(x)); + print_hygiene_debug_info(); } assert!(!fail); } @@ -1504,7 +1598,7 @@ mod test { } #[test] fn fmt_in_macro_used_inside_module_macro() { - let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_str())) + let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string())) macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}})) foo_module!() ".to_string(); @@ -1571,12 +1665,12 @@ foo_module!() let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); let int_ident = token::str_to_ident("int"); - let renames = vec!((x_ident,16)); + let renames = vec!((x_ident,Name(16))); let mut renamer = IdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); let idents = crate_idents(&renamed_crate); let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect(); - assert_eq!(resolved,vec!(f_ident.name,16,int_ident.name,16,16,16)); + assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16))); } // test the PatIdentRenamer; only PatIdents get renamed @@ -1586,13 +1680,13 @@ foo_module!() let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); let int_ident = token::str_to_ident("int"); - let renames = vec!((x_ident,16)); + let renames = vec!((x_ident,Name(16))); let mut renamer = PatIdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); let idents = crate_idents(&renamed_crate); let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect(); let x_name = x_ident.name; - assert_eq!(resolved,vec!(f_ident.name,16,int_ident.name,16,x_name,x_name)); + assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name)); } diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index f39e50ad131..786fd953f89 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -37,24 +37,24 @@ struct Context<'a, 'b> { ecx: &'a mut ExtCtxt<'b>, fmtsp: Span, - // Parsed argument expressions and the types that we've found so far for - // them. + /// Parsed argument expressions and the types that we've found so far for + /// them. args: Vec<Gc<ast::Expr>>, arg_types: Vec<Option<ArgumentType>>, - // Parsed named expressions and the types that we've found for them so far. - // Note that we keep a side-array of the ordering of the named arguments - // found to be sure that we can translate them in the same order that they - // were declared in. + /// Parsed named expressions and the types that we've found for them so far. + /// Note that we keep a side-array of the ordering of the named arguments + /// found to be sure that we can translate them in the same order that they + /// were declared in. names: HashMap<String, Gc<ast::Expr>>, name_types: HashMap<String, ArgumentType>, name_ordering: Vec<String>, - // Collection of the compiled `rt::Piece` structures + /// Collection of the compiled `rt::Piece` structures pieces: Vec<Gc<ast::Expr>>, name_positions: HashMap<String, uint>, method_statics: Vec<Gc<ast::Item>>, - // Updated as arguments are consumed or methods are entered + /// Updated as arguments are consumed or methods are entered nest_level: uint, next_arg: uint, } @@ -126,7 +126,7 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, allow_method: bool, _ => { ecx.span_err(p.span, format!("expected ident for named argument, but found `{}`", - p.this_token_to_str()).as_slice()); + p.this_token_to_string()).as_slice()); return (invocation, None); } }; @@ -690,7 +690,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, fmtsp: sp, }; cx.fmtsp = efmt.span; - let fmt = match expr_to_str(cx.ecx, + let fmt = match expr_to_string(cx.ecx, efmt, "format argument must be a string literal.") { Some((fmt, _)) => fmt, diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index 486d060da77..1f4d087abd0 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -21,7 +21,7 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, -> Box<base::MacResult> { cx.print_backtrace(); - println!("{}", print::pprust::tt_to_str(&ast::TTDelim( + println!("{}", print::pprust::tt_to_string(&ast::TTDelim( Rc::new(tt.iter().map(|x| (*x).clone()).collect())))); // any so that `log_syntax` can be invoked as an expression and item. diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 18466e381a5..2c94db52967 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -21,16 +21,16 @@ use std::cell::RefCell; use std::rc::Rc; use std::collections::HashMap; -// the SCTable contains a table of SyntaxContext_'s. It -// represents a flattened tree structure, to avoid having -// managed pointers everywhere (that caused an ICE). -// the mark_memo and rename_memo fields are side-tables -// that ensure that adding the same mark to the same context -// gives you back the same context as before. This shouldn't -// change the semantics--everything here is immutable--but -// it should cut down on memory use *a lot*; applying a mark -// to a tree containing 50 identifiers would otherwise generate -// 50 new contexts +/// The SCTable contains a table of SyntaxContext_'s. It +/// represents a flattened tree structure, to avoid having +/// managed pointers everywhere (that caused an ICE). +/// the mark_memo and rename_memo fields are side-tables +/// that ensure that adding the same mark to the same context +/// gives you back the same context as before. This shouldn't +/// change the semantics--everything here is immutable--but +/// it should cut down on memory use *a lot*; applying a mark +/// to a tree containing 50 identifiers would otherwise generate +/// 50 new contexts pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, mark_memo: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, @@ -41,16 +41,16 @@ pub struct SCTable { pub enum SyntaxContext_ { EmptyCtxt, Mark (Mrk,SyntaxContext), - // flattening the name and syntaxcontext into the rename... - // HIDDEN INVARIANTS: - // 1) the first name in a Rename node - // can only be a programmer-supplied name. - // 2) Every Rename node with a given Name in the - // "to" slot must have the same name and context - // in the "from" slot. In essence, they're all - // pointers to a single "rename" event node. + /// flattening the name and syntaxcontext into the rename... + /// HIDDEN INVARIANTS: + /// 1) the first name in a Rename node + /// can only be a programmer-supplied name. + /// 2) Every Rename node with a given Name in the + /// "to" slot must have the same name and context + /// in the "from" slot. In essence, they're all + /// pointers to a single "rename" event node. Rename (Ident,Name,SyntaxContext), - // actually, IllegalCtxt may not be necessary. + /// actually, IllegalCtxt may not be necessary. IllegalCtxt } @@ -62,7 +62,7 @@ pub fn apply_mark(m: Mrk, ctxt: SyntaxContext) -> SyntaxContext { with_sctable(|table| apply_mark_internal(m, ctxt, table)) } -// Extend a syntax context with a given mark and sctable (explicit memoization) +/// Extend a syntax context with a given mark and sctable (explicit memoization) fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (ctxt, m); let new_ctxt = |_: &(SyntaxContext, Mrk)| @@ -77,13 +77,13 @@ pub fn apply_rename(id: Ident, to:Name, with_sctable(|table| apply_rename_internal(id, to, ctxt, table)) } -// Extend a syntax context with a given rename and sctable (explicit memoization) +/// Extend a syntax context with a given rename and sctable (explicit memoization) fn apply_rename_internal(id: Ident, to: Name, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext { - let key = (ctxt,id,to); - let new_ctxt = |_: &(SyntaxContext, Ident, Mrk)| + let key = (ctxt, id, to); + let new_ctxt = |_: &(SyntaxContext, Ident, Name)| idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt)); *table.rename_memo.borrow_mut().find_or_insert_with(key, new_ctxt) @@ -141,8 +141,8 @@ pub fn clear_tables() { with_resolve_table_mut(|table| *table = HashMap::new()); } -// Add a value to the end of a vec, return its index -fn idx_push<T>(vec: &mut Vec<T> , val: T) -> u32 { +/// Add a value to the end of a vec, return its index +fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 { vec.push(val); (vec.len() - 1) as u32 } @@ -173,8 +173,8 @@ fn with_resolve_table_mut<T>(op: |&mut ResolveTable| -> T) -> T { } } -// Resolve a syntax object to a name, per MTWT. -// adding memoization to resolve 500+ seconds in resolve for librustc (!) +/// Resolve a syntax object to a name, per MTWT. +/// adding memoization to resolve 500+ seconds in resolve for librustc (!) fn resolve_internal(id: Ident, table: &SCTable, resolve_table: &mut ResolveTable) -> Name { @@ -264,8 +264,8 @@ pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { }) } -// Push a name... unless it matches the one on top, in which -// case pop and discard (so two of the same marks cancel) +/// Push a name... unless it matches the one on top, in which +/// case pop and discard (so two of the same marks cancel) fn xor_push(marks: &mut Vec<Mrk>, mark: Mrk) { if (marks.len() > 0) && (*marks.last().unwrap() == mark) { marks.pop().unwrap(); @@ -301,8 +301,8 @@ mod tests { assert_eq!(s.clone(), vec!(14)); } - fn id(n: Name, s: SyntaxContext) -> Ident { - Ident {name: n, ctxt: s} + fn id(n: u32, s: SyntaxContext) -> Ident { + Ident {name: Name(n), ctxt: s} } // because of the SCTable, I now need a tidy way of @@ -349,12 +349,12 @@ mod tests { fn test_unfold_refold(){ let mut t = new_sctable_internal(); - let test_sc = vec!(M(3),R(id(101,0),14),M(9)); + let test_sc = vec!(M(3),R(id(101,0),Name(14)),M(9)); assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); assert!(*table.get(2) == Mark(9,0)); - assert!(*table.get(3) == Rename(id(101,0),14,2)); + assert!(*table.get(3) == Rename(id(101,0),Name(14),2)); assert!(*table.get(4) == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); @@ -381,8 +381,8 @@ mod tests { #[test] fn test_marksof () { - let stopname = 242; - let name1 = 243; + let stopname = Name(242); + let name1 = Name(243); let mut t = new_sctable_internal(); assert_eq!(marksof_internal (EMPTY_CTXT,stopname,&t),Vec::new()); // FIXME #5074: ANF'd to dodge nested calls @@ -396,16 +396,16 @@ mod tests { assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), - R(id(name1, + R(id(name1.uint() as u32, apply_mark_internal (4, EMPTY_CTXT,&mut t)), - 100101102), + Name(100101102)), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); assert_eq! (marksof_internal (ans, stopname, &t), vec!(9,14));} // rename where stop does match { let name1sc = apply_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), - R(id(name1, name1sc), + R(id(name1.uint() as u32, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); @@ -419,55 +419,55 @@ mod tests { let mut t = new_sctable_internal(); let mut rt = HashMap::new(); // - ctxt is MT - assert_eq!(resolve_internal(id(a,EMPTY_CTXT),&mut t, &mut rt),a); + assert_eq!(resolve_internal(id(a,EMPTY_CTXT),&mut t, &mut rt),Name(a)); // - simple ignored marks { let sc = unfold_marks(vec!(1,2,3),EMPTY_CTXT,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),Name(a));} // - orthogonal rename where names don't match - { let sc = unfold_test_sc(vec!(R(id(50,EMPTY_CTXT),51),M(12)),EMPTY_CTXT,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),a);} + { let sc = unfold_test_sc(vec!(R(id(50,EMPTY_CTXT),Name(51)),M(12)),EMPTY_CTXT,&mut t); + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),Name(a));} // - rename where names do match, but marks don't { let sc1 = apply_mark_internal(1,EMPTY_CTXT,&mut t); - let sc = unfold_test_sc(vec!(R(id(a,sc1),50), + let sc = unfold_test_sc(vec!(R(id(a,sc1),Name(50)), M(1), M(2)), EMPTY_CTXT,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), a);} + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), Name(a));} // - rename where names and marks match { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); - let sc = unfold_test_sc(vec!(R(id(a,sc1),50),M(1),M(2)),EMPTY_CTXT,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } + let sc = unfold_test_sc(vec!(R(id(a,sc1),Name(50)),M(1),M(2)),EMPTY_CTXT,&mut t); + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), Name(50)); } // - rename where names and marks match by literal sharing { let sc1 = unfold_test_sc(vec!(M(1),M(2)),EMPTY_CTXT,&mut t); - let sc = unfold_test_sc(vec!(R(id(a,sc1),50)),sc1,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 50); } + let sc = unfold_test_sc(vec!(R(id(a,sc1),Name(50))),sc1,&mut t); + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), Name(50)); } // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: println!("about to run bad test"); - { let sc = unfold_test_sc(vec!(R(id(a,EMPTY_CTXT),50), - R(id(a,EMPTY_CTXT),51)), + { let sc = unfold_test_sc(vec!(R(id(a,EMPTY_CTXT),Name(50)), + R(id(a,EMPTY_CTXT),Name(51))), EMPTY_CTXT,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), 51); } + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt), Name(51)); } // the simplest double-rename: - { let a_to_a50 = apply_rename_internal(id(a,EMPTY_CTXT),50,EMPTY_CTXT,&mut t); - let a50_to_a51 = apply_rename_internal(id(a,a_to_a50),51,a_to_a50,&mut t); - assert_eq!(resolve_internal(id(a,a50_to_a51),&mut t, &mut rt),51); + { let a_to_a50 = apply_rename_internal(id(a,EMPTY_CTXT),Name(50),EMPTY_CTXT,&mut t); + let a50_to_a51 = apply_rename_internal(id(a,a_to_a50),Name(51),a_to_a50,&mut t); + assert_eq!(resolve_internal(id(a,a50_to_a51),&mut t, &mut rt),Name(51)); // mark on the outside doesn't stop rename: let sc = apply_mark_internal(9,a50_to_a51,&mut t); - assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),51); + assert_eq!(resolve_internal(id(a,sc),&mut t, &mut rt),Name(51)); // but mark on the inside does: - let a50_to_a51_b = unfold_test_sc(vec!(R(id(a,a_to_a50),51), + let a50_to_a51_b = unfold_test_sc(vec!(R(id(a,a_to_a50),Name(51)), M(9)), a_to_a50, &mut t); - assert_eq!(resolve_internal(id(a,a50_to_a51_b),&mut t, &mut rt),50);} + assert_eq!(resolve_internal(id(a,a50_to_a51_b),&mut t, &mut rt),Name(50));} } #[test] fn mtwt_resolve_test(){ let a = 40; - assert_eq!(resolve(id(a,EMPTY_CTXT)),a); + assert_eq!(resolve(id(a,EMPTY_CTXT)),Name(a)); } @@ -496,10 +496,10 @@ mod tests { #[test] fn new_resolves_test() { - let renames = vec!((Ident{name:23,ctxt:EMPTY_CTXT},24), - (Ident{name:29,ctxt:EMPTY_CTXT},29)); + let renames = vec!((Ident{name:Name(23),ctxt:EMPTY_CTXT},Name(24)), + (Ident{name:Name(29),ctxt:EMPTY_CTXT},Name(29))); let new_ctxt1 = apply_renames(&renames,EMPTY_CTXT); - assert_eq!(resolve(Ident{name:23,ctxt:new_ctxt1}),24); - assert_eq!(resolve(Ident{name:29,ctxt:new_ctxt1}),29); + assert_eq!(resolve(Ident{name:Name(23),ctxt:new_ctxt1}),Name(24)); + assert_eq!(resolve(Ident{name:Name(29),ctxt:new_ctxt1}),Name(29)); } } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 7b24b97d5da..696d62838ba 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -128,13 +128,13 @@ pub mod rt { } } - impl_to_source!(ast::Ty, ty_to_str) - impl_to_source!(ast::Block, block_to_str) - impl_to_source!(ast::Arg, arg_to_str) - impl_to_source!(Generics, generics_to_str) - impl_to_source!(Gc<ast::Item>, item_to_str) - impl_to_source!(Gc<ast::Expr>, expr_to_str) - impl_to_source!(Gc<ast::Pat>, pat_to_str) + impl_to_source!(ast::Ty, ty_to_string) + impl_to_source!(ast::Block, block_to_string) + impl_to_source!(ast::Arg, arg_to_string) + impl_to_source!(Generics, generics_to_string) + impl_to_source!(Gc<ast::Item>, item_to_string) + impl_to_source!(Gc<ast::Expr>, expr_to_string) + impl_to_source!(Gc<ast::Pat>, pat_to_string) impl_to_source_slice!(ast::Ty, ", ") impl_to_source_slice!(Gc<ast::Item>, "\n\n") @@ -142,7 +142,7 @@ pub mod rt { fn to_source(&self) -> String { let lit = dummy_spanned(ast::LitStr( token::intern_and_get_ident(*self), ast::CookedStr)); - pprust::lit_to_str(&lit) + pprust::lit_to_string(&lit) } } @@ -155,14 +155,14 @@ pub mod rt { impl ToSource for bool { fn to_source(&self) -> String { let lit = dummy_spanned(ast::LitBool(*self)); - pprust::lit_to_str(&lit) + pprust::lit_to_string(&lit) } } impl ToSource for char { fn to_source(&self) -> String { let lit = dummy_spanned(ast::LitChar(*self)); - pprust::lit_to_str(&lit) + pprust::lit_to_string(&lit) } } @@ -171,7 +171,7 @@ pub mod rt { impl ToSource for $t { fn to_source(&self) -> String { let lit = dummy_spanned(ast::LitInt(*self as i64, ast::$tag)); - pprust::lit_to_str(&lit) + pprust::lit_to_string(&lit) } } ); @@ -179,7 +179,7 @@ pub mod rt { impl ToSource for $t { fn to_source(&self) -> String { let lit = dummy_spanned(ast::LitUint(*self as u64, ast::$tag)); - pprust::lit_to_str(&lit) + pprust::lit_to_string(&lit) } } ); @@ -363,6 +363,15 @@ fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> Gc<ast::Expr> { vec!(e_str)) } +// Lift a name to the expr that evaluates to that name +fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> Gc<ast::Expr> { + let e_str = cx.expr_str(sp, token::get_ident(ident)); + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext("ext_cx")), + id_ext("name_of"), + vec!(e_str)) +} + fn mk_ast_path(cx: &ExtCtxt, sp: Span, name: &str) -> Gc<ast::Expr> { let idents = vec!(id_ext("syntax"), id_ext("ast"), id_ext(name)); cx.expr_path(cx.path_global(sp, idents)) @@ -401,68 +410,37 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> Gc<ast::Expr> { } LIT_BYTE(i) => { - let e_byte = cx.expr_lit(sp, ast::LitByte(i)); + let e_byte = mk_name(cx, sp, i.ident()); return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_BYTE"), vec!(e_byte)); } LIT_CHAR(i) => { - let e_char = cx.expr_lit(sp, ast::LitChar(i)); + let e_char = mk_name(cx, sp, i.ident()); return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_CHAR"), vec!(e_char)); } - LIT_INT(i, ity) => { - let s_ity = match ity { - ast::TyI => "TyI", - ast::TyI8 => "TyI8", - ast::TyI16 => "TyI16", - ast::TyI32 => "TyI32", - ast::TyI64 => "TyI64" - }; - let e_ity = mk_ast_path(cx, sp, s_ity); - let e_i64 = cx.expr_lit(sp, ast::LitInt(i, ast::TyI64)); - return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_INT"), vec!(e_i64, e_ity)); + LIT_INTEGER(i) => { + let e_int = mk_name(cx, sp, i.ident()); + return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_INTEGER"), vec!(e_int)); } - LIT_UINT(u, uty) => { - let s_uty = match uty { - ast::TyU => "TyU", - ast::TyU8 => "TyU8", - ast::TyU16 => "TyU16", - ast::TyU32 => "TyU32", - ast::TyU64 => "TyU64" - }; - let e_uty = mk_ast_path(cx, sp, s_uty); - let e_u64 = cx.expr_lit(sp, ast::LitUint(u, ast::TyU64)); - return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_UINT"), vec!(e_u64, e_uty)); - } - - LIT_INT_UNSUFFIXED(i) => { - let e_i64 = cx.expr_lit(sp, ast::LitInt(i, ast::TyI64)); - return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_INT_UNSUFFIXED"), vec!(e_i64)); - } - - LIT_FLOAT(fident, fty) => { - let s_fty = match fty { - ast::TyF32 => "TyF32", - ast::TyF64 => "TyF64", - }; - let e_fty = mk_ast_path(cx, sp, s_fty); - let e_fident = mk_ident(cx, sp, fident); - return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_FLOAT"), vec!(e_fident, e_fty)); + LIT_FLOAT(fident) => { + let e_fident = mk_name(cx, sp, fident.ident()); + return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_FLOAT"), vec!(e_fident)); } LIT_STR(ident) => { return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_STR"), - vec!(mk_ident(cx, sp, ident))); + vec!(mk_name(cx, sp, ident.ident()))); } LIT_STR_RAW(ident, n) => { return cx.expr_call(sp, mk_token_path(cx, sp, "LIT_STR_RAW"), - vec!(mk_ident(cx, sp, ident), cx.expr_uint(sp, n))); + vec!(mk_name(cx, sp, ident.ident()), cx.expr_uint(sp, n))); } IDENT(ident, b) => { @@ -480,7 +458,7 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> Gc<ast::Expr> { DOC_COMMENT(ident) => { return cx.expr_call(sp, mk_token_path(cx, sp, "DOC_COMMENT"), - vec!(mk_ident(cx, sp, ident))); + vec!(mk_name(cx, sp, ident.ident()))); } INTERPOLATED(_) => fail!("quote! with interpolated token"), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 915fc16c156..5ac9dc86fce 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -28,7 +28,7 @@ use std::str; // the column/row/filename of the expression, or they include // a given file into the current one. -/* line!(): expands to the current line number */ +/// line!(): expands to the current line number pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult> { base::check_zero_tts(cx, sp, tts, "line!"); @@ -49,9 +49,9 @@ pub fn expand_col(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) base::MacExpr::new(cx.expr_uint(topmost.call_site, loc.col.to_uint())) } -/* file!(): expands to the current filename */ -/* The filemap (`loc.file`) contains a bunch more information we could spit - * out if we wanted. */ +/// file!(): expands to the current filename */ +/// The filemap (`loc.file`) contains a bunch more information we could spit +/// out if we wanted. pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult> { base::check_zero_tts(cx, sp, tts, "file!"); @@ -64,7 +64,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult> { - let s = pprust::tts_to_str(tts); + let s = pprust::tts_to_string(tts); base::MacExpr::new(cx.expr_str(sp, token::intern_and_get_ident(s.as_slice()))) } @@ -82,9 +82,9 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) token::intern_and_get_ident(string.as_slice()))) } -// include! : parse the given file as an expr -// This is generally a bad idea because it's going to behave -// unhygienically. +/// include! : parse the given file as an expr +/// This is generally a bad idea because it's going to behave +/// unhygienically. pub fn expand_include(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult> { let file = match get_single_str_from_tts(cx, sp, tts, "include!") { @@ -126,7 +126,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(src) => { // Add this input file to the code map to make it available as // dependency information - let filename = file.display().to_str(); + let filename = file.display().to_string(); let interned = token::intern_and_get_ident(src); cx.codemap().new_filemap(filename, src.to_string()); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 86fbc8cec2a..bdf1f6eb600 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -8,7 +8,72 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Earley-like parser for macros. +//! This is an Earley-like parser, without support for in-grammar nonterminals, +//! only by calling out to the main rust parser for named nonterminals (which it +//! commits to fully when it hits one in a grammar). This means that there are no +//! completer or predictor rules, and therefore no need to store one column per +//! token: instead, there's a set of current Earley items and a set of next +//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in +//! pathological cases, is worse than traditional Earley parsing, but it's an +//! easier fit for Macro-by-Example-style rules, and I think the overhead is +//! lower. (In order to prevent the pathological case, we'd need to lazily +//! construct the resulting `NamedMatch`es at the very end. It'd be a pain, +//! and require more memory to keep around old items, but it would also save +//! overhead) +//! +//! Quick intro to how the parser works: +//! +//! A 'position' is a dot in the middle of a matcher, usually represented as a +//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. +//! +//! The parser walks through the input a character at a time, maintaining a list +//! of items consistent with the current position in the input string: `cur_eis`. +//! +//! As it processes them, it fills up `eof_eis` with items that would be valid if +//! the macro invocation is now over, `bb_eis` with items that are waiting on +//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting +//! on the a particular token. Most of the logic concerns moving the · through the +//! repetitions indicated by Kleene stars. It only advances or calls out to the +//! real Rust parser when no `cur_eis` items remain +//! +//! Example: Start parsing `a a a a b` against [· a $( a )* a b]. +//! +//! Remaining input: `a a a a b` +//! next_eis: [· a $( a )* a b] +//! +//! - - - Advance over an `a`. - - - +//! +//! Remaining input: `a a a b` +//! cur: [a · $( a )* a b] +//! Descend/Skip (first item). +//! next: [a $( · a )* a b] [a $( a )* · a b]. +//! +//! - - - Advance over an `a`. - - - +//! +//! Remaining input: `a a b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] +//! +//! - - - Advance over an `a`. - - - (this looks exactly like the last step) +//! +//! Remaining input: `a b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] +//! +//! - - - Advance over an `a`. - - - (this looks exactly like the last step) +//! +//! Remaining input: `b` +//! cur: [a $( a · )* a b] next: [a $( a )* a · b] +//! Finish/Repeat (first item) +//! next: [a $( a )* · a b] [a $( · a )* a b] +//! +//! - - - Advance over a `b`. - - - +//! +//! Remaining input: `` +//! eof: [a $( a )* a b ·] + use ast; use ast::{Matcher, MatchTok, MatchSeq, MatchNonterminal, Ident}; @@ -25,75 +90,6 @@ use std::rc::Rc; use std::gc::GC; use std::collections::HashMap; -/* This is an Earley-like parser, without support for in-grammar nonterminals, -only by calling out to the main rust parser for named nonterminals (which it -commits to fully when it hits one in a grammar). This means that there are no -completer or predictor rules, and therefore no need to store one column per -token: instead, there's a set of current Earley items and a set of next -ones. Instead of NTs, we have a special case for Kleene star. The big-O, in -pathological cases, is worse than traditional Earley parsing, but it's an -easier fit for Macro-by-Example-style rules, and I think the overhead is -lower. (In order to prevent the pathological case, we'd need to lazily -construct the resulting `NamedMatch`es at the very end. It'd be a pain, -and require more memory to keep around old items, but it would also save -overhead)*/ - -/* Quick intro to how the parser works: - -A 'position' is a dot in the middle of a matcher, usually represented as a -dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. - -The parser walks through the input a character at a time, maintaining a list -of items consistent with the current position in the input string: `cur_eis`. - -As it processes them, it fills up `eof_eis` with items that would be valid if -the macro invocation is now over, `bb_eis` with items that are waiting on -a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting -on the a particular token. Most of the logic concerns moving the · through the -repetitions indicated by Kleene stars. It only advances or calls out to the -real Rust parser when no `cur_eis` items remain - -Example: Start parsing `a a a a b` against [· a $( a )* a b]. - -Remaining input: `a a a a b` -next_eis: [· a $( a )* a b] - -- - - Advance over an `a`. - - - - -Remaining input: `a a a b` -cur: [a · $( a )* a b] -Descend/Skip (first item). -next: [a $( · a )* a b] [a $( a )* · a b]. - -- - - Advance over an `a`. - - - - -Remaining input: `a a b` -cur: [a $( a · )* a b] next: [a $( a )* a · b] -Finish/Repeat (first item) -next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] - -- - - Advance over an `a`. - - - (this looks exactly like the last step) - -Remaining input: `a b` -cur: [a $( a · )* a b] next: [a $( a )* a · b] -Finish/Repeat (first item) -next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] - -- - - Advance over an `a`. - - - (this looks exactly like the last step) - -Remaining input: `b` -cur: [a $( a · )* a b] next: [a $( a )* a · b] -Finish/Repeat (first item) -next: [a $( a )* · a b] [a $( · a )* a b] - -- - - Advance over a `b`. - - - - -Remaining input: `` -eof: [a $( a )* a b ·] - - */ - - /* to avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body. */ @@ -147,24 +143,24 @@ pub fn initial_matcher_pos(ms: Vec<Matcher> , sep: Option<Token>, lo: BytePos) } } -// NamedMatch is a pattern-match result for a single ast::MatchNonterminal: -// so it is associated with a single ident in a parse, and all -// MatchedNonterminal's in the NamedMatch have the same nonterminal type -// (expr, item, etc). All the leaves in a single NamedMatch correspond to a -// single matcher_nonterminal in the ast::Matcher that produced it. -// -// It should probably be renamed, it has more or less exact correspondence to -// ast::match nodes, and the in-memory structure of a particular NamedMatch -// represents the match that occurred when a particular subset of an -// ast::match -- those ast::Matcher nodes leading to a single -// MatchNonterminal -- was applied to a particular token tree. -// -// The width of each MatchedSeq in the NamedMatch, and the identity of the -// MatchedNonterminal's, will depend on the token tree it was applied to: each -// MatchedSeq corresponds to a single MatchSeq in the originating -// ast::Matcher. The depth of the NamedMatch structure will therefore depend -// only on the nesting depth of ast::MatchSeq's in the originating -// ast::Matcher it was derived from. +/// NamedMatch is a pattern-match result for a single ast::MatchNonterminal: +/// so it is associated with a single ident in a parse, and all +/// MatchedNonterminal's in the NamedMatch have the same nonterminal type +/// (expr, item, etc). All the leaves in a single NamedMatch correspond to a +/// single matcher_nonterminal in the ast::Matcher that produced it. +/// +/// It should probably be renamed, it has more or less exact correspondence to +/// ast::match nodes, and the in-memory structure of a particular NamedMatch +/// represents the match that occurred when a particular subset of an +/// ast::match -- those ast::Matcher nodes leading to a single +/// MatchNonterminal -- was applied to a particular token tree. +/// +/// The width of each MatchedSeq in the NamedMatch, and the identity of the +/// MatchedNonterminal's, will depend on the token tree it was applied to: each +/// MatchedSeq corresponds to a single MatchSeq in the originating +/// ast::Matcher. The depth of the NamedMatch structure will therefore depend +/// only on the nesting depth of ast::MatchSeq's in the originating +/// ast::Matcher it was derived from. pub enum NamedMatch { MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span), @@ -224,7 +220,8 @@ pub fn parse_or_else(sess: &ParseSess, } } -// perform a token equality check, ignoring syntax context (that is, an unhygienic comparison) +/// Perform a token equality check, ignoring syntax context (that is, an +/// unhygienic comparison) pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool { match (t1,t2) { (&token::IDENT(id1,_),&token::IDENT(id2,_)) @@ -354,8 +351,7 @@ pub fn parse(sess: &ParseSess, MatchNonterminal(_,_,_) => { bb_eis.push(ei) } MatchTok(ref t) => { let mut ei_t = ei.clone(); - //if (token_name_eq(t,&tok)) { - if token::mtwt_token_eq(t,&tok) { + if token_name_eq(t,&tok) { ei_t.idx += 1; next_eis.push(ei_t); } @@ -395,7 +391,7 @@ pub fn parse(sess: &ParseSess, nts, next_eis.len()).to_string()); } else if bb_eis.len() == 0u && next_eis.len() == 0u { return Failure(sp, format!("no rules expected the token `{}`", - token::to_str(&tok)).to_string()); + token::to_string(&tok)).to_string()); } else if next_eis.len() > 0u { /* Now process the next token */ while next_eis.len() > 0u { @@ -442,7 +438,7 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { "ident" => match p.token { token::IDENT(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { - let token_str = token::to_str(&p.token); + let token_str = token::to_string(&p.token); p.fatal((format!("expected ident, found {}", token_str.as_slice())).as_slice()) } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 72c578b8769..249e9305150 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -48,7 +48,7 @@ impl<'a> ParserAnyMacro<'a> { parser.bump() } if parser.token != EOF { - let token_str = parser.this_token_to_str(); + let token_str = parser.this_token_to_string(); let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); @@ -119,7 +119,7 @@ impl MacResult for MacroRulesDefiner { } } -// Given `lhses` and `rhses`, this is the new macro we create +/// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension(cx: &ExtCtxt, sp: Span, name: Ident, @@ -131,7 +131,7 @@ fn generic_extension(cx: &ExtCtxt, println!("{}! {} {} {}", token::get_ident(name), "{", - print::pprust::tt_to_str(&TTDelim(Rc::new(arg.iter() + print::pprust::tt_to_string(&TTDelim(Rc::new(arg.iter() .map(|x| (*x).clone()) .collect()))), "}"); @@ -193,9 +193,9 @@ fn generic_extension(cx: &ExtCtxt, cx.span_fatal(best_fail_spot, best_fail_msg.as_slice()); } -// this procedure performs the expansion of the -// macro_rules! macro. It parses the RHS and adds -// an extension to the current context. +/// This procedure performs the expansion of the +/// macro_rules! macro. It parses the RHS and adds +/// an extension to the current context. pub fn add_new_extension(cx: &mut ExtCtxt, sp: Span, name: Ident, @@ -254,7 +254,7 @@ pub fn add_new_extension(cx: &mut ExtCtxt, box MacroRulesDefiner { def: RefCell::new(Some(MacroDef { - name: token::get_ident(name).to_str(), + name: token::get_ident(name).to_string(), ext: NormalTT(exp, Some(sp)) })) } as Box<MacResult> diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index c0c066fe466..726a7315f69 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -32,7 +32,7 @@ struct TtFrame { #[deriving(Clone)] pub struct TtReader<'a> { pub sp_diag: &'a SpanHandler, - // the unzipped tree: + /// the unzipped tree: stack: Vec<TtFrame>, /* for MBE-style macro transcription */ interpolations: HashMap<Ident, Rc<NamedMatch>>, @@ -43,9 +43,9 @@ pub struct TtReader<'a> { pub cur_span: Span, } -/** This can do Macro-By-Example transcription. On the other hand, if - * `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and - * should) be none. */ +/// This can do Macro-By-Example transcription. On the other hand, if +/// `src` contains no `TTSeq`s and `TTNonterminal`s, `interp` can (and +/// should) be none. pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler, interp: Option<HashMap<Ident, Rc<NamedMatch>>>, src: Vec<ast::TokenTree> ) @@ -138,8 +138,8 @@ fn lockstep_iter_size(t: &TokenTree, r: &TtReader) -> LockstepIterSize { } } -// return the next token from the TtReader. -// EFFECT: advances the reader's token field +/// Return the next token from the TtReader. +/// EFFECT: advances the reader's token field pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { // FIXME(pcwalton): Bad copy? let ret_val = TokenAndSpan { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 04e6612daf1..bcdf920e5dd 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -334,9 +334,9 @@ pub trait Folder { fn fold_explicit_self_(&mut self, es: &ExplicitSelf_) -> ExplicitSelf_ { match *es { - SelfStatic | SelfValue | SelfUniq => *es, - SelfRegion(ref lifetime, m) => { - SelfRegion(fold_opt_lifetime(lifetime, self), m) + SelfStatic | SelfValue(_) | SelfUniq(_) => *es, + SelfRegion(ref lifetime, m, id) => { + SelfRegion(fold_opt_lifetime(lifetime, self), m, id) } } } @@ -491,8 +491,8 @@ pub fn fold_ty_param<T: Folder>(tp: &TyParam, fld: &mut T) -> TyParam { TyParam { ident: tp.ident, id: id, - sized: tp.sized, bounds: tp.bounds.map(|x| fold_ty_param_bound(x, fld)), + unbound: tp.unbound.as_ref().map(|x| fold_ty_param_bound(x, fld)), default: tp.default.map(|x| fld.fold_ty(x)), span: tp.span } @@ -666,7 +666,7 @@ pub fn noop_fold_item_underscore<T: Folder>(i: &Item_, folder: &mut T) -> Item_ methods.iter().map(|x| folder.fold_method(*x)).collect() ) } - ItemTrait(ref generics, ref sized, ref traits, ref methods) => { + ItemTrait(ref generics, ref unbound, ref traits, ref methods) => { let methods = methods.iter().map(|method| { match *method { Required(ref m) => Required(folder.fold_type_method(m)), @@ -674,7 +674,7 @@ pub fn noop_fold_item_underscore<T: Folder>(i: &Item_, folder: &mut T) -> Item_ } }).collect(); ItemTrait(fold_generics(generics, folder), - *sized, + unbound.clone(), traits.iter().map(|p| fold_trait_ref(p, folder)).collect(), methods) } @@ -1026,7 +1026,7 @@ mod test { assert_pred!( matches_codepattern, "matches_codepattern", - pprust::to_str(|s| fake_print_crate(s, &folded_crate)), + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); } @@ -1040,7 +1040,7 @@ mod test { assert_pred!( matches_codepattern, "matches_codepattern", - pprust::to_str(|s| fake_print_crate(s, &folded_crate)), + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))".to_string()); } } diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 6df91c66a25..53ee991385a 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -8,15 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! - -The Rust parser and macro expander. - -# Note - -This API is completely unstable and subject to change. - -*/ +//! The Rust parser and macro expander. +//! +//! # Note +//! +//! This API is completely unstable and subject to change. #![crate_id = "syntax#0.11.0"] // NOTE: remove after stage0 #![crate_name = "syntax"] diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index e47080dadfd..55ad1b77123 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -18,7 +18,7 @@ use parse::token::INTERPOLATED; use std::gc::{Gc, GC}; -// a parser that can parse attributes. +/// A parser that can parse attributes. pub trait ParserAttr { fn parse_outer_attributes(&mut self) -> Vec<ast::Attribute>; fn parse_attribute(&mut self, permit_inner: bool) -> ast::Attribute; @@ -30,11 +30,11 @@ pub trait ParserAttr { } impl<'a> ParserAttr for Parser<'a> { - // Parse attributes that appear before an item + /// Parse attributes that appear before an item fn parse_outer_attributes(&mut self) -> Vec<ast::Attribute> { let mut attrs: Vec<ast::Attribute> = Vec::new(); loop { - debug!("parse_outer_attributes: self.token={:?}", + debug!("parse_outer_attributes: self.token={}", self.token); match self.token { token::POUND => { @@ -43,7 +43,7 @@ impl<'a> ParserAttr for Parser<'a> { token::DOC_COMMENT(s) => { let attr = ::attr::mk_sugared_doc_attr( attr::mk_attr_id(), - self.id_to_interned_str(s), + self.id_to_interned_str(s.ident()), self.span.lo, self.span.hi ); @@ -59,10 +59,10 @@ impl<'a> ParserAttr for Parser<'a> { return attrs; } - // matches attribute = # ! [ meta_item ] - // - // if permit_inner is true, then a leading `!` indicates an inner - // attribute + /// Matches `attribute = # ! [ meta_item ]` + /// + /// If permit_inner is true, then a leading `!` indicates an inner + /// attribute fn parse_attribute(&mut self, permit_inner: bool) -> ast::Attribute { debug!("parse_attributes: permit_inner={:?} self.token={:?}", permit_inner, self.token); @@ -91,7 +91,7 @@ impl<'a> ParserAttr for Parser<'a> { (mk_sp(lo, hi), meta_item, style) } _ => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("expected `#` but found `{}`", token_str).as_slice()); } @@ -114,17 +114,17 @@ impl<'a> ParserAttr for Parser<'a> { }; } - // Parse attributes that appear after the opening of an item. These should - // be preceded by an exclamation mark, but we accept and warn about one - // terminated by a semicolon. In addition to a vector of inner attributes, - // this function also returns a vector that may contain the first outer - // attribute of the next item (since we can't know whether the attribute - // is an inner attribute of the containing item or an outer attribute of - // the first contained item until we see the semi). - - // matches inner_attrs* outer_attr? - // you can make the 'next' field an Option, but the result is going to be - // more useful as a vector. + /// Parse attributes that appear after the opening of an item. These should + /// be preceded by an exclamation mark, but we accept and warn about one + /// terminated by a semicolon. In addition to a vector of inner attributes, + /// this function also returns a vector that may contain the first outer + /// attribute of the next item (since we can't know whether the attribute + /// is an inner attribute of the containing item or an outer attribute of + /// the first contained item until we see the semi). + + /// matches inner_attrs* outer_attr? + /// you can make the 'next' field an Option, but the result is going to be + /// more useful as a vector. fn parse_inner_attrs_and_next(&mut self) -> (Vec<ast::Attribute> , Vec<ast::Attribute> ) { let mut inner_attrs: Vec<ast::Attribute> = Vec::new(); @@ -139,7 +139,7 @@ impl<'a> ParserAttr for Parser<'a> { let Span { lo, hi, .. } = self.span; self.bump(); attr::mk_sugared_doc_attr(attr::mk_attr_id(), - self.id_to_interned_str(s), + self.id_to_interned_str(s.ident()), lo, hi) } @@ -157,9 +157,9 @@ impl<'a> ParserAttr for Parser<'a> { (inner_attrs, next_outer_attrs) } - // matches meta_item = IDENT - // | IDENT = lit - // | IDENT meta_seq + /// matches meta_item = IDENT + /// | IDENT = lit + /// | IDENT meta_seq fn parse_meta_item(&mut self) -> Gc<ast::MetaItem> { match self.token { token::INTERPOLATED(token::NtMeta(e)) => { @@ -201,7 +201,7 @@ impl<'a> ParserAttr for Parser<'a> { } } - // matches meta_seq = ( COMMASEP(meta_item) ) + /// matches meta_seq = ( COMMASEP(meta_item) ) fn parse_meta_seq(&mut self) -> Vec<Gc<ast::MetaItem>> { self.parse_seq(&token::LPAREN, &token::RPAREN, diff --git a/src/libsyntax/parse/classify.rs b/src/libsyntax/parse/classify.rs index 8d9cc305c26..516f22cdf4d 100644 --- a/src/libsyntax/parse/classify.rs +++ b/src/libsyntax/parse/classify.rs @@ -15,13 +15,13 @@ use ast; use std::gc::Gc; -// does this expression require a semicolon to be treated -// as a statement? The negation of this: 'can this expression -// be used as a statement without a semicolon' -- is used -// as an early-bail-out in the parser so that, for instance, -// 'if true {...} else {...} -// |x| 5 ' -// isn't parsed as (if true {...} else {...} | x) | 5 +/// Does this expression require a semicolon to be treated +/// as a statement? The negation of this: 'can this expression +/// be used as a statement without a semicolon' -- is used +/// as an early-bail-out in the parser so that, for instance, +/// if true {...} else {...} +/// |x| 5 +/// isn't parsed as (if true {...} else {...} | x) | 5 pub fn expr_requires_semi_to_be_stmt(e: Gc<ast::Expr>) -> bool { match e.node { ast::ExprIf(..) @@ -41,9 +41,9 @@ pub fn expr_is_simple_block(e: Gc<ast::Expr>) -> bool { } } -// this statement requires a semicolon after it. -// note that in one case (stmt_semi), we've already -// seen the semicolon, and thus don't need another. +/// this statement requires a semicolon after it. +/// note that in one case (stmt_semi), we've already +/// seen the semicolon, and thus don't need another. pub fn stmt_ends_with_semi(stmt: &ast::Stmt) -> bool { return match stmt.node { ast::StmtDecl(d, _) => { diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index 3c3f0c7a820..3842170d677 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -12,8 +12,8 @@ use parse::token; -// SeqSep : a sequence separator (token) -// and whether a trailing separator is allowed. +/// SeqSep : a sequence separator (token) +/// and whether a trailing separator is allowed. pub struct SeqSep { pub sep: Option<token::Token>, pub trailing_sep_allowed: bool diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index f00c1ab4455..3f3a8a723f1 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -13,7 +13,7 @@ use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; use parse::lexer::{is_whitespace, Reader}; use parse::lexer::{StringReader, TokenAndSpan}; -use parse::lexer::{is_line_non_doc_comment, is_block_non_doc_comment}; +use parse::lexer::is_block_doc_comment; use parse::lexer; use parse::token; @@ -24,10 +24,14 @@ use std::uint; #[deriving(Clone, PartialEq)] pub enum CommentStyle { - Isolated, // No code on either side of each line of the comment - Trailing, // Code exists to the left of the comment - Mixed, // Code before /* foo */ and after the comment - BlankLine, // Just a manual blank line "\n\n", for layout + /// No code on either side of each line of the comment + Isolated, + /// Code exists to the left of the comment + Trailing, + /// Code before /* foo */ and after the comment + Mixed, + /// Just a manual blank line "\n\n", for layout + BlankLine, } #[deriving(Clone)] @@ -38,9 +42,9 @@ pub struct Comment { } pub fn is_doc_comment(s: &str) -> bool { - (s.starts_with("///") && !is_line_non_doc_comment(s)) || + (s.starts_with("///") && super::is_doc_comment(s)) || s.starts_with("//!") || - (s.starts_with("/**") && !is_block_non_doc_comment(s)) || + (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") } @@ -198,9 +202,9 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, } } -// Returns None if the first col chars of s contain a non-whitespace char. -// Otherwise returns Some(k) where k is first char offset after that leading -// whitespace. Note k may be outside bounds of s. +/// Returns None if the first col chars of s contain a non-whitespace char. +/// Otherwise returns Some(k) where k is first char offset after that leading +/// whitespace. Note k may be outside bounds of s. fn all_whitespace(s: &str, col: CharPos) -> Option<uint> { let len = s.len(); let mut col = col.to_uint(); @@ -256,7 +260,7 @@ fn read_block_comment(rdr: &mut StringReader, rdr.bump(); rdr.bump(); } - if !is_block_non_doc_comment(curr_line.as_slice()) { + if is_block_doc_comment(curr_line.as_slice()) { return } assert!(!curr_line.as_slice().contains_char('\n')); @@ -369,7 +373,7 @@ pub fn gather_comments_and_literals(span_diagnostic: &diagnostic::SpanHandler, literals.push(Literal {lit: s.to_string(), pos: sp.lo}); }) } else { - debug!("tok: {}", token::to_str(&tok)); + debug!("tok: {}", token::to_string(&tok)); } first_read = false; } diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 0f188fdf18a..0aaddacfab6 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -18,7 +18,6 @@ use parse::token::{str_to_ident}; use std::char; use std::mem::replace; -use std::num::from_str_radix; use std::rc::Rc; use std::str; @@ -44,13 +43,13 @@ pub struct TokenAndSpan { pub struct StringReader<'a> { pub span_diagnostic: &'a SpanHandler, - // The absolute offset within the codemap of the next character to read + /// The absolute offset within the codemap of the next character to read pub pos: BytePos, - // The absolute offset within the codemap of the last character read(curr) + /// The absolute offset within the codemap of the last character read(curr) pub last_pos: BytePos, - // The column of the next character to read + /// The column of the next character to read pub col: CharPos, - // The last character to be read + /// The last character to be read pub curr: Option<char>, pub filemap: Rc<codemap::FileMap>, /* cached: */ @@ -60,7 +59,7 @@ pub struct StringReader<'a> { impl<'a> Reader for StringReader<'a> { fn is_eof(&self) -> bool { self.curr.is_none() } - // return the next token. EFFECT: advances the string_reader. + /// Return the next token. EFFECT: advances the string_reader. fn next_token(&mut self) -> TokenAndSpan { let ret_val = TokenAndSpan { tok: replace(&mut self.peek_tok, token::UNDERSCORE), @@ -90,7 +89,7 @@ impl<'a> Reader for TtReader<'a> { } fn next_token(&mut self) -> TokenAndSpan { let r = tt_next_token(self); - debug!("TtReader: r={:?}", r); + debug!("TtReader: r={}", r); r } fn fatal(&self, m: &str) -> ! { @@ -188,7 +187,7 @@ impl<'a> StringReader<'a> { /// Advance peek_tok and peek_span to refer to the next token, and /// possibly update the interner. fn advance_token(&mut self) { - match self.consume_whitespace_and_comments() { + match self.scan_whitespace_or_comment() { Some(comment) => { self.peek_span = comment.sp; self.peek_tok = comment.tok; @@ -217,6 +216,20 @@ impl<'a> StringReader<'a> { self.with_str_from_to(start, self.last_pos, f) } + /// Create a Name from a given offset to the current offset, each + /// adjusted 1 towards each other (assumes that on either side there is a + /// single-byte delimiter). + pub fn name_from(&self, start: BytePos) -> ast::Name { + debug!("taking an ident from {} to {}", start, self.last_pos); + self.with_str_from(start, token::intern) + } + + /// As name_from, with an explicit endpoint. + pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name { + debug!("taking an ident from {} to {}", start, end); + self.with_str_from_to(start, end, token::intern) + } + /// Calls `f` with a string slice of the source text spanning from `start` /// up to but excluding `end`. fn with_str_from_to<T>(&self, start: BytePos, end: BytePos, f: |s: &str| -> T) -> T { @@ -326,8 +339,7 @@ impl<'a> StringReader<'a> { /// PRECONDITION: self.curr is not whitespace /// Eats any kind of comment. - /// Returns a Some(sugared-doc-attr) if one exists, None otherwise - fn consume_any_line_comment(&mut self) -> Option<TokenAndSpan> { + fn scan_comment(&mut self) -> Option<TokenAndSpan> { match self.curr { Some(c) => { if c.is_whitespace() { @@ -362,28 +374,32 @@ impl<'a> StringReader<'a> { } self.bump(); } - let ret = self.with_str_from(start_bpos, |string| { + return self.with_str_from(start_bpos, |string| { // but comments with only more "/"s are not - if !is_line_non_doc_comment(string) { - Some(TokenAndSpan{ - tok: token::DOC_COMMENT(str_to_ident(string)), - sp: codemap::mk_sp(start_bpos, self.last_pos) - }) + let tok = if is_doc_comment(string) { + token::DOC_COMMENT(token::intern(string)) } else { - None - } - }); + token::COMMENT + }; - if ret.is_some() { - return ret; - } + return Some(TokenAndSpan{ + tok: tok, + sp: codemap::mk_sp(start_bpos, self.last_pos) + }); + }); } else { + let start_bpos = self.last_pos - BytePos(2); while !self.curr_is('\n') && !self.is_eof() { self.bump(); } + return Some(TokenAndSpan { + tok: token::COMMENT, + sp: codemap::mk_sp(start_bpos, self.last_pos) + }); } - // Restart whitespace munch. - self.consume_whitespace_and_comments() } - Some('*') => { self.bump(); self.bump(); self.consume_block_comment() } + Some('*') => { + self.bump(); self.bump(); + self.scan_block_comment() + } _ => None } } else if self.curr_is('#') { @@ -399,9 +415,15 @@ impl<'a> StringReader<'a> { let cmap = CodeMap::new(); cmap.files.borrow_mut().push(self.filemap.clone()); let loc = cmap.lookup_char_pos_adj(self.last_pos); + debug!("Skipping a shebang"); if loc.line == 1u && loc.col == CharPos(0u) { + // FIXME: Add shebang "token", return it + let start = self.last_pos; while !self.curr_is('\n') && !self.is_eof() { self.bump(); } - return self.consume_whitespace_and_comments(); + return Some(TokenAndSpan { + tok: token::SHEBANG(self.name_from(start)), + sp: codemap::mk_sp(start, self.last_pos) + }); } } None @@ -410,15 +432,33 @@ impl<'a> StringReader<'a> { } } - /// EFFECT: eats whitespace and comments. - /// Returns a Some(sugared-doc-attr) if one exists, None otherwise. - fn consume_whitespace_and_comments(&mut self) -> Option<TokenAndSpan> { - while is_whitespace(self.curr) { self.bump(); } - return self.consume_any_line_comment(); + /// If there is whitespace, shebang, or a comment, scan it. Otherwise, + /// return None. + fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> { + match self.curr.unwrap_or('\0') { + // # to handle shebang at start of file -- this is the entry point + // for skipping over all "junk" + '/' | '#' => { + let c = self.scan_comment(); + debug!("scanning a comment {}", c); + c + }, + c if is_whitespace(Some(c)) => { + let start_bpos = self.last_pos; + while is_whitespace(self.curr) { self.bump(); } + let c = Some(TokenAndSpan { + tok: token::WS, + sp: codemap::mk_sp(start_bpos, self.last_pos) + }); + debug!("scanning whitespace: {}", c); + c + }, + _ => None + } } - // might return a sugared-doc-attr - fn consume_block_comment(&mut self) -> Option<TokenAndSpan> { + /// Might return a sugared-doc-attr + fn scan_block_comment(&mut self) -> Option<TokenAndSpan> { // block comments starting with "/**" or "/*!" are doc-comments let is_doc_comment = self.curr_is('*') || self.curr_is('!'); let start_bpos = self.last_pos - BytePos(2); @@ -453,228 +493,132 @@ impl<'a> StringReader<'a> { self.bump(); } - let res = if is_doc_comment { - self.with_str_from(start_bpos, |string| { - // but comments with only "*"s between two "/"s are not - if !is_block_non_doc_comment(string) { - let string = if has_cr { - self.translate_crlf(start_bpos, string, - "bare CR not allowed in block doc-comment") - } else { string.into_maybe_owned() }; - Some(TokenAndSpan{ - tok: token::DOC_COMMENT(str_to_ident(string.as_slice())), - sp: codemap::mk_sp(start_bpos, self.last_pos) - }) - } else { - None - } - }) - } else { - None - }; - - // restart whitespace munch. - if res.is_some() { res } else { self.consume_whitespace_and_comments() } - } - - fn scan_exponent(&mut self, start_bpos: BytePos) -> Option<String> { - // \x00 hits the `return None` case immediately, so this is fine. - let mut c = self.curr.unwrap_or('\x00'); - let mut rslt = String::new(); - if c == 'e' || c == 'E' { - rslt.push_char(c); - self.bump(); - c = self.curr.unwrap_or('\x00'); - if c == '-' || c == '+' { - rslt.push_char(c); - self.bump(); - } - let exponent = self.scan_digits(10u); - if exponent.len() > 0u { - rslt.push_str(exponent.as_slice()); - return Some(rslt); + self.with_str_from(start_bpos, |string| { + // but comments with only "*"s between two "/"s are not + let tok = if is_block_doc_comment(string) { + let string = if has_cr { + self.translate_crlf(start_bpos, string, + "bare CR not allowed in block doc-comment") + } else { string.into_maybe_owned() }; + token::DOC_COMMENT(token::intern(string.as_slice())) } else { - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "scan_exponent: bad fp literal"); - rslt.push_str("1"); // arbitrary placeholder exponent - return Some(rslt); - } - } else { - return None::<String>; - } + token::COMMENT + }; + + Some(TokenAndSpan{ + tok: tok, + sp: codemap::mk_sp(start_bpos, self.last_pos) + }) + }) } - fn scan_digits(&mut self, radix: uint) -> String { - let mut rslt = String::new(); + /// Scan through any digits (base `radix`) or underscores, and return how + /// many digits there were. + fn scan_digits(&mut self, radix: uint) -> uint { + let mut len = 0u; loop { let c = self.curr; - if c == Some('_') { self.bump(); continue; } + if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } match c.and_then(|cc| char::to_digit(cc, radix)) { - Some(_) => { - rslt.push_char(c.unwrap()); - self.bump(); - } - _ => return rslt + Some(_) => { + debug!("{} in scan_digits", c); + len += 1; + self.bump(); + } + _ => return len } }; } - fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) { - match base { - 16u => self.err_span_(start_bpos, last_bpos, - "hexadecimal float literal is not supported"), - 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), - 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), - _ => () - } - } - + /// Lex a LIT_INTEGER or a LIT_FLOAT fn scan_number(&mut self, c: char) -> token::Token { - let mut num_str; - let mut base = 10u; - let mut c = c; - let mut n = self.nextch().unwrap_or('\x00'); + let mut num_digits; + let mut base = 10; let start_bpos = self.last_pos; - if c == '0' && n == 'x' { - self.bump(); - self.bump(); - base = 16u; - } else if c == '0' && n == 'o' { - self.bump(); - self.bump(); - base = 8u; - } else if c == '0' && n == 'b' { - self.bump(); - self.bump(); - base = 2u; - } - num_str = self.scan_digits(base); - c = self.curr.unwrap_or('\x00'); - self.nextch(); - if c == 'u' || c == 'i' { - enum Result { Signed(ast::IntTy), Unsigned(ast::UintTy) } - let signed = c == 'i'; - let mut tp = { - if signed { Signed(ast::TyI) } - else { Unsigned(ast::TyU) } - }; - self.bump(); - c = self.curr.unwrap_or('\x00'); - if c == '8' { - self.bump(); - tp = if signed { Signed(ast::TyI8) } - else { Unsigned(ast::TyU8) }; - } - n = self.nextch().unwrap_or('\x00'); - if c == '1' && n == '6' { - self.bump(); - self.bump(); - tp = if signed { Signed(ast::TyI16) } - else { Unsigned(ast::TyU16) }; - } else if c == '3' && n == '2' { - self.bump(); - self.bump(); - tp = if signed { Signed(ast::TyI32) } - else { Unsigned(ast::TyU32) }; - } else if c == '6' && n == '4' { - self.bump(); - self.bump(); - tp = if signed { Signed(ast::TyI64) } - else { Unsigned(ast::TyU64) }; - } - if num_str.len() == 0u { - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "no valid digits found for number"); - num_str = "1".to_string(); - } - let parsed = match from_str_radix::<u64>(num_str.as_slice(), - base as uint) { - Some(p) => p, - None => { - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "int literal is too large"); - 1 - } - }; - match tp { - Signed(t) => return token::LIT_INT(parsed as i64, t), - Unsigned(t) => return token::LIT_UINT(parsed, t) + self.bump(); + + if c == '0' { + match self.curr.unwrap_or('\0') { + 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2); } + 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8); } + 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16); } + '0'..'9' | '_' | '.' => { + num_digits = self.scan_digits(10) + 1; + } + 'u' | 'i' => { + self.scan_int_suffix(); + return token::LIT_INTEGER(self.name_from(start_bpos)); + }, + 'f' => { + let last_pos = self.last_pos; + self.scan_float_suffix(); + self.check_float_base(start_bpos, last_pos, base); + return token::LIT_FLOAT(self.name_from(start_bpos)); + } + _ => { + // just a 0 + return token::LIT_INTEGER(self.name_from(start_bpos)); + } } + } else if c.is_digit_radix(10) { + num_digits = self.scan_digits(10) + 1; + } else { + num_digits = 0; } - let mut is_float = false; - if self.curr_is('.') && !(ident_start(self.nextch()) || self.nextch_is('.')) { - is_float = true; - self.bump(); - let dec_part = self.scan_digits(10u); - num_str.push_char('.'); - num_str.push_str(dec_part.as_slice()); - } - match self.scan_exponent(start_bpos) { - Some(ref s) => { - is_float = true; - num_str.push_str(s.as_slice()); - } - None => () + + if num_digits == 0 { + self.err_span_(start_bpos, self.last_pos, "no valid digits found for number"); + // eat any suffix + self.scan_int_suffix(); + return token::LIT_INTEGER(token::intern("0")); } - if self.curr_is('f') { + // might be a float, but don't be greedy if this is actually an + // integer literal followed by field/method access or a range pattern + // (`0..2` and `12.foo()`) + if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0') + .is_XID_start() { + // might have stuff after the ., and if it does, it needs to start + // with a number self.bump(); - c = self.curr.unwrap_or('\x00'); - n = self.nextch().unwrap_or('\x00'); - if c == '3' && n == '2' { - self.bump(); - self.bump(); - let last_bpos = self.last_pos; - self.check_float_base(start_bpos, last_bpos, base); - return token::LIT_FLOAT(str_to_ident(num_str.as_slice()), - ast::TyF32); - } else if c == '6' && n == '4' { - self.bump(); - self.bump(); - let last_bpos = self.last_pos; - self.check_float_base(start_bpos, last_bpos, base); - return token::LIT_FLOAT(str_to_ident(num_str.as_slice()), - ast::TyF64); - /* FIXME (#2252): if this is out of range for either a - 32-bit or 64-bit float, it won't be noticed till the - back-end. */ + if self.curr.unwrap_or('\0').is_digit_radix(10) { + self.scan_digits(10); + self.scan_float_exponent(); + self.scan_float_suffix(); } - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "expected `f32` or `f64` suffix"); - } - if is_float { - let last_bpos = self.last_pos; - self.check_float_base(start_bpos, last_bpos, base); - return token::LIT_FLOAT_UNSUFFIXED(str_to_ident( - num_str.as_slice())); + let last_pos = self.last_pos; + self.check_float_base(start_bpos, last_pos, base); + return token::LIT_FLOAT(self.name_from(start_bpos)); + } else if self.curr_is('f') { + // or it might be an integer literal suffixed as a float + self.scan_float_suffix(); + let last_pos = self.last_pos; + self.check_float_base(start_bpos, last_pos, base); + return token::LIT_FLOAT(self.name_from(start_bpos)); } else { - if num_str.len() == 0u { - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "no valid digits found for number"); - num_str = "1".to_string(); + // it might be a float if it has an exponent + if self.curr_is('e') || self.curr_is('E') { + self.scan_float_exponent(); + self.scan_float_suffix(); + let last_pos = self.last_pos; + self.check_float_base(start_bpos, last_pos, base); + return token::LIT_FLOAT(self.name_from(start_bpos)); } - let parsed = match from_str_radix::<u64>(num_str.as_slice(), - base as uint) { - Some(p) => p, - None => { - let last_bpos = self.last_pos; - self.err_span_(start_bpos, last_bpos, "int literal is too large"); - 1 - } - }; - - debug!("lexing {} as an unsuffixed integer literal", - num_str.as_slice()); - return token::LIT_INT_UNSUFFIXED(parsed as i64); + // but we certainly have an integer! + self.scan_int_suffix(); + return token::LIT_INTEGER(self.name_from(start_bpos)); } } - - fn scan_numeric_escape(&mut self, n_hex_digits: uint, delim: char) -> char { - let mut accum_int = 0u32; + /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an + /// error if too many or too few digits are encountered. + fn scan_hex_digits(&mut self, n_digits: uint, delim: char) -> bool { + debug!("scanning {} digits until {}", n_digits, delim); let start_bpos = self.last_pos; - for _ in range(0, n_hex_digits) { + let mut accum_int = 0; + + for _ in range(0, n_digits) { if self.is_eof() { let last_bpos = self.last_pos; self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape"); @@ -695,11 +639,11 @@ impl<'a> StringReader<'a> { } match char::from_u32(accum_int) { - Some(x) => x, + Some(_) => true, None => { let last_bpos = self.last_pos; self.err_span_(start_bpos, last_bpos, "illegal numeric character escape"); - '?' + false } } } @@ -707,8 +651,10 @@ impl<'a> StringReader<'a> { /// Scan for a single (possibly escaped) byte or char /// in a byte, (non-raw) byte string, char, or (non-raw) string literal. /// `start` is the position of `first_source_char`, which is already consumed. + /// + /// Returns true if there was a valid char/byte, false otherwise. fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char, - ascii_only: bool, delim: char) -> Option<char> { + ascii_only: bool, delim: char) -> bool { match first_source_char { '\\' => { // '\X' for some X must be a character constant: @@ -718,24 +664,18 @@ impl<'a> StringReader<'a> { match escaped { None => {}, // EOF here is an error that will be checked later. Some(e) => { - return Some(match e { - 'n' => '\n', - 'r' => '\r', - 't' => '\t', - '\\' => '\\', - '\'' => '\'', - '"' => '"', - '0' => '\x00', - 'x' => self.scan_numeric_escape(2u, delim), - 'u' if !ascii_only => self.scan_numeric_escape(4u, delim), - 'U' if !ascii_only => self.scan_numeric_escape(8u, delim), + return match e { + 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true, + 'x' => self.scan_hex_digits(2u, delim), + 'u' if !ascii_only => self.scan_hex_digits(4u, delim), + 'U' if !ascii_only => self.scan_hex_digits(8u, delim), '\n' if delim == '"' => { self.consume_whitespace(); - return None + true }, '\r' if delim == '"' && self.curr_is('\n') => { self.consume_whitespace(); - return None + true } c => { let last_pos = self.last_pos; @@ -744,9 +684,9 @@ impl<'a> StringReader<'a> { if ascii_only { "unknown byte escape" } else { "unknown character escape" }, c); - c + false } - }) + } } } } @@ -757,14 +697,16 @@ impl<'a> StringReader<'a> { if ascii_only { "byte constant must be escaped" } else { "character constant must be escaped" }, first_source_char); + return false; } '\r' => { if self.curr_is('\n') { self.bump(); - return Some('\n'); + return true; } else { self.err_span_(start, self.last_pos, "bare CR not allowed in string, use \\r instead"); + return false; } } _ => if ascii_only && first_source_char > '\x7F' { @@ -773,9 +715,84 @@ impl<'a> StringReader<'a> { start, last_pos, "byte constant must be ASCII. \ Use a \\xHH escape for a non-ASCII byte", first_source_char); + return false; + } + } + true + } + + /// Scan over an int literal suffix. + fn scan_int_suffix(&mut self) { + match self.curr { + Some('i') | Some('u') => { + self.bump(); + + if self.curr_is('8') { + self.bump(); + } else if self.curr_is('1') { + if !self.nextch_is('6') { + self.err_span_(self.last_pos, self.pos, + "illegal int suffix"); + } else { + self.bump(); self.bump(); + } + } else if self.curr_is('3') { + if !self.nextch_is('2') { + self.err_span_(self.last_pos, self.pos, + "illegal int suffix"); + } else { + self.bump(); self.bump(); + } + } else if self.curr_is('6') { + if !self.nextch_is('4') { + self.err_span_(self.last_pos, self.pos, + "illegal int suffix"); + } else { + self.bump(); self.bump(); + } + } + }, + _ => { } + } + } + + /// Scan over a float literal suffix + fn scan_float_suffix(&mut self) { + if self.curr_is('f') { + if (self.nextch_is('3') && self.nextnextch_is('2')) + || (self.nextch_is('6') && self.nextnextch_is('4')) { + self.bump(); + self.bump(); + self.bump(); + } else { + self.err_span_(self.last_pos, self.pos, "illegal float suffix"); } } - Some(first_source_char) + } + + /// Scan over a float exponent. + fn scan_float_exponent(&mut self) { + if self.curr_is('e') || self.curr_is('E') { + self.bump(); + if self.curr_is('-') || self.curr_is('+') { + self.bump(); + } + if self.scan_digits(10) == 0 { + self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent") + } + } + } + + /// Check that a base is valid for a floating literal, emitting a nice + /// error if it isn't. + fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) { + match base { + 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ + supported"), + 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), + 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), + _ => () + } } fn binop(&mut self, op: token::BinOp) -> token::Token { @@ -849,6 +866,7 @@ impl<'a> StringReader<'a> { '@' => { self.bump(); return token::AT; } '#' => { self.bump(); return token::POUND; } '~' => { self.bump(); return token::TILDE; } + '?' => { self.bump(); return token::QUESTION; } ':' => { self.bump(); if self.curr_is(':') { @@ -909,7 +927,7 @@ impl<'a> StringReader<'a> { let start = self.last_pos; // the eof will be picked up by the final `'` check below - let mut c2 = self.curr.unwrap_or('\x00'); + let c2 = self.curr.unwrap_or('\x00'); self.bump(); // If the character is an ident start not followed by another single @@ -952,7 +970,7 @@ impl<'a> StringReader<'a> { } // Otherwise it is a character constant: - c2 = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'').unwrap(); + let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\''); if !self.curr_is('\'') { let last_bpos = self.last_pos; self.fatal_span_verbose( @@ -962,118 +980,23 @@ impl<'a> StringReader<'a> { start - BytePos(1), last_bpos, "unterminated character constant".to_string()); } + let id = if valid { self.name_from(start) } else { token::intern("0") }; self.bump(); // advance curr past token - return token::LIT_CHAR(c2); + return token::LIT_CHAR(id); } 'b' => { self.bump(); return match self.curr { - Some('\'') => parse_byte(self), - Some('"') => parse_byte_string(self), - Some('r') => parse_raw_byte_string(self), + Some('\'') => self.scan_byte(), + Some('"') => self.scan_byte_string(), + Some('r') => self.scan_raw_byte_string(), _ => unreachable!() // Should have been a token::IDENT above. }; - fn parse_byte(self_: &mut StringReader) -> token::Token { - self_.bump(); - let start = self_.last_pos; - - // the eof will be picked up by the final `'` check below - let mut c2 = self_.curr.unwrap_or('\x00'); - self_.bump(); - - c2 = self_.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'').unwrap(); - if !self_.curr_is('\'') { - // Byte offsetting here is okay because the - // character before position `start` are an - // ascii single quote and ascii 'b'. - let last_pos = self_.last_pos; - self_.fatal_span_verbose( - start - BytePos(2), last_pos, - "unterminated byte constant".to_string()); - } - self_.bump(); // advance curr past token - return token::LIT_BYTE(c2 as u8); - } - - fn parse_byte_string(self_: &mut StringReader) -> token::Token { - self_.bump(); - let start = self_.last_pos; - let mut value = Vec::new(); - while !self_.curr_is('"') { - if self_.is_eof() { - let last_pos = self_.last_pos; - self_.fatal_span_(start, last_pos, - "unterminated double quote byte string"); - } - - let ch_start = self_.last_pos; - let ch = self_.curr.unwrap(); - self_.bump(); - self_.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"') - .map(|ch| value.push(ch as u8)); - } - self_.bump(); - return token::LIT_BINARY(Rc::new(value)); - } - - fn parse_raw_byte_string(self_: &mut StringReader) -> token::Token { - let start_bpos = self_.last_pos; - self_.bump(); - let mut hash_count = 0u; - while self_.curr_is('#') { - self_.bump(); - hash_count += 1; - } - - if self_.is_eof() { - let last_pos = self_.last_pos; - self_.fatal_span_(start_bpos, last_pos, "unterminated raw string"); - } else if !self_.curr_is('"') { - let last_pos = self_.last_pos; - let ch = self_.curr.unwrap(); - self_.fatal_span_char(start_bpos, last_pos, - "only `#` is allowed in raw string delimitation; \ - found illegal character", - ch); - } - self_.bump(); - let content_start_bpos = self_.last_pos; - let mut content_end_bpos; - 'outer: loop { - match self_.curr { - None => { - let last_pos = self_.last_pos; - self_.fatal_span_(start_bpos, last_pos, "unterminated raw string") - }, - Some('"') => { - content_end_bpos = self_.last_pos; - for _ in range(0, hash_count) { - self_.bump(); - if !self_.curr_is('#') { - continue 'outer; - } - } - break; - }, - Some(c) => if c > '\x7F' { - let last_pos = self_.last_pos; - self_.err_span_char( - last_pos, last_pos, "raw byte string must be ASCII", c); - } - } - self_.bump(); - } - self_.bump(); - let bytes = self_.with_str_from_to(content_start_bpos, - content_end_bpos, - |s| s.as_bytes().to_owned()); - return token::LIT_BINARY_RAW(Rc::new(bytes), hash_count); - } } '"' => { - let mut accum_str = String::new(); let start_bpos = self.last_pos; + let mut valid = true; self.bump(); while !self.curr_is('"') { if self.is_eof() { @@ -1084,11 +1007,13 @@ impl<'a> StringReader<'a> { let ch_start = self.last_pos; let ch = self.curr.unwrap(); self.bump(); - self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"') - .map(|ch| accum_str.push_char(ch)); + valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"'); } + // adjust for the ACSII " at the start of the literal + let id = if valid { self.name_from(start_bpos + BytePos(1)) } + else { token::intern("??") }; self.bump(); - return token::LIT_STR(str_to_ident(accum_str.as_slice())); + return token::LIT_STR(id); } 'r' => { let start_bpos = self.last_pos; @@ -1113,7 +1038,7 @@ impl<'a> StringReader<'a> { self.bump(); let content_start_bpos = self.last_pos; let mut content_end_bpos; - let mut has_cr = false; + let mut valid = true; 'outer: loop { if self.is_eof() { let last_bpos = self.last_pos; @@ -1136,23 +1061,26 @@ impl<'a> StringReader<'a> { } } break; - } + }, '\r' => { - has_cr = true; + if !self.nextch_is('\n') { + let last_bpos = self.last_pos; + self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \ + string, use \\r instead"); + valid = false; + } } _ => () } self.bump(); } self.bump(); - let str_content = self.with_str_from_to(content_start_bpos, content_end_bpos, |string| { - let string = if has_cr { - self.translate_crlf(content_start_bpos, string, - "bare CR not allowed in raw string") - } else { string.into_maybe_owned() }; - str_to_ident(string.as_slice()) - }); - return token::LIT_STR_RAW(str_content, hash_count); + let id = if valid { + self.name_from_to(content_start_bpos, content_end_bpos) + } else { + token::intern("??") + }; + return token::LIT_STR_RAW(id, hash_count); } '-' => { if self.nextch_is('>') { @@ -1220,6 +1148,104 @@ impl<'a> StringReader<'a> { // consider shebangs comments, but not inner attributes || (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('[')) } + + fn scan_byte(&mut self) -> token::Token { + self.bump(); + let start = self.last_pos; + + // the eof will be picked up by the final `'` check below + let c2 = self.curr.unwrap_or('\x00'); + self.bump(); + + let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\''); + if !self.curr_is('\'') { + // Byte offsetting here is okay because the + // character before position `start` are an + // ascii single quote and ascii 'b'. + let last_pos = self.last_pos; + self.fatal_span_verbose( + start - BytePos(2), last_pos, + "unterminated byte constant".to_string()); + } + + let id = if valid { self.name_from(start) } else { token::intern("??") }; + self.bump(); // advance curr past token + return token::LIT_BYTE(id); + } + + fn scan_byte_string(&mut self) -> token::Token { + self.bump(); + let start = self.last_pos; + let mut valid = true; + + while !self.curr_is('"') { + if self.is_eof() { + let last_pos = self.last_pos; + self.fatal_span_(start, last_pos, + "unterminated double quote byte string"); + } + + let ch_start = self.last_pos; + let ch = self.curr.unwrap(); + self.bump(); + valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"'); + } + let id = if valid { self.name_from(start) } else { token::intern("??") }; + self.bump(); + return token::LIT_BINARY(id); + } + + fn scan_raw_byte_string(&mut self) -> token::Token { + let start_bpos = self.last_pos; + self.bump(); + let mut hash_count = 0u; + while self.curr_is('#') { + self.bump(); + hash_count += 1; + } + + if self.is_eof() { + let last_pos = self.last_pos; + self.fatal_span_(start_bpos, last_pos, "unterminated raw string"); + } else if !self.curr_is('"') { + let last_pos = self.last_pos; + let ch = self.curr.unwrap(); + self.fatal_span_char(start_bpos, last_pos, + "only `#` is allowed in raw string delimitation; \ + found illegal character", + ch); + } + self.bump(); + let content_start_bpos = self.last_pos; + let mut content_end_bpos; + 'outer: loop { + match self.curr { + None => { + let last_pos = self.last_pos; + self.fatal_span_(start_bpos, last_pos, "unterminated raw string") + }, + Some('"') => { + content_end_bpos = self.last_pos; + for _ in range(0, hash_count) { + self.bump(); + if !self.curr_is('#') { + continue 'outer; + } + } + break; + }, + Some(c) => if c > '\x7F' { + let last_pos = self.last_pos; + self.err_span_char( + last_pos, last_pos, "raw byte string must be ASCII", c); + } + } + self.bump(); + } + self.bump(); + return token::LIT_BINARY_RAW(self.name_from_to(content_start_bpos, content_end_bpos), + hash_count); + } } pub fn is_whitespace(c: Option<char>) -> bool { @@ -1238,12 +1264,18 @@ fn in_range(c: Option<char>, lo: char, hi: char) -> bool { fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); } -pub fn is_line_non_doc_comment(s: &str) -> bool { - s.starts_with("////") +pub fn is_doc_comment(s: &str) -> bool { + let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') + || s.starts_with("//!"); + debug!("is `{}` a doc comment? {}", s, res); + res } -pub fn is_block_non_doc_comment(s: &str) -> bool { - s.starts_with("/***") +pub fn is_block_doc_comment(s: &str) -> bool { + let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') + || s.starts_with("/*!"); + debug!("is `{}` a doc comment? {}", s, res); + res } fn ident_start(c: Option<char>) -> bool { @@ -1294,11 +1326,14 @@ mod test { "/* my source file */ \ fn main() { println!(\"zebra\"); }\n".to_string()); let id = str_to_ident("fn"); + assert_eq!(string_reader.next_token().tok, token::COMMENT); + assert_eq!(string_reader.next_token().tok, token::WS); let tok1 = string_reader.next_token(); let tok2 = TokenAndSpan{ tok:token::IDENT(id, false), sp:Span {lo:BytePos(21),hi:BytePos(23),expn_info: None}}; assert_eq!(tok1,tok2); + assert_eq!(string_reader.next_token().tok, token::WS); // the 'main' id is already read: assert_eq!(string_reader.last_pos.clone(), BytePos(28)); // read another token: @@ -1327,6 +1362,7 @@ mod test { #[test] fn doublecolonparsing () { check_tokenization(setup(&mk_sh(), "a b".to_string()), vec!(mk_ident("a",false), + token::WS, mk_ident("b",false))); } @@ -1340,6 +1376,7 @@ mod test { #[test] fn dcparsing_3 () { check_tokenization(setup(&mk_sh(), "a ::b".to_string()), vec!(mk_ident("a",false), + token::WS, token::MOD_SEP, mk_ident("b",false))); } @@ -1348,22 +1385,23 @@ mod test { check_tokenization(setup(&mk_sh(), "a:: b".to_string()), vec!(mk_ident("a",true), token::MOD_SEP, + token::WS, mk_ident("b",false))); } #[test] fn character_a() { assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok, - token::LIT_CHAR('a')); + token::LIT_CHAR(token::intern("a"))); } #[test] fn character_space() { assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok, - token::LIT_CHAR(' ')); + token::LIT_CHAR(token::intern(" "))); } #[test] fn character_escaped() { assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok, - token::LIT_CHAR('\n')); + token::LIT_CHAR(token::intern("\\n"))); } #[test] fn lifetime_name() { @@ -1375,19 +1413,23 @@ mod test { assert_eq!(setup(&mk_sh(), "r###\"\"#a\\b\x00c\"\"###".to_string()).next_token() .tok, - token::LIT_STR_RAW(token::str_to_ident("\"#a\\b\x00c\""), 3)); + token::LIT_STR_RAW(token::intern("\"#a\\b\x00c\""), 3)); } #[test] fn line_doc_comments() { - assert!(!is_line_non_doc_comment("///")); - assert!(!is_line_non_doc_comment("/// blah")); - assert!(is_line_non_doc_comment("////")); + assert!(is_doc_comment("///")); + assert!(is_doc_comment("/// blah")); + assert!(!is_doc_comment("////")); } #[test] fn nested_block_comments() { - assert_eq!(setup(&mk_sh(), - "/* /* */ */'a'".to_string()).next_token().tok, - token::LIT_CHAR('a')); + let sh = mk_sh(); + let mut lexer = setup(&sh, "/* /* */ */'a'".to_string()); + match lexer.next_token().tok { + token::COMMENT => { }, + _ => fail!("expected a comment!") + } + assert_eq!(lexer.next_token().tok, token::LIT_CHAR(token::intern("a"))); } } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index fb4a23cf326..37c84c95af6 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -10,7 +10,6 @@ //! The main parser interface - use ast; use codemap::{Span, CodeMap, FileMap}; use diagnostic::{SpanHandler, mk_span_handler, default_handler, Auto}; @@ -32,7 +31,7 @@ pub mod common; pub mod classify; pub mod obsolete; -// info about a parsing session. +/// Info about a parsing session. pub struct ParseSess { pub span_diagnostic: SpanHandler, // better be the same as the one in the reader! /// Used to determine and report recursive mod inclusions @@ -241,14 +240,14 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>) unreachable!() } -// given a session and a string, add the string to -// the session's codemap and return the new filemap +/// Given a session and a string, add the string to +/// the session's codemap and return the new filemap pub fn string_to_filemap(sess: &ParseSess, source: String, path: String) -> Rc<FileMap> { sess.span_diagnostic.cm.new_filemap(path, source) } -// given a filemap, produce a sequence of token-trees +/// Given a filemap, produce a sequence of token-trees pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>) -> Vec<ast::TokenTree> { // it appears to me that the cfg doesn't matter here... indeed, @@ -259,7 +258,7 @@ pub fn filemap_to_tts(sess: &ParseSess, filemap: Rc<FileMap>) p1.parse_all_token_trees() } -// given tts and cfg, produce a parser +/// Given tts and cfg, produce a parser pub fn tts_to_parser<'a>(sess: &'a ParseSess, tts: Vec<ast::TokenTree>, cfg: ast::CrateConfig) -> Parser<'a> { @@ -267,13 +266,354 @@ pub fn tts_to_parser<'a>(sess: &'a ParseSess, Parser::new(sess, cfg, box trdr) } -// abort if necessary +/// Abort if necessary pub fn maybe_aborted<T>(result: T, mut p: Parser) -> T { p.abort_if_errors(); result } +/// Parse a string representing a character literal into its final form. +/// Rather than just accepting/rejecting a given literal, unescapes it as +/// well. Can take any slice prefixed by a character escape. Returns the +/// character and the number of characters consumed. +pub fn char_lit(lit: &str) -> (char, int) { + use std::{num, char}; + + let mut chars = lit.chars(); + let c = match (chars.next(), chars.next()) { + (Some(c), None) if c != '\\' => return (c, 1), + (Some('\\'), Some(c)) => match c { + '"' => Some('"'), + 'n' => Some('\n'), + 'r' => Some('\r'), + 't' => Some('\t'), + '\\' => Some('\\'), + '\'' => Some('\''), + '0' => Some('\0'), + _ => { None } + }, + _ => fail!("lexer accepted invalid char escape `{}`", lit) + }; + + match c { + Some(x) => return (x, 2), + None => { } + } + + let msg = format!("lexer should have rejected a bad character escape {}", lit); + let msg2 = msg.as_slice(); + + let esc: |uint| -> Option<(char, int)> = |len| + num::from_str_radix(lit.slice(2, len), 16) + .and_then(char::from_u32) + .map(|x| (x, len as int)); + + // Unicode escapes + return match lit.as_bytes()[1] as char { + 'x' | 'X' => esc(4), + 'u' => esc(6), + 'U' => esc(10), + _ => None, + }.expect(msg2); +} + +/// Parse a string representing a string literal into its final form. Does +/// unescaping. +pub fn str_lit(lit: &str) -> String { + debug!("parse_str_lit: given {}", lit.escape_default()); + let mut res = String::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let error = |i| format!("lexer should have rejected {} at {}", lit, i); + + /// Eat everything up to a non-whitespace + fn eat<'a>(it: &mut ::std::iter::Peekable<(uint, char), ::std::str::CharOffsets<'a>>) { + loop { + match it.peek().map(|x| x.val1()) { + Some(' ') | Some('\n') | Some('\r') | Some('\t') => { + it.next(); + }, + _ => { break; } + } + } + } + + let mut chars = lit.char_indices().peekable(); + loop { + match chars.next() { + Some((i, c)) => { + let em = error(i); + match c { + '\\' => { + if chars.peek().expect(em.as_slice()).val1() == '\n' { + eat(&mut chars); + } else if chars.peek().expect(em.as_slice()).val1() == '\r' { + chars.next(); + if chars.peek().expect(em.as_slice()).val1() != '\n' { + fail!("lexer accepted bare CR"); + } + eat(&mut chars); + } else { + // otherwise, a normal escape + let (c, n) = char_lit(lit.slice_from(i)); + for _ in range(0, n - 1) { // we don't need to move past the first \ + chars.next(); + } + res.push_char(c); + } + }, + '\r' => { + if chars.peek().expect(em.as_slice()).val1() != '\n' { + fail!("lexer accepted bare CR"); + } + chars.next(); + res.push_char('\n'); + } + c => res.push_char(c), + } + }, + None => break + } + } + + res.shrink_to_fit(); // probably not going to do anything, unless there was an escape. + debug!("parse_str_lit: returning {}", res); + res +} + +/// Parse a string representing a raw string literal into its final form. The +/// only operation this does is convert embedded CRLF into a single LF. +pub fn raw_str_lit(lit: &str) -> String { + debug!("raw_str_lit: given {}", lit.escape_default()); + let mut res = String::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let mut chars = lit.chars().peekable(); + loop { + match chars.next() { + Some(c) => { + if c == '\r' { + if *chars.peek().unwrap() != '\n' { + fail!("lexer accepted bare CR"); + } + chars.next(); + res.push_char('\n'); + } else { + res.push_char(c); + } + }, + None => break + } + } + + res.shrink_to_fit(); + res +} + +pub fn float_lit(s: &str) -> ast::Lit_ { + debug!("float_lit: {}", s); + // FIXME #2252: bounds checking float literals is defered until trans + let s2 = s.chars().filter(|&c| c != '_').collect::<String>(); + let s = s2.as_slice(); + + let mut ty = None; + + if s.ends_with("f32") { + ty = Some(ast::TyF32); + } else if s.ends_with("f64") { + ty = Some(ast::TyF64); + } + + + match ty { + Some(t) => { + ast::LitFloat(token::intern_and_get_ident(s.slice_to(s.len() - t.suffix_len())), t) + }, + None => ast::LitFloatUnsuffixed(token::intern_and_get_ident(s)) + } +} + +/// Parse a string representing a byte literal into its final form. Similar to `char_lit` +pub fn byte_lit(lit: &str) -> (u8, uint) { + let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i); + + if lit.len() == 1 { + (lit.as_bytes()[0], 1) + } else { + assert!(lit.as_bytes()[0] == b'\\', err(0i)); + let b = match lit.as_bytes()[1] { + b'"' => b'"', + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'\'' => b'\'', + b'0' => b'\0', + _ => { + match ::std::num::from_str_radix::<u64>(lit.slice(2, 4), 16) { + Some(c) => + if c > 0xFF { + fail!(err(2)) + } else { + return (c as u8, 4) + }, + None => fail!(err(3)) + } + } + }; + return (b, 2); + } +} + +pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { + let mut res = Vec::with_capacity(lit.len()); + + // FIXME #8372: This could be a for-loop if it didn't borrow the iterator + let error = |i| format!("lexer should have rejected {} at {}", lit, i); + + // binary literals *must* be ASCII, but the escapes don't have to be + let mut chars = lit.as_bytes().iter().enumerate().peekable(); + loop { + match chars.next() { + Some((i, &c)) => { + if c == b'\\' { + if *chars.peek().expect(error(i).as_slice()).val1() == b'\n' { + loop { + // eat everything up to a non-whitespace + match chars.peek().map(|x| *x.val1()) { + Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { + chars.next(); + }, + _ => { break; } + } + } + } else { + // otherwise, a normal escape + let (c, n) = byte_lit(lit.slice_from(i)); + for _ in range(0, n - 1) { // we don't need to move past the first \ + chars.next(); + } + res.push(c); + } + } else { + res.push(c); + } + }, + None => { break; } + } + } + + Rc::new(res) +} + +pub fn integer_lit(s: &str, sd: &SpanHandler, sp: Span) -> ast::Lit_ { + // s can only be ascii, byte indexing is fine + + let s2 = s.chars().filter(|&c| c != '_').collect::<String>(); + let mut s = s2.as_slice(); + + debug!("parse_integer_lit: {}", s); + + if s.len() == 1 { + return ast::LitIntUnsuffixed((s.char_at(0)).to_digit(10).unwrap() as i64); + } + let mut base = 10; + let orig = s; + + #[deriving(Show)] + enum Result { + Nothing, + Signed(ast::IntTy), + Unsigned(ast::UintTy) + } + + impl Result { + fn suffix_len(&self) -> uint { + match *self { + Nothing => 0, + Signed(s) => s.suffix_len(), + Unsigned(u) => u.suffix_len() + } + } + } + + let mut ty = Nothing; + + + if s.char_at(0) == '0' { + match s.char_at(1) { + 'x' => base = 16, + 'o' => base = 8, + 'b' => base = 2, + _ => { } + } + } + + if base != 10 { + s = s.slice_from(2); + } + + let last = s.len() - 1; + match s.char_at(last) { + 'i' => ty = Signed(ast::TyI), + 'u' => ty = Unsigned(ast::TyU), + '8' => { + if s.len() > 2 { + match s.char_at(last - 1) { + 'i' => ty = Signed(ast::TyI8), + 'u' => ty = Unsigned(ast::TyU8), + _ => { } + } + } + }, + '6' => { + if s.len() > 3 && s.char_at(last - 1) == '1' { + match s.char_at(last - 2) { + 'i' => ty = Signed(ast::TyI16), + 'u' => ty = Unsigned(ast::TyU16), + _ => { } + } + } + }, + '2' => { + if s.len() > 3 && s.char_at(last - 1) == '3' { + match s.char_at(last - 2) { + 'i' => ty = Signed(ast::TyI32), + 'u' => ty = Unsigned(ast::TyU32), + _ => { } + } + } + }, + '4' => { + if s.len() > 3 && s.char_at(last - 1) == '6' { + match s.char_at(last - 2) { + 'i' => ty = Signed(ast::TyI64), + 'u' => ty = Unsigned(ast::TyU64), + _ => { } + } + } + }, + _ => { } + } + + + s = s.slice_to(s.len() - ty.suffix_len()); + + debug!("The suffix is {}, base {}, the new string is {}, the original \ + string was {}", ty, base, s, orig); + + let res: u64 = match ::std::num::from_str_radix(s, base) { + Some(r) => r, + None => { sd.span_err(sp, "int literal is too large"); 0 } + }; + + match ty { + Nothing => ast::LitIntUnsuffixed(res as i64), + Signed(t) => ast::LitInt(res as i64, t), + Unsigned(t) => ast::LitUint(res, t) + } +} #[cfg(test)] mod test { diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 025684ae71e..cadae7ef12f 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -38,8 +38,8 @@ pub enum ObsoleteSyntax { pub trait ParserObsoleteMethods { /// Reports an obsolete syntax non-fatal error. fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax); - // Reports an obsolete syntax non-fatal error, and returns - // a placeholder expression + /// Reports an obsolete syntax non-fatal error, and returns + /// a placeholder expression fn obsolete_expr(&mut self, sp: Span, kind: ObsoleteSyntax) -> Gc<Expr>; fn report(&mut self, sp: Span, @@ -83,8 +83,8 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { self.report(sp, kind, kind_str, desc); } - // Reports an obsolete syntax non-fatal error, and returns - // a placeholder expression + /// Reports an obsolete syntax non-fatal error, and returns + /// a placeholder expression fn obsolete_expr(&mut self, sp: Span, kind: ObsoleteSyntax) -> Gc<Expr> { self.obsolete(sp, kind); self.mk_expr(sp.lo, sp.hi, ExprLit(box(GC) respan(sp, LitNil))) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 6b6387b0127..743eeed9da5 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -33,8 +33,8 @@ use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod}; use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic}; use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl}; use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_}; -use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar, LitByte, LitBinary}; -use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local, LocalLet}; +use ast::{LitBool, LitChar, LitByte, LitBinary}; +use ast::{LitNil, LitStr, LitUint, Local, LocalLet}; use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal}; use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability}; use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum}; @@ -42,7 +42,6 @@ use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct}; use ast::{PatTup, PatBox, PatWild, PatWildMulti}; use ast::{BiRem, Required}; use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl}; -use ast::{Sized, DynSize, StaticSize}; use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField}; use ast::{StructVariantKind, BiSub}; use ast::StrStyle; @@ -62,6 +61,7 @@ use ast_util::{as_prec, ident_to_path, lit_is_str, operator_prec}; use ast_util; use codemap::{Span, BytePos, Spanned, spanned, mk_sp}; use codemap; +use parse; use parse::attr::ParserAttr; use parse::classify; use parse::common::{SeqSep, seq_sep_none}; @@ -118,8 +118,8 @@ pub struct PathAndBounds { } enum ItemOrViewItem { - // Indicates a failure to parse any kind of item. The attributes are - // returned. + /// Indicates a failure to parse any kind of item. The attributes are + /// returned. IoviNone(Vec<Attribute>), IoviItem(Gc<Item>), IoviForeignItem(Gc<ForeignItem>), @@ -127,12 +127,12 @@ enum ItemOrViewItem { } -// Possibly accept an `INTERPOLATED` expression (a pre-parsed expression -// dropped into the token stream, which happens while parsing the -// result of macro expansion) -/* Placement of these is not as complex as I feared it would be. -The important thing is to make sure that lookahead doesn't balk -at INTERPOLATED tokens */ +/// Possibly accept an `INTERPOLATED` expression (a pre-parsed expression +/// dropped into the token stream, which happens while parsing the +/// result of macro expansion) +/// Placement of these is not as complex as I feared it would be. +/// The important thing is to make sure that lookahead doesn't balk +/// at INTERPOLATED tokens macro_rules! maybe_whole_expr ( ($p:expr) => ( { @@ -167,7 +167,7 @@ macro_rules! maybe_whole_expr ( ) ) -// As above, but for things other than expressions +/// As maybe_whole_expr, but for things other than expressions macro_rules! maybe_whole ( ($p:expr, $constructor:ident) => ( { @@ -288,14 +288,14 @@ struct ParsedItemsAndViewItems { pub struct Parser<'a> { pub sess: &'a ParseSess, - // the current token: + /// the current token: pub token: token::Token, - // the span of the current token: + /// the span of the current token: pub span: Span, - // the span of the prior token: + /// the span of the prior token: pub last_span: Span, pub cfg: CrateConfig, - // the previous token or None (only stashed sometimes). + /// the previous token or None (only stashed sometimes). pub last_token: Option<Box<token::Token>>, pub buffer: [TokenAndSpan, ..4], pub buffer_start: int, @@ -325,10 +325,24 @@ fn is_plain_ident_or_underscore(t: &token::Token) -> bool { is_plain_ident(t) || *t == token::UNDERSCORE } +/// Get a token the parser cares about +fn real_token(rdr: &mut Reader) -> TokenAndSpan { + let mut t = rdr.next_token(); + loop { + match t.tok { + token::WS | token::COMMENT | token::SHEBANG(_) => { + t = rdr.next_token(); + }, + _ => break + } + } + t +} + impl<'a> Parser<'a> { pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig, mut rdr: Box<Reader>) -> Parser<'a> { - let tok0 = rdr.next_token(); + let tok0 = real_token(rdr); let span = tok0.sp; let placeholder = TokenAndSpan { tok: token::UNDERSCORE, @@ -362,57 +376,58 @@ impl<'a> Parser<'a> { root_module_name: None, } } - // convert a token to a string using self's reader - pub fn token_to_str(token: &token::Token) -> String { - token::to_str(token) + + /// Convert a token to a string using self's reader + pub fn token_to_string(token: &token::Token) -> String { + token::to_string(token) } - // convert the current token to a string using self's reader - pub fn this_token_to_str(&mut self) -> String { - Parser::token_to_str(&self.token) + /// Convert the current token to a string using self's reader + pub fn this_token_to_string(&mut self) -> String { + Parser::token_to_string(&self.token) } pub fn unexpected_last(&mut self, t: &token::Token) -> ! { - let token_str = Parser::token_to_str(t); + let token_str = Parser::token_to_string(t); let last_span = self.last_span; self.span_fatal(last_span, format!("unexpected token: `{}`", token_str).as_slice()); } pub fn unexpected(&mut self) -> ! { - let this_token = self.this_token_to_str(); + let this_token = self.this_token_to_string(); self.fatal(format!("unexpected token: `{}`", this_token).as_slice()); } - // expect and consume the token t. Signal an error if - // the next token is not t. + /// Expect and consume the token t. Signal an error if + /// the next token is not t. pub fn expect(&mut self, t: &token::Token) { if self.token == *t { self.bump(); } else { - let token_str = Parser::token_to_str(t); - let this_token_str = self.this_token_to_str(); + let token_str = Parser::token_to_string(t); + let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}` but found `{}`", token_str, this_token_str).as_slice()) } } - // Expect next token to be edible or inedible token. If edible, - // then consume it; if inedible, then return without consuming - // anything. Signal a fatal error if next token is unexpected. + /// Expect next token to be edible or inedible token. If edible, + /// then consume it; if inedible, then return without consuming + /// anything. Signal a fatal error if next token is unexpected. pub fn expect_one_of(&mut self, edible: &[token::Token], inedible: &[token::Token]) { - fn tokens_to_str(tokens: &[token::Token]) -> String { + fn tokens_to_string(tokens: &[token::Token]) -> String { let mut i = tokens.iter(); // This might be a sign we need a connect method on Iterator. let b = i.next() - .map_or("".to_string(), |t| Parser::token_to_str(t)); + .map_or("".to_string(), |t| Parser::token_to_string(t)); i.fold(b, |b,a| { let mut b = b; b.push_str("`, `"); - b.push_str(Parser::token_to_str(a).as_slice()); + b.push_str(Parser::token_to_string(a).as_slice()); b }) } @@ -422,8 +437,8 @@ impl<'a> Parser<'a> { // leave it in the input } else { let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible); - let expect = tokens_to_str(expected.as_slice()); - let actual = self.this_token_to_str(); + let expect = tokens_to_string(expected.as_slice()); + let actual = self.this_token_to_string(); self.fatal( (if expected.len() != 1 { (format!("expected one of `{}` but found `{}`", @@ -438,9 +453,9 @@ impl<'a> Parser<'a> { } } - // Check for erroneous `ident { }`; if matches, signal error and - // recover (without consuming any expected input token). Returns - // true if and only if input was consumed for recovery. + /// Check for erroneous `ident { }`; if matches, signal error and + /// recover (without consuming any expected input token). Returns + /// true if and only if input was consumed for recovery. pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool { if self.token == token::LBRACE && expected.iter().all(|t| *t != token::LBRACE) @@ -457,9 +472,9 @@ impl<'a> Parser<'a> { } } - // Commit to parsing a complete expression `e` expected to be - // followed by some token from the set edible + inedible. Recover - // from anticipated input errors, discarding erroneous characters. + /// Commit to parsing a complete expression `e` expected to be + /// followed by some token from the set edible + inedible. Recover + /// from anticipated input errors, discarding erroneous characters. pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token], inedible: &[token::Token]) { debug!("commit_expr {:?}", e); @@ -480,9 +495,9 @@ impl<'a> Parser<'a> { self.commit_expr(e, &[edible], &[]) } - // Commit to parsing a complete statement `s`, which expects to be - // followed by some token from the set edible + inedible. Check - // for recoverable input errors, discarding erroneous characters. + /// Commit to parsing a complete statement `s`, which expects to be + /// followed by some token from the set edible + inedible. Check + /// for recoverable input errors, discarding erroneous characters. pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token], inedible: &[token::Token]) { debug!("commit_stmt {:?}", s); @@ -512,7 +527,7 @@ impl<'a> Parser<'a> { self.bug("ident interpolation not converted to real token"); } _ => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal((format!("expected ident, found `{}`", token_str)).as_slice()) } @@ -527,8 +542,8 @@ impl<'a> Parser<'a> { id: ast::DUMMY_NODE_ID }) } - // consume token 'tok' if it exists. Returns true if the given - // token was present, false otherwise. + /// Consume token 'tok' if it exists. Returns true if the given + /// token was present, false otherwise. pub fn eat(&mut self, tok: &token::Token) -> bool { let is_present = self.token == *tok; if is_present { self.bump() } @@ -539,33 +554,34 @@ impl<'a> Parser<'a> { token::is_keyword(kw, &self.token) } - // if the next token is the given keyword, eat it and return - // true. Otherwise, return false. + /// If the next token is the given keyword, eat it and return + /// true. Otherwise, return false. pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool { - let is_kw = match self.token { - token::IDENT(sid, false) => kw.to_ident().name == sid.name, + match self.token { + token::IDENT(sid, false) if kw.to_name() == sid.name => { + self.bump(); + true + } _ => false - }; - if is_kw { self.bump() } - is_kw + } } - // if the given word is not a keyword, signal an error. - // if the next token is not the given word, signal an error. - // otherwise, eat it. + /// If the given word is not a keyword, signal an error. + /// If the next token is not the given word, signal an error. + /// Otherwise, eat it. pub fn expect_keyword(&mut self, kw: keywords::Keyword) { if !self.eat_keyword(kw) { - let id_interned_str = token::get_ident(kw.to_ident()); - let token_str = self.this_token_to_str(); + let id_interned_str = token::get_name(kw.to_name()); + let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", id_interned_str, token_str).as_slice()) } } - // signal an error if the given string is a strict keyword + /// Signal an error if the given string is a strict keyword pub fn check_strict_keywords(&mut self) { if token::is_strict_keyword(&self.token) { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); let span = self.span; self.span_err(span, format!("found `{}` in ident position", @@ -573,17 +589,17 @@ impl<'a> Parser<'a> { } } - // signal an error if the current token is a reserved keyword + /// Signal an error if the current token is a reserved keyword pub fn check_reserved_keywords(&mut self) { if token::is_reserved_keyword(&self.token) { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("`{}` is a reserved keyword", token_str).as_slice()) } } - // Expect and consume an `&`. If `&&` is seen, replace it with a single - // `&` and continue. If an `&` is not seen, signal an error. + /// Expect and consume an `&`. If `&&` is seen, replace it with a single + /// `&` and continue. If an `&` is not seen, signal an error. fn expect_and(&mut self) { match self.token { token::BINOP(token::AND) => self.bump(), @@ -593,9 +609,9 @@ impl<'a> Parser<'a> { self.replace_token(token::BINOP(token::AND), lo, span.hi) } _ => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); let found_token = - Parser::token_to_str(&token::BINOP(token::AND)); + Parser::token_to_string(&token::BINOP(token::AND)); self.fatal(format!("expected `{}`, found `{}`", found_token, token_str).as_slice()) @@ -603,8 +619,8 @@ impl<'a> Parser<'a> { } } - // Expect and consume a `|`. If `||` is seen, replace it with a single - // `|` and continue. If a `|` is not seen, signal an error. + /// Expect and consume a `|`. If `||` is seen, replace it with a single + /// `|` and continue. If a `|` is not seen, signal an error. fn expect_or(&mut self) { match self.token { token::BINOP(token::OR) => self.bump(), @@ -614,9 +630,9 @@ impl<'a> Parser<'a> { self.replace_token(token::BINOP(token::OR), lo, span.hi) } _ => { - let found_token = self.this_token_to_str(); + let found_token = self.this_token_to_string(); let token_str = - Parser::token_to_str(&token::BINOP(token::OR)); + Parser::token_to_string(&token::BINOP(token::OR)); self.fatal(format!("expected `{}`, found `{}`", token_str, found_token).as_slice()) @@ -624,26 +640,26 @@ impl<'a> Parser<'a> { } } - // Attempt to consume a `<`. If `<<` is seen, replace it with a single - // `<` and continue. If a `<` is not seen, return false. - // - // This is meant to be used when parsing generics on a path to get the - // starting token. The `force` parameter is used to forcefully break up a - // `<<` token. If `force` is false, then `<<` is only broken when a lifetime - // shows up next. For example, consider the expression: - // - // foo as bar << test - // - // The parser needs to know if `bar <<` is the start of a generic path or if - // it's a left-shift token. If `test` were a lifetime, then it's impossible - // for the token to be a left-shift, but if it's not a lifetime, then it's - // considered a left-shift. - // - // The reason for this is that the only current ambiguity with `<<` is when - // parsing closure types: - // - // foo::<<'a> ||>(); - // impl Foo<<'a> ||>() { ... } + /// Attempt to consume a `<`. If `<<` is seen, replace it with a single + /// `<` and continue. If a `<` is not seen, return false. + /// + /// This is meant to be used when parsing generics on a path to get the + /// starting token. The `force` parameter is used to forcefully break up a + /// `<<` token. If `force` is false, then `<<` is only broken when a lifetime + /// shows up next. For example, consider the expression: + /// + /// foo as bar << test + /// + /// The parser needs to know if `bar <<` is the start of a generic path or if + /// it's a left-shift token. If `test` were a lifetime, then it's impossible + /// for the token to be a left-shift, but if it's not a lifetime, then it's + /// considered a left-shift. + /// + /// The reason for this is that the only current ambiguity with `<<` is when + /// parsing closure types: + /// + /// foo::<<'a> ||>(); + /// impl Foo<<'a> ||>() { ... } fn eat_lt(&mut self, force: bool) -> bool { match self.token { token::LT => { self.bump(); true } @@ -667,15 +683,15 @@ impl<'a> Parser<'a> { fn expect_lt(&mut self) { if !self.eat_lt(true) { - let found_token = self.this_token_to_str(); - let token_str = Parser::token_to_str(&token::LT); + let found_token = self.this_token_to_string(); + let token_str = Parser::token_to_string(&token::LT); self.fatal(format!("expected `{}`, found `{}`", token_str, found_token).as_slice()) } } - // Parse a sequence bracketed by `|` and `|`, stopping before the `|`. + /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`. fn parse_seq_to_before_or<T>( &mut self, sep: &token::Token, @@ -696,9 +712,9 @@ impl<'a> Parser<'a> { vector } - // expect and consume a GT. if a >> is seen, replace it - // with a single > and continue. If a GT is not seen, - // signal an error. + /// Expect and consume a GT. if a >> is seen, replace it + /// with a single > and continue. If a GT is not seen, + /// signal an error. pub fn expect_gt(&mut self) { match self.token { token::GT => self.bump(), @@ -718,8 +734,8 @@ impl<'a> Parser<'a> { self.replace_token(token::EQ, lo, span.hi) } _ => { - let gt_str = Parser::token_to_str(&token::GT); - let this_token_str = self.this_token_to_str(); + let gt_str = Parser::token_to_string(&token::GT); + let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", gt_str, this_token_str).as_slice()) @@ -727,8 +743,8 @@ impl<'a> Parser<'a> { } } - // parse a sequence bracketed by '<' and '>', stopping - // before the '>'. + /// Parse a sequence bracketed by '<' and '>', stopping + /// before the '>'. pub fn parse_seq_to_before_gt<T>( &mut self, sep: Option<token::Token>, @@ -762,9 +778,9 @@ impl<'a> Parser<'a> { return v; } - // parse a sequence, including the closing delimiter. The function - // f must consume tokens until reaching the next separator or - // closing bracket. + /// Parse a sequence, including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. pub fn parse_seq_to_end<T>( &mut self, ket: &token::Token, @@ -776,9 +792,9 @@ impl<'a> Parser<'a> { val } - // parse a sequence, not including the closing delimiter. The function - // f must consume tokens until reaching the next separator or - // closing bracket. + /// Parse a sequence, not including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. pub fn parse_seq_to_before_end<T>( &mut self, ket: &token::Token, @@ -801,9 +817,9 @@ impl<'a> Parser<'a> { return v; } - // parse a sequence, including the closing delimiter. The function - // f must consume tokens until reaching the next separator or - // closing bracket. + /// Parse a sequence, including the closing delimiter. The function + /// f must consume tokens until reaching the next separator or + /// closing bracket. pub fn parse_unspanned_seq<T>( &mut self, bra: &token::Token, @@ -817,8 +833,8 @@ impl<'a> Parser<'a> { result } - // parse a sequence parameter of enum variant. For consistency purposes, - // these should not be empty. + /// Parse a sequence parameter of enum variant. For consistency purposes, + /// these should not be empty. pub fn parse_enum_variant_seq<T>( &mut self, bra: &token::Token, @@ -852,7 +868,7 @@ impl<'a> Parser<'a> { spanned(lo, hi, result) } - // advance the parser by one token + /// Advance the parser by one token pub fn bump(&mut self) { self.last_span = self.span; // Stash token for error recovery (sometimes; clone is not necessarily cheap). @@ -862,7 +878,7 @@ impl<'a> Parser<'a> { None }; let next = if self.buffer_start == self.buffer_end { - self.reader.next_token() + real_token(self.reader) } else { // Avoid token copies with `replace`. let buffer_start = self.buffer_start as uint; @@ -880,14 +896,14 @@ impl<'a> Parser<'a> { self.tokens_consumed += 1u; } - // Advance the parser by one token and return the bumped token. + /// Advance the parser by one token and return the bumped token. pub fn bump_and_get(&mut self) -> token::Token { let old_token = replace(&mut self.token, token::UNDERSCORE); self.bump(); old_token } - // EFFECT: replace the current token and span with the given one + /// EFFECT: replace the current token and span with the given one pub fn replace_token(&mut self, next: token::Token, lo: BytePos, @@ -906,7 +922,7 @@ impl<'a> Parser<'a> { -> R { let dist = distance as int; while self.buffer_length() < dist { - self.buffer[self.buffer_end as uint] = self.reader.next_token(); + self.buffer[self.buffer_end as uint] = real_token(self.reader); self.buffer_end = (self.buffer_end + 1) & 3; } f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok) @@ -940,8 +956,8 @@ impl<'a> Parser<'a> { token::get_ident(id) } - // Is the current token one of the keywords that signals a bare function - // type? + /// Is the current token one of the keywords that signals a bare function + /// type? pub fn token_is_bare_fn_keyword(&mut self) -> bool { if token::is_keyword(keywords::Fn, &self.token) { return true @@ -955,14 +971,14 @@ impl<'a> Parser<'a> { false } - // Is the current token one of the keywords that signals a closure type? + /// Is the current token one of the keywords that signals a closure type? pub fn token_is_closure_keyword(&mut self) -> bool { token::is_keyword(keywords::Unsafe, &self.token) || token::is_keyword(keywords::Once, &self.token) } - // Is the current token one of the keywords that signals an old-style - // closure type (with explicit sigil)? + /// Is the current token one of the keywords that signals an old-style + /// closure type (with explicit sigil)? pub fn token_is_old_style_closure_keyword(&mut self) -> bool { token::is_keyword(keywords::Unsafe, &self.token) || token::is_keyword(keywords::Once, &self.token) || @@ -983,7 +999,7 @@ impl<'a> Parser<'a> { } } - // parse a TyBareFn type: + /// parse a TyBareFn type: pub fn parse_ty_bare_fn(&mut self) -> Ty_ { /* @@ -1014,8 +1030,8 @@ impl<'a> Parser<'a> { }); } - // Parses a procedure type (`proc`). The initial `proc` keyword must - // already have been parsed. + /// Parses a procedure type (`proc`). The initial `proc` keyword must + /// already have been parsed. pub fn parse_proc_type(&mut self) -> Ty_ { /* @@ -1063,7 +1079,7 @@ impl<'a> Parser<'a> { }) } - // parse a TyClosure type + /// Parse a TyClosure type pub fn parse_ty_closure(&mut self) -> Ty_ { /* @@ -1154,7 +1170,7 @@ impl<'a> Parser<'a> { } } - // parse a function type (following the 'fn') + /// Parse a function type (following the 'fn') pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool) -> (P<FnDecl>, Vec<ast::Lifetime>) { /* @@ -1186,7 +1202,7 @@ impl<'a> Parser<'a> { (decl, lifetimes) } - // parse the methods in a trait declaration + /// Parse the methods in a trait declaration pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> { self.parse_unspanned_seq( &token::LBRACE, @@ -1247,7 +1263,7 @@ impl<'a> Parser<'a> { } _ => { - let token_str = p.this_token_to_str(); + let token_str = p.this_token_to_string(); p.fatal((format!("expected `;` or `{{` but found `{}`", token_str)).as_slice()) } @@ -1255,15 +1271,15 @@ impl<'a> Parser<'a> { }) } - // parse a possibly mutable type + /// Parse a possibly mutable type pub fn parse_mt(&mut self) -> MutTy { let mutbl = self.parse_mutability(); let t = self.parse_ty(true); MutTy { ty: t, mutbl: mutbl } } - // parse [mut/const/imm] ID : TY - // now used only by obsolete record syntax parser... + /// Parse [mut/const/imm] ID : TY + /// now used only by obsolete record syntax parser... pub fn parse_ty_field(&mut self) -> TypeField { let lo = self.span.lo; let mutbl = self.parse_mutability(); @@ -1278,7 +1294,7 @@ impl<'a> Parser<'a> { } } - // parse optional return type [ -> TY ] in function decl + /// Parse optional return type [ -> TY ] in function decl pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) { return if self.eat(&token::RARROW) { let lo = self.span.lo; @@ -1478,8 +1494,8 @@ impl<'a> Parser<'a> { } } - // This version of parse arg doesn't necessarily require - // identifier names. + /// This version of parse arg doesn't necessarily require + /// identifier names. pub fn parse_arg_general(&mut self, require_name: bool) -> Arg { let pat = if require_name || self.is_named_argument() { debug!("parse_arg_general parse_pat (require_name:{:?})", @@ -1504,12 +1520,12 @@ impl<'a> Parser<'a> { } } - // parse a single function argument + /// Parse a single function argument pub fn parse_arg(&mut self) -> Arg { self.parse_arg_general(true) } - // parse an argument in a lambda header e.g. |arg, arg| + /// Parse an argument in a lambda header e.g. |arg, arg| pub fn parse_fn_block_arg(&mut self) -> Arg { let pat = self.parse_pat(); let t = if self.eat(&token::COLON) { @@ -1539,34 +1555,32 @@ impl<'a> Parser<'a> { } } - // matches token_lit = LIT_INT | ... + /// Matches token_lit = LIT_INTEGER | ... pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ { match *tok { - token::LIT_BYTE(i) => LitByte(i), - token::LIT_CHAR(i) => LitChar(i), - token::LIT_INT(i, it) => LitInt(i, it), - token::LIT_UINT(u, ut) => LitUint(u, ut), - token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i), - token::LIT_FLOAT(s, ft) => { - LitFloat(self.id_to_interned_str(s), ft) - } - token::LIT_FLOAT_UNSUFFIXED(s) => { - LitFloatUnsuffixed(self.id_to_interned_str(s)) - } + token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()), + token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()), + token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(), + &self.sess.span_diagnostic, self.span), + token::LIT_FLOAT(s) => parse::float_lit(s.as_str()), token::LIT_STR(s) => { - LitStr(self.id_to_interned_str(s), ast::CookedStr) + LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()), + ast::CookedStr) } token::LIT_STR_RAW(s, n) => { - LitStr(self.id_to_interned_str(s), ast::RawStr(n)) + LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()), + ast::RawStr(n)) } - token::LIT_BINARY_RAW(ref v, _) | - token::LIT_BINARY(ref v) => LitBinary(v.clone()), + token::LIT_BINARY(i) => + LitBinary(parse::binary_lit(i.as_str())), + token::LIT_BINARY_RAW(i, _) => + LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())), token::LPAREN => { self.expect(&token::RPAREN); LitNil }, _ => { self.unexpected_last(tok); } } } - // matches lit = true | false | token_lit + /// Matches lit = true | false | token_lit pub fn parse_lit(&mut self) -> Lit { let lo = self.span.lo; let lit = if self.eat_keyword(keywords::True) { @@ -1581,7 +1595,7 @@ impl<'a> Parser<'a> { codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) } } - // matches '-' lit | lit + /// matches '-' lit | lit pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> { let minus_lo = self.span.lo; let minus_present = self.eat(&token::BINOP(token::MINUS)); @@ -1719,7 +1733,7 @@ impl<'a> Parser<'a> { } /// Parses a single lifetime - // matches lifetime = LIFETIME + /// Matches lifetime = LIFETIME pub fn parse_lifetime(&mut self) -> ast::Lifetime { match self.token { token::LIFETIME(i) => { @@ -1779,7 +1793,7 @@ impl<'a> Parser<'a> { token::is_keyword(keywords::Const, tok) } - // parse mutability declaration (mut/const/imm) + /// Parse mutability declaration (mut/const/imm) pub fn parse_mutability(&mut self) -> Mutability { if self.eat_keyword(keywords::Mut) { MutMutable @@ -1788,7 +1802,7 @@ impl<'a> Parser<'a> { } } - // parse ident COLON expr + /// Parse ident COLON expr pub fn parse_field(&mut self) -> Field { let lo = self.span.lo; let i = self.parse_ident(); @@ -1867,9 +1881,9 @@ impl<'a> Parser<'a> { } } - // at the bottom (top?) of the precedence hierarchy, - // parse things like parenthesized exprs, - // macros, return, etc. + /// At the bottom (top?) of the precedence hierarchy, + /// parse things like parenthesized exprs, + /// macros, return, etc. pub fn parse_bottom_expr(&mut self) -> Gc<Expr> { maybe_whole_expr!(self); @@ -1878,217 +1892,241 @@ impl<'a> Parser<'a> { let ex: Expr_; - if self.token == token::LPAREN { - self.bump(); - // (e) is parenthesized e - // (e,) is a tuple with only one field, e - let mut trailing_comma = false; - if self.token == token::RPAREN { - hi = self.span.hi; - self.bump(); - let lit = box(GC) spanned(lo, hi, LitNil); - return self.mk_expr(lo, hi, ExprLit(lit)); - } - let mut es = vec!(self.parse_expr()); - self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]); - while self.token == token::COMMA { + match self.token { + token::LPAREN => { self.bump(); - if self.token != token::RPAREN { - es.push(self.parse_expr()); - self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]); + // (e) is parenthesized e + // (e,) is a tuple with only one field, e + let mut trailing_comma = false; + if self.token == token::RPAREN { + hi = self.span.hi; + self.bump(); + let lit = box(GC) spanned(lo, hi, LitNil); + return self.mk_expr(lo, hi, ExprLit(lit)); } - else { - trailing_comma = true; + let mut es = vec!(self.parse_expr()); + self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]); + while self.token == token::COMMA { + self.bump(); + if self.token != token::RPAREN { + es.push(self.parse_expr()); + self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]); + } + else { + trailing_comma = true; + } } - } - hi = self.span.hi; - self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN); - - return if es.len() == 1 && !trailing_comma { - self.mk_expr(lo, hi, ExprParen(*es.get(0))) - } - else { - self.mk_expr(lo, hi, ExprTup(es)) - } - } else if self.token == token::LBRACE { - self.bump(); - let blk = self.parse_block_tail(lo, DefaultBlock); - return self.mk_expr(blk.span.lo, blk.span.hi, - ExprBlock(blk)); - } else if token::is_bar(&self.token) { - return self.parse_lambda_expr(); - } else if self.eat_keyword(keywords::Proc) { - let decl = self.parse_proc_decl(); - let body = self.parse_expr(); - let fakeblock = P(ast::Block { - view_items: Vec::new(), - stmts: Vec::new(), - expr: Some(body), - id: ast::DUMMY_NODE_ID, - rules: DefaultBlock, - span: body.span, - }); + hi = self.span.hi; + self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN); - return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock)); - } else if self.eat_keyword(keywords::Self) { - let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_); - ex = ExprPath(path); - hi = self.last_span.hi; - } else if self.eat_keyword(keywords::If) { - return self.parse_if_expr(); - } else if self.eat_keyword(keywords::For) { - return self.parse_for_expr(None); - } else if self.eat_keyword(keywords::While) { - return self.parse_while_expr(); - } else if Parser::token_is_lifetime(&self.token) { - let lifetime = self.get_lifetime(); - self.bump(); - self.expect(&token::COLON); - if self.eat_keyword(keywords::For) { - return self.parse_for_expr(Some(lifetime)) - } else if self.eat_keyword(keywords::Loop) { - return self.parse_loop_expr(Some(lifetime)) - } else { - self.fatal("expected `for` or `loop` after a label") + return if es.len() == 1 && !trailing_comma { + self.mk_expr(lo, hi, ExprParen(*es.get(0))) + } + else { + self.mk_expr(lo, hi, ExprTup(es)) + } + }, + token::LBRACE => { + self.bump(); + let blk = self.parse_block_tail(lo, DefaultBlock); + return self.mk_expr(blk.span.lo, blk.span.hi, + ExprBlock(blk)); + }, + token::BINOP(token::OR) | token::OROR => { + return self.parse_lambda_expr(); + }, + _ if self.eat_keyword(keywords::Proc) => { + let decl = self.parse_proc_decl(); + let body = self.parse_expr(); + let fakeblock = P(ast::Block { + view_items: Vec::new(), + stmts: Vec::new(), + expr: Some(body), + id: ast::DUMMY_NODE_ID, + rules: DefaultBlock, + span: body.span, + }); + return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock)); + }, + // FIXME #13626: Should be able to stick in + // token::SELF_KEYWORD_NAME + token::IDENT(id @ ast::Ident{ + name: ast::Name(token::SELF_KEYWORD_NAME_NUM), + ctxt: _ + } ,false) => { + self.bump(); + let path = ast_util::ident_to_path(mk_sp(lo, hi), id); + ex = ExprPath(path); + hi = self.last_span.hi; } - } else if self.eat_keyword(keywords::Loop) { - return self.parse_loop_expr(None); - } else if self.eat_keyword(keywords::Continue) { - let lo = self.span.lo; - let ex = if Parser::token_is_lifetime(&self.token) { + _ if self.eat_keyword(keywords::If) => { + return self.parse_if_expr(); + }, + _ if self.eat_keyword(keywords::For) => { + return self.parse_for_expr(None); + }, + _ if self.eat_keyword(keywords::While) => { + return self.parse_while_expr(); + }, + _ if Parser::token_is_lifetime(&self.token) => { let lifetime = self.get_lifetime(); self.bump(); - ExprAgain(Some(lifetime)) - } else { - ExprAgain(None) - }; - let hi = self.span.hi; - return self.mk_expr(lo, hi, ex); - } else if self.eat_keyword(keywords::Match) { - return self.parse_match_expr(); - } else if self.eat_keyword(keywords::Unsafe) { - return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided)); - } else if self.token == token::LBRACKET { - self.bump(); - - if self.token == token::RBRACKET { - // Empty vector. - self.bump(); - ex = ExprVec(Vec::new()); - } else { - // Nonempty vector. - let first_expr = self.parse_expr(); - if self.token == token::COMMA && - self.look_ahead(1, |t| *t == token::DOTDOT) { - // Repeating vector syntax: [ 0, ..512 ] + self.expect(&token::COLON); + if self.eat_keyword(keywords::For) { + return self.parse_for_expr(Some(lifetime)) + } else if self.eat_keyword(keywords::Loop) { + return self.parse_loop_expr(Some(lifetime)) + } else { + self.fatal("expected `for` or `loop` after a label") + } + }, + _ if self.eat_keyword(keywords::Loop) => { + return self.parse_loop_expr(None); + }, + _ if self.eat_keyword(keywords::Continue) => { + let lo = self.span.lo; + let ex = if Parser::token_is_lifetime(&self.token) { + let lifetime = self.get_lifetime(); self.bump(); + ExprAgain(Some(lifetime)) + } else { + ExprAgain(None) + }; + let hi = self.span.hi; + return self.mk_expr(lo, hi, ex); + }, + _ if self.eat_keyword(keywords::Match) => { + return self.parse_match_expr(); + }, + _ if self.eat_keyword(keywords::Unsafe) => { + return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided)); + }, + token::LBRACKET => { + self.bump(); + + if self.token == token::RBRACKET { + // Empty vector. self.bump(); - let count = self.parse_expr(); - self.expect(&token::RBRACKET); - ex = ExprRepeat(first_expr, count); - } else if self.token == token::COMMA { - // Vector with two or more elements. + ex = ExprVec(Vec::new()); + } else { + // Nonempty vector. + let first_expr = self.parse_expr(); + if self.token == token::COMMA && + self.look_ahead(1, |t| *t == token::DOTDOT) { + // Repeating vector syntax: [ 0, ..512 ] + self.bump(); + self.bump(); + let count = self.parse_expr(); + self.expect(&token::RBRACKET); + ex = ExprRepeat(first_expr, count); + } else if self.token == token::COMMA { + // Vector with two or more elements. + self.bump(); + let remaining_exprs = self.parse_seq_to_end( + &token::RBRACKET, + seq_sep_trailing_allowed(token::COMMA), + |p| p.parse_expr() + ); + let mut exprs = vec!(first_expr); + exprs.push_all_move(remaining_exprs); + ex = ExprVec(exprs); + } else { + // Vector with one element. + self.expect(&token::RBRACKET); + ex = ExprVec(vec!(first_expr)); + } + } + hi = self.last_span.hi; + }, + _ if self.eat_keyword(keywords::Return) => { + // RETURN expression + if can_begin_expr(&self.token) { + let e = self.parse_expr(); + hi = e.span.hi; + ex = ExprRet(Some(e)); + } else { ex = ExprRet(None); } + }, + _ if self.eat_keyword(keywords::Break) => { + // BREAK expression + if Parser::token_is_lifetime(&self.token) { + let lifetime = self.get_lifetime(); self.bump(); - let remaining_exprs = self.parse_seq_to_end( - &token::RBRACKET, - seq_sep_trailing_allowed(token::COMMA), - |p| p.parse_expr() - ); - let mut exprs = vec!(first_expr); - exprs.push_all_move(remaining_exprs); - ex = ExprVec(exprs); + ex = ExprBreak(Some(lifetime)); } else { - // Vector with one element. - self.expect(&token::RBRACKET); - ex = ExprVec(vec!(first_expr)); + ex = ExprBreak(None); } - } - hi = self.last_span.hi; - } else if self.eat_keyword(keywords::Return) { - // RETURN expression - if can_begin_expr(&self.token) { - let e = self.parse_expr(); - hi = e.span.hi; - ex = ExprRet(Some(e)); - } else { ex = ExprRet(None); } - } else if self.eat_keyword(keywords::Break) { - // BREAK expression - if Parser::token_is_lifetime(&self.token) { - let lifetime = self.get_lifetime(); - self.bump(); - ex = ExprBreak(Some(lifetime)); - } else { - ex = ExprBreak(None); - } - hi = self.span.hi; - } else if self.token == token::MOD_SEP || + hi = self.span.hi; + }, + _ if self.token == token::MOD_SEP || is_ident(&self.token) && !self.is_keyword(keywords::True) && - !self.is_keyword(keywords::False) { - let pth = self.parse_path(LifetimeAndTypesWithColons).path; + !self.is_keyword(keywords::False) => { + let pth = self.parse_path(LifetimeAndTypesWithColons).path; - // `!`, as an operator, is prefix, so we know this isn't that - if self.token == token::NOT { - // MACRO INVOCATION expression - self.bump(); + // `!`, as an operator, is prefix, so we know this isn't that + if self.token == token::NOT { + // MACRO INVOCATION expression + self.bump(); - let ket = token::close_delimiter_for(&self.token) - .unwrap_or_else(|| self.fatal("expected open delimiter")); - self.bump(); + let ket = token::close_delimiter_for(&self.token) + .unwrap_or_else(|| self.fatal("expected open delimiter")); + self.bump(); - let tts = self.parse_seq_to_end(&ket, - seq_sep_none(), - |p| p.parse_token_tree()); - let hi = self.span.hi; + let tts = self.parse_seq_to_end(&ket, + seq_sep_none(), + |p| p.parse_token_tree()); + let hi = self.span.hi; - return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)); - } else if self.token == token::LBRACE { - // This is a struct literal, unless we're prohibited from - // parsing struct literals here. - if self.restriction != RESTRICT_NO_STRUCT_LITERAL { - // It's a struct literal. - self.bump(); - let mut fields = Vec::new(); - let mut base = None; + return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)); + } else if self.token == token::LBRACE { + // This is a struct literal, unless we're prohibited from + // parsing struct literals here. + if self.restriction != RESTRICT_NO_STRUCT_LITERAL { + // It's a struct literal. + self.bump(); + let mut fields = Vec::new(); + let mut base = None; + + while self.token != token::RBRACE { + if self.eat(&token::DOTDOT) { + base = Some(self.parse_expr()); + break; + } - while self.token != token::RBRACE { - if self.eat(&token::DOTDOT) { - base = Some(self.parse_expr()); - break; + fields.push(self.parse_field()); + self.commit_expr(fields.last().unwrap().expr, + &[token::COMMA], &[token::RBRACE]); } - fields.push(self.parse_field()); - self.commit_expr(fields.last().unwrap().expr, - &[token::COMMA], &[token::RBRACE]); - } + if fields.len() == 0 && base.is_none() { + let last_span = self.last_span; + self.span_err(last_span, + "structure literal must either have at \ + least one field or use functional \ + structure update syntax"); + } - if fields.len() == 0 && base.is_none() { - let last_span = self.last_span; - self.span_err(last_span, - "structure literal must either have at \ - least one field or use functional \ - structure update syntax"); + hi = self.span.hi; + self.expect(&token::RBRACE); + ex = ExprStruct(pth, fields, base); + return self.mk_expr(lo, hi, ex); } - - hi = self.span.hi; - self.expect(&token::RBRACE); - ex = ExprStruct(pth, fields, base); - return self.mk_expr(lo, hi, ex); } - } hi = pth.span.hi; ex = ExprPath(pth); - } else { - // other literal expression - let lit = self.parse_lit(); - hi = lit.span.hi; - ex = ExprLit(box(GC) lit); + }, + _ => { + // other literal expression + let lit = self.parse_lit(); + hi = lit.span.hi; + ex = ExprLit(box(GC) lit); + } } return self.mk_expr(lo, hi, ex); } - // parse a block or unsafe block + /// Parse a block or unsafe block pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode) -> Gc<Expr> { self.expect(&token::LBRACE); @@ -2096,7 +2134,7 @@ impl<'a> Parser<'a> { return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)); } - // parse a.b or a(13) or a[4] or just a + /// parse a.b or a(13) or a[4] or just a pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> { let b = self.parse_bottom_expr(); self.parse_dot_or_call_expr_with(b) @@ -2180,8 +2218,8 @@ impl<'a> Parser<'a> { return e; } - // parse an optional separator followed by a kleene-style - // repetition token (+ or *). + /// Parse an optional separator followed by a kleene-style + /// repetition token (+ or *). pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) { fn parse_zerok(parser: &mut Parser) -> Option<bool> { match parser.token { @@ -2206,7 +2244,7 @@ impl<'a> Parser<'a> { } } - // parse a single token tree from the input. + /// parse a single token tree from the input. pub fn parse_token_tree(&mut self) -> TokenTree { // FIXME #6994: currently, this is too eager. It // parses token trees but also identifies TTSeq's @@ -2231,7 +2269,7 @@ impl<'a> Parser<'a> { None => {} Some(&sp) => p.span_note(sp, "unclosed delimiter"), }; - let token_str = p.this_token_to_str(); + let token_str = p.this_token_to_string(); p.fatal(format!("incorrect close delimiter: `{}`", token_str).as_slice()) }, @@ -2322,9 +2360,9 @@ impl<'a> Parser<'a> { } } - // This goofy function is necessary to correctly match parens in Matcher's. - // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be - // invalid. It's similar to common::parse_seq. + /// This goofy function is necessary to correctly match parens in Matcher's. + /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be + /// invalid. It's similar to common::parse_seq. pub fn parse_matcher_subseq_upto(&mut self, name_idx: &mut uint, ket: &token::Token) @@ -2373,7 +2411,7 @@ impl<'a> Parser<'a> { return spanned(lo, self.span.hi, m); } - // parse a prefix-operator expr + /// Parse a prefix-operator expr pub fn parse_prefix_expr(&mut self) -> Gc<Expr> { let lo = self.span.lo; let hi; @@ -2481,13 +2519,13 @@ impl<'a> Parser<'a> { return self.mk_expr(lo, hi, ex); } - // parse an expression of binops + /// Parse an expression of binops pub fn parse_binops(&mut self) -> Gc<Expr> { let prefix_expr = self.parse_prefix_expr(); self.parse_more_binops(prefix_expr, 0) } - // parse an expression of binops of at least min_prec precedence + /// Parse an expression of binops of at least min_prec precedence pub fn parse_more_binops(&mut self, lhs: Gc<Expr>, min_prec: uint) -> Gc<Expr> { if self.expr_is_complete(lhs) { return lhs; } @@ -2535,9 +2573,9 @@ impl<'a> Parser<'a> { } } - // parse an assignment expression.... - // actually, this seems to be the main entry point for - // parsing an arbitrary expression. + /// Parse an assignment expression.... + /// actually, this seems to be the main entry point for + /// parsing an arbitrary expression. pub fn parse_assign_expr(&mut self) -> Gc<Expr> { let lo = self.span.lo; let lhs = self.parse_binops(); @@ -2571,7 +2609,7 @@ impl<'a> Parser<'a> { } } - // parse an 'if' expression ('if' token already eaten) + /// Parse an 'if' expression ('if' token already eaten) pub fn parse_if_expr(&mut self) -> Gc<Expr> { let lo = self.last_span.lo; let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL); @@ -2586,7 +2624,7 @@ impl<'a> Parser<'a> { self.mk_expr(lo, hi, ExprIf(cond, thn, els)) } - // `|args| { ... }` or `{ ...}` like in `do` expressions + /// `|args| { ... }` or `{ ...}` like in `do` expressions pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> { self.parse_lambda_expr_( |p| { @@ -2615,15 +2653,15 @@ impl<'a> Parser<'a> { }) } - // `|args| expr` + /// `|args| expr` pub fn parse_lambda_expr(&mut self) -> Gc<Expr> { self.parse_lambda_expr_(|p| p.parse_fn_block_decl(), |p| p.parse_expr()) } - // parse something of the form |args| expr - // this is used both in parsing a lambda expr - // and in parsing a block expr as e.g. in for... + /// parse something of the form |args| expr + /// this is used both in parsing a lambda expr + /// and in parsing a block expr as e.g. in for... pub fn parse_lambda_expr_(&mut self, parse_decl: |&mut Parser| -> P<FnDecl>, parse_body: |&mut Parser| -> Gc<Expr>) @@ -2652,7 +2690,7 @@ impl<'a> Parser<'a> { } } - // parse a 'for' .. 'in' expression ('for' token already eaten) + /// Parse a 'for' .. 'in' expression ('for' token already eaten) pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> { // Parse: `for <src_pat> in <src_expr> <src_loop_block>` @@ -2718,12 +2756,12 @@ impl<'a> Parser<'a> { return self.mk_expr(lo, hi, ExprMatch(discriminant, arms)); } - // parse an expression + /// Parse an expression pub fn parse_expr(&mut self) -> Gc<Expr> { return self.parse_expr_res(UNRESTRICTED); } - // parse an expression, subject to the given restriction + /// Parse an expression, subject to the given restriction pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> { let old = self.restriction; self.restriction = r; @@ -2732,7 +2770,7 @@ impl<'a> Parser<'a> { return e; } - // parse the RHS of a local variable declaration (e.g. '= 14;') + /// Parse the RHS of a local variable declaration (e.g. '= 14;') fn parse_initializer(&mut self) -> Option<Gc<Expr>> { if self.token == token::EQ { self.bump(); @@ -2742,7 +2780,7 @@ impl<'a> Parser<'a> { } } - // parse patterns, separated by '|' s + /// Parse patterns, separated by '|' s fn parse_pats(&mut self) -> Vec<Gc<Pat>> { let mut pats = Vec::new(); loop { @@ -2805,7 +2843,7 @@ impl<'a> Parser<'a> { (before, slice, after) } - // parse the fields of a struct-like pattern + /// Parse the fields of a struct-like pattern fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) { let mut fields = Vec::new(); let mut etc = false; @@ -2822,7 +2860,7 @@ impl<'a> Parser<'a> { if self.token == token::DOTDOT { self.bump(); if self.token != token::RBRACE { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", "}", token_str).as_slice()) } @@ -2843,7 +2881,7 @@ impl<'a> Parser<'a> { let subpat = if self.token == token::COLON { match bind_type { BindByRef(..) | BindByValue(MutMutable) => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("unexpected `{}`", token_str).as_slice()) } @@ -2865,7 +2903,7 @@ impl<'a> Parser<'a> { return (fields, etc); } - // parse a pattern. + /// Parse a pattern. pub fn parse_pat(&mut self) -> Gc<Pat> { maybe_whole!(self, NtPat); @@ -3107,9 +3145,9 @@ impl<'a> Parser<'a> { } } - // parse ident or ident @ pat - // used by the copy foo and ref foo patterns to give a good - // error message when parsing mistakes like ref foo(a,b) + /// Parse ident or ident @ pat + /// used by the copy foo and ref foo patterns to give a good + /// error message when parsing mistakes like ref foo(a,b) fn parse_pat_ident(&mut self, binding_mode: ast::BindingMode) -> ast::Pat_ { @@ -3143,7 +3181,7 @@ impl<'a> Parser<'a> { PatIdent(binding_mode, name, sub) } - // parse a local variable declaration + /// Parse a local variable declaration fn parse_local(&mut self) -> Gc<Local> { let lo = self.span.lo; let pat = self.parse_pat(); @@ -3167,14 +3205,14 @@ impl<'a> Parser<'a> { } } - // parse a "let" stmt + /// Parse a "let" stmt fn parse_let(&mut self) -> Gc<Decl> { let lo = self.span.lo; let local = self.parse_local(); box(GC) spanned(lo, self.last_span.hi, DeclLocal(local)) } - // parse a structure field + /// Parse a structure field fn parse_name_and_ty(&mut self, pr: Visibility, attrs: Vec<Attribute> ) -> StructField { let lo = self.span.lo; @@ -3192,8 +3230,8 @@ impl<'a> Parser<'a> { }) } - // parse a statement. may include decl. - // precondition: any attributes are parsed already + /// Parse a statement. may include decl. + /// Precondition: any attributes are parsed already pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> { maybe_whole!(self, NtStmt); @@ -3214,18 +3252,6 @@ impl<'a> Parser<'a> { } else if is_ident(&self.token) && !token::is_any_keyword(&self.token) && self.look_ahead(1, |t| *t == token::NOT) { - // parse a macro invocation. Looks like there's serious - // overlap here; if this clause doesn't catch it (and it - // won't, for brace-delimited macros) it will fall through - // to the macro clause of parse_item_or_view_item. This - // could use some cleanup, it appears to me. - - // whoops! I now have a guess: I'm guessing the "parens-only" - // rule here is deliberate, to allow macro users to use parens - // for things that should be parsed as stmt_mac, and braces - // for things that should expand into items. Tricky, and - // somewhat awkward... and probably undocumented. Of course, - // I could just be wrong. check_expected_item(self, !item_attrs.is_empty()); @@ -3253,7 +3279,7 @@ impl<'a> Parser<'a> { } else { "" }; - let tok_str = self.this_token_to_str(); + let tok_str = self.this_token_to_string(); self.fatal(format!("expected {}`(` or `{{`, but found `{}`", ident_str, tok_str).as_slice()) @@ -3308,13 +3334,13 @@ impl<'a> Parser<'a> { } } - // is this expression a successfully-parsed statement? + /// Is this expression a successfully-parsed statement? fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool { return self.restriction == RESTRICT_STMT_EXPR && !classify::expr_requires_semi_to_be_stmt(e); } - // parse a block. No inner attrs are allowed. + /// Parse a block. No inner attrs are allowed. pub fn parse_block(&mut self) -> P<Block> { maybe_whole!(no_clone self, NtBlock); @@ -3324,7 +3350,7 @@ impl<'a> Parser<'a> { return self.parse_block_tail_(lo, DefaultBlock, Vec::new()); } - // parse a block. Inner attrs are allowed. + /// Parse a block. Inner attrs are allowed. fn parse_inner_attrs_and_block(&mut self) -> (Vec<Attribute> , P<Block>) { @@ -3337,15 +3363,15 @@ impl<'a> Parser<'a> { (inner, self.parse_block_tail_(lo, DefaultBlock, next)) } - // Precondition: already parsed the '{' or '#{' - // I guess that also means "already parsed the 'impure'" if - // necessary, and this should take a qualifier. - // some blocks start with "#{"... + /// Precondition: already parsed the '{' or '#{' + /// I guess that also means "already parsed the 'impure'" if + /// necessary, and this should take a qualifier. + /// Some blocks start with "#{"... fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> { self.parse_block_tail_(lo, s, Vec::new()) } - // parse the rest of a block expression or function body + /// Parse the rest of a block expression or function body fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode, first_item_attrs: Vec<Attribute> ) -> P<Block> { let mut stmts = Vec::new(); @@ -3503,18 +3529,18 @@ impl<'a> Parser<'a> { } } - // matches bounds = ( boundseq )? - // where boundseq = ( bound + boundseq ) | bound - // and bound = 'static | ty - // Returns "None" if there's no colon (e.g. "T"); - // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:") - // Returns "Some(stuff)" otherwise (e.g. "T:stuff"). - // NB: The None/Some distinction is important for issue #7264. - // - // Note that the `allow_any_lifetime` argument is a hack for now while the - // AST doesn't support arbitrary lifetimes in bounds on type parameters. In - // the future, this flag should be removed, and the return value of this - // function should be Option<~[TyParamBound]> + /// matches optbounds = ( ( : ( boundseq )? )? ) + /// where boundseq = ( bound + boundseq ) | bound + /// and bound = 'static | ty + /// Returns "None" if there's no colon (e.g. "T"); + /// Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:") + /// Returns "Some(stuff)" otherwise (e.g. "T:stuff"). + /// NB: The None/Some distinction is important for issue #7264. + /// + /// Note that the `allow_any_lifetime` argument is a hack for now while the + /// AST doesn't support arbitrary lifetimes in bounds on type parameters. In + /// the future, this flag should be removed, and the return value of this + /// function should be Option<~[TyParamBound]> fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool) -> (Option<ast::Lifetime>, OwnedSlice<TyParamBound>) { @@ -3564,11 +3590,40 @@ impl<'a> Parser<'a> { return (ret_lifetime, OwnedSlice::from_vec(result)); } - // matches typaram = type? IDENT optbounds ( EQ ty )? + fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef { + let segment = ast::PathSegment { + identifier: ident, + lifetimes: Vec::new(), + types: OwnedSlice::empty(), + }; + let path = ast::Path { + span: span, + global: false, + segments: vec![segment], + }; + ast::TraitRef { + path: path, + ref_id: ast::DUMMY_NODE_ID, + } + } + + /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )? fn parse_ty_param(&mut self) -> TyParam { - let sized = self.parse_sized(); - let span = self.span; - let ident = self.parse_ident(); + // This is a bit hacky. Currently we are only interested in a single + // unbound, and it may only be `Sized`. To avoid backtracking and other + // complications, we parse an ident, then check for `?`. If we find it, + // we use the ident as the unbound, otherwise, we use it as the name of + // type param. + let mut span = self.span; + let mut ident = self.parse_ident(); + let mut unbound = None; + if self.eat(&token::QUESTION) { + let tref = Parser::trait_ref_from_ident(ident, span); + unbound = Some(TraitTyParamBound(tref)); + span = self.span; + ident = self.parse_ident(); + } + let opt_bounds = { if self.eat(&token::COLON) { let (_, bounds) = self.parse_ty_param_bounds(false); @@ -3589,17 +3644,17 @@ impl<'a> Parser<'a> { TyParam { ident: ident, id: ast::DUMMY_NODE_ID, - sized: sized, bounds: bounds, + unbound: unbound, default: default, span: span, } } - // parse a set of optional generic type parameter declarations - // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) - // | ( < lifetimes , typaramseq ( , )? > ) - // where typaramseq = ( typaram ) | ( typaram , typaramseq ) + /// Parse a set of optional generic type parameter declarations + /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > ) + /// | ( < lifetimes , typaramseq ( , )? > ) + /// where typaramseq = ( typaram ) | ( typaram , typaramseq ) pub fn parse_generics(&mut self) -> ast::Generics { if self.eat(&token::LT) { let lifetimes = self.parse_lifetimes(); @@ -3691,7 +3746,7 @@ impl<'a> Parser<'a> { (args, variadic) } - // parse the argument list and result type of a function declaration + /// Parse the argument list and result type of a function declaration pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> { let (args, variadic) = self.parse_fn_args(true, allow_variadic); @@ -3712,17 +3767,22 @@ impl<'a> Parser<'a> { } } - fn expect_self_ident(&mut self) { - if !self.is_self_ident() { - let token_str = self.this_token_to_str(); - self.fatal(format!("expected `self` but found `{}`", - token_str).as_slice()) + fn expect_self_ident(&mut self) -> ast::Ident { + match self.token { + token::IDENT(id, false) if id.name == special_idents::self_.name => { + self.bump(); + id + }, + _ => { + let token_str = self.this_token_to_string(); + self.fatal(format!("expected `self` but found `{}`", + token_str).as_slice()) + } } - self.bump(); } - // parse the argument list and result type of a function - // that may have a self type. + /// Parse the argument list and result type of a function + /// that may have a self type. fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg) -> (ExplicitSelf, P<FnDecl>) { fn maybe_parse_borrowed_explicit_self(this: &mut Parser) @@ -3738,24 +3798,21 @@ impl<'a> Parser<'a> { if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) { this.bump(); - this.expect_self_ident(); - SelfRegion(None, MutImmutable) + SelfRegion(None, MutImmutable, this.expect_self_ident()) } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) && this.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) { this.bump(); let mutability = this.parse_mutability(); - this.expect_self_ident(); - SelfRegion(None, mutability) + SelfRegion(None, mutability, this.expect_self_ident()) } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) && this.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) { this.bump(); let lifetime = this.parse_lifetime(); - this.expect_self_ident(); - SelfRegion(Some(lifetime), MutImmutable) + SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident()) } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) && this.look_ahead(2, |t| { Parser::token_is_mutability(t) @@ -3765,8 +3822,7 @@ impl<'a> Parser<'a> { this.bump(); let lifetime = this.parse_lifetime(); let mutability = this.parse_mutability(); - this.expect_self_ident(); - SelfRegion(Some(lifetime), mutability) + SelfRegion(Some(lifetime), mutability, this.expect_self_ident()) } else { SelfStatic } @@ -3786,15 +3842,13 @@ impl<'a> Parser<'a> { // We need to make sure it isn't a type if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) { self.bump(); - self.expect_self_ident(); - SelfUniq + SelfUniq(self.expect_self_ident()) } else { SelfStatic } } token::IDENT(..) if self.is_self_ident() => { - self.bump(); - SelfValue + SelfValue(self.expect_self_ident()) } token::BINOP(token::STAR) => { // Possibly "*self" or "*mut self" -- not supported. Try to avoid @@ -3808,29 +3862,32 @@ impl<'a> Parser<'a> { self.span_err(span, "cannot pass self by unsafe pointer"); self.bump(); } - SelfValue + // error case, making bogus self ident: + SelfValue(special_idents::self_) } _ if Parser::token_is_mutability(&self.token) && self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => { mutbl_self = self.parse_mutability(); - self.expect_self_ident(); - SelfValue + SelfValue(self.expect_self_ident()) } _ if Parser::token_is_mutability(&self.token) && self.look_ahead(1, |t| *t == token::TILDE) && self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => { mutbl_self = self.parse_mutability(); self.bump(); - self.expect_self_ident(); - SelfUniq + SelfUniq(self.expect_self_ident()) } _ => SelfStatic }; let explicit_self_sp = mk_sp(lo, self.span.hi); - // If we parsed a self type, expect a comma before the argument list. - let fn_inputs = if explicit_self != SelfStatic { + // shared fall-through for the three cases below. borrowing prevents simply + // writing this as a closure + macro_rules! parse_remaining_arguments { + ($self_id:ident) => + { + // If we parsed a self type, expect a comma before the argument list. match self.token { token::COMMA => { self.bump(); @@ -3840,23 +3897,33 @@ impl<'a> Parser<'a> { sep, parse_arg_fn ); - fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self)); + fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id)); fn_inputs } token::RPAREN => { - vec!(Arg::new_self(explicit_self_sp, mutbl_self)) + vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id)) } _ => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("expected `,` or `)`, found `{}`", token_str).as_slice()) } } - } else { - let sep = seq_sep_trailing_disallowed(token::COMMA); - self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn) + } + } + + let fn_inputs = match explicit_self { + SelfStatic => { + let sep = seq_sep_trailing_disallowed(token::COMMA); + self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn) + } + SelfValue(id) => parse_remaining_arguments!(id), + SelfRegion(_,_,id) => parse_remaining_arguments!(id), + SelfUniq(id) => parse_remaining_arguments!(id) + }; + self.expect(&token::RPAREN); let hi = self.span.hi; @@ -3873,7 +3940,7 @@ impl<'a> Parser<'a> { (spanned(lo, hi, explicit_self), fn_decl) } - // parse the |arg, arg| header on a lambda + /// Parse the |arg, arg| header on a lambda fn parse_fn_block_decl(&mut self) -> P<FnDecl> { let inputs_captures = { if self.eat(&token::OROR) { @@ -3905,7 +3972,7 @@ impl<'a> Parser<'a> { }) } - // Parses the `(arg, arg) -> return_type` header on a procedure. + /// Parses the `(arg, arg) -> return_type` header on a procedure. fn parse_proc_decl(&mut self) -> P<FnDecl> { let inputs = self.parse_unspanned_seq(&token::LPAREN, @@ -3931,7 +3998,7 @@ impl<'a> Parser<'a> { }) } - // parse the name and optional generic types of a function header. + /// Parse the name and optional generic types of a function header. fn parse_fn_header(&mut self) -> (Ident, ast::Generics) { let id = self.parse_ident(); let generics = self.parse_generics(); @@ -3951,7 +4018,7 @@ impl<'a> Parser<'a> { } } - // parse an item-position function declaration. + /// Parse an item-position function declaration. fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo { let (ident, generics) = self.parse_fn_header(); let decl = self.parse_fn_decl(false); @@ -3959,7 +4026,7 @@ impl<'a> Parser<'a> { (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs)) } - // parse a method in a trait impl, starting with `attrs` attributes. + /// Parse a method in a trait impl, starting with `attrs` attributes. fn parse_method(&mut self, already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> { let next_attrs = self.parse_outer_attributes(); @@ -3995,7 +4062,7 @@ impl<'a> Parser<'a> { } } - // parse trait Foo { ... } + /// Parse trait Foo { ... } fn parse_item_trait(&mut self) -> ItemInfo { let ident = self.parse_ident(); let tps = self.parse_generics(); @@ -4014,9 +4081,9 @@ impl<'a> Parser<'a> { (ident, ItemTrait(tps, sized, traits, meths), None) } - // Parses two variants (with the region/type params always optional): - // impl<T> Foo { ... } - // impl<T> ToStr for ~[T] { ... } + /// Parses two variants (with the region/type params always optional): + /// impl<T> Foo { ... } + /// impl<T> ToString for ~[T] { ... } fn parse_item_impl(&mut self) -> ItemInfo { // First, parse type parameters if necessary. let generics = self.parse_generics(); @@ -4069,7 +4136,7 @@ impl<'a> Parser<'a> { (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs)) } - // parse a::B<String,int> + /// Parse a::B<String,int> fn parse_trait_ref(&mut self) -> TraitRef { ast::TraitRef { path: self.parse_path(LifetimeAndTypesWithoutColons).path, @@ -4077,7 +4144,7 @@ impl<'a> Parser<'a> { } } - // parse B + C<String,int> + D + /// Parse B + C<String,int> + D fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> { self.parse_seq_to_before_end( ket, @@ -4086,7 +4153,7 @@ impl<'a> Parser<'a> { ) } - // parse struct Foo { ... } + /// Parse struct Foo { ... } fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo { let class_name = self.parse_ident(); let generics = self.parse_generics(); @@ -4151,7 +4218,7 @@ impl<'a> Parser<'a> { is_tuple_like = true; fields = Vec::new(); } else { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, `(`, or `;` after struct \ name but found `{}`", "{", token_str).as_slice()) @@ -4169,7 +4236,7 @@ impl<'a> Parser<'a> { None) } - // parse a structure field declaration + /// Parse a structure field declaration pub fn parse_single_struct_field(&mut self, vis: Visibility, attrs: Vec<Attribute> ) @@ -4182,7 +4249,7 @@ impl<'a> Parser<'a> { token::RBRACE => {} _ => { let span = self.span; - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected `,`, or `}}` but found `{}`", token_str).as_slice()) @@ -4191,7 +4258,7 @@ impl<'a> Parser<'a> { a_var } - // parse an element of a struct definition + /// Parse an element of a struct definition fn parse_struct_decl_field(&mut self) -> StructField { let attrs = self.parse_outer_attributes(); @@ -4203,32 +4270,30 @@ impl<'a> Parser<'a> { return self.parse_single_struct_field(Inherited, attrs); } - // parse visiility: PUB, PRIV, or nothing + /// Parse visiility: PUB, PRIV, or nothing fn parse_visibility(&mut self) -> Visibility { if self.eat_keyword(keywords::Pub) { Public } else { Inherited } } - fn parse_sized(&mut self) -> Sized { - if self.eat_keyword(keywords::Type) { DynSize } - else { StaticSize } - } - - fn parse_for_sized(&mut self) -> Sized { + fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> { if self.eat_keyword(keywords::For) { - if !self.eat_keyword(keywords::Type) { - let last_span = self.last_span; - self.span_err(last_span, - "expected 'type' after for in trait item"); + let span = self.span; + let ident = self.parse_ident(); + if !self.eat(&token::QUESTION) { + self.span_err(span, + "expected 'Sized?' after `for` in trait item"); + return None; } - DynSize + let tref = Parser::trait_ref_from_ident(ident, span); + Some(TraitTyParamBound(tref)) } else { - StaticSize + None } } - // given a termination token and a vector of already-parsed - // attributes (of length 0 or 1), parse all of the items in a module + /// Given a termination token and a vector of already-parsed + /// attributes (of length 0 or 1), parse all of the items in a module fn parse_mod_items(&mut self, term: token::Token, first_item_attrs: Vec<Attribute>, @@ -4265,7 +4330,7 @@ impl<'a> Parser<'a> { the module"); } _ => { - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.fatal(format!("expected item but found `{}`", token_str).as_slice()) } @@ -4296,7 +4361,7 @@ impl<'a> Parser<'a> { (id, ItemStatic(ty, m, e), None) } - // parse a `mod <foo> { ... }` or `mod <foo>;` item + /// Parse a `mod <foo> { ... }` or `mod <foo>;` item fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo { let id_span = self.span; let id = self.parse_ident(); @@ -4334,7 +4399,7 @@ impl<'a> Parser<'a> { self.mod_path_stack.pop().unwrap(); } - // read a module from a source file. + /// Read a module from a source file. fn eval_src_mod(&mut self, id: ast::Ident, outer_attrs: &[ast::Attribute], @@ -4442,7 +4507,7 @@ impl<'a> Parser<'a> { return (ast::ItemMod(m0), mod_attrs); } - // parse a function declaration from a foreign module + /// Parse a function declaration from a foreign module fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, attrs: Vec<Attribute>) -> Gc<ForeignItem> { let lo = self.span.lo; @@ -4460,7 +4525,7 @@ impl<'a> Parser<'a> { vis: vis } } - // parse a static item from a foreign module + /// Parse a static item from a foreign module fn parse_item_foreign_static(&mut self, vis: ast::Visibility, attrs: Vec<Attribute> ) -> Gc<ForeignItem> { let lo = self.span.lo; @@ -4483,7 +4548,7 @@ impl<'a> Parser<'a> { } } - // parse safe/unsafe and fn + /// Parse safe/unsafe and fn fn parse_fn_style(&mut self) -> FnStyle { if self.eat_keyword(keywords::Fn) { NormalFn } else if self.eat_keyword(keywords::Unsafe) { @@ -4494,8 +4559,8 @@ impl<'a> Parser<'a> { } - // at this point, this is essentially a wrapper for - // parse_foreign_items. + /// At this point, this is essentially a wrapper for + /// parse_foreign_items. fn parse_foreign_mod_items(&mut self, abi: abi::Abi, first_item_attrs: Vec<Attribute> ) @@ -4545,7 +4610,7 @@ impl<'a> Parser<'a> { } _ => { let span = self.span; - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected extern crate name but \ found `{}`", @@ -4596,7 +4661,7 @@ impl<'a> Parser<'a> { return IoviItem(item); } - // parse type Foo = Bar; + /// Parse type Foo = Bar; fn parse_item_type(&mut self) -> ItemInfo { let ident = self.parse_ident(); let tps = self.parse_generics(); @@ -4606,8 +4671,8 @@ impl<'a> Parser<'a> { (ident, ItemTy(ty, tps), None) } - // parse a structure-like enum variant definition - // this should probably be renamed or refactored... + /// Parse a structure-like enum variant definition + /// this should probably be renamed or refactored... fn parse_struct_def(&mut self) -> Gc<StructDef> { let mut fields: Vec<StructField> = Vec::new(); while self.token != token::RBRACE { @@ -4623,7 +4688,7 @@ impl<'a> Parser<'a> { }; } - // parse the part of an "enum" decl following the '{' + /// Parse the part of an "enum" decl following the '{' fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef { let mut variants = Vec::new(); let mut all_nullary = true; @@ -4687,7 +4752,7 @@ impl<'a> Parser<'a> { ast::EnumDef { variants: variants } } - // parse an "enum" declaration + /// Parse an "enum" declaration fn parse_item_enum(&mut self) -> ItemInfo { let id = self.parse_ident(); let generics = self.parse_generics(); @@ -4704,14 +4769,13 @@ impl<'a> Parser<'a> { } } - // Parses a string as an ABI spec on an extern type or module. Consumes - // the `extern` keyword, if one is found. + /// Parses a string as an ABI spec on an extern type or module. Consumes + /// the `extern` keyword, if one is found. fn parse_opt_abi(&mut self) -> Option<abi::Abi> { match self.token { token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => { self.bump(); - let identifier_string = token::get_ident(s); - let the_string = identifier_string.get(); + let the_string = s.as_str(); match abi::lookup(the_string) { Some(abi) => Some(abi), None => { @@ -4731,10 +4795,10 @@ impl<'a> Parser<'a> { } } - // parse one of the items or view items allowed by the - // flags; on failure, return IoviNone. - // NB: this function no longer parses the items inside an - // extern crate. + /// Parse one of the items or view items allowed by the + /// flags; on failure, return IoviNone. + /// NB: this function no longer parses the items inside an + /// extern crate. fn parse_item_or_view_item(&mut self, attrs: Vec<Attribute> , macros_allowed: bool) @@ -4803,7 +4867,7 @@ impl<'a> Parser<'a> { } let span = self.span; - let token_str = self.this_token_to_str(); + let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected `{}` or `fn` but found `{}`", "{", token_str).as_slice()); @@ -4942,7 +5006,7 @@ impl<'a> Parser<'a> { self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } - // parse a foreign item; on failure, return IoviNone. + /// Parse a foreign item; on failure, return IoviNone. fn parse_foreign_item(&mut self, attrs: Vec<Attribute> , macros_allowed: bool) @@ -4965,7 +5029,7 @@ impl<'a> Parser<'a> { self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } - // this is the fall-through for parsing items. + /// This is the fall-through for parsing items. fn parse_macro_use_or_failure( &mut self, attrs: Vec<Attribute> , @@ -5049,17 +5113,17 @@ impl<'a> Parser<'a> { } } - // parse, e.g., "use a::b::{z,y}" + /// Parse, e.g., "use a::b::{z,y}" fn parse_use(&mut self) -> ViewItem_ { return ViewItemUse(self.parse_view_path()); } - // matches view_path : MOD? IDENT EQ non_global_path - // | MOD? non_global_path MOD_SEP LBRACE RBRACE - // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE - // | MOD? non_global_path MOD_SEP STAR - // | MOD? non_global_path + /// Matches view_path : MOD? IDENT EQ non_global_path + /// | MOD? non_global_path MOD_SEP LBRACE RBRACE + /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE + /// | MOD? non_global_path MOD_SEP STAR + /// | MOD? non_global_path fn parse_view_path(&mut self) -> Gc<ViewPath> { let lo = self.span.lo; @@ -5182,10 +5246,10 @@ impl<'a> Parser<'a> { ViewPathSimple(last, path, ast::DUMMY_NODE_ID)); } - // Parses a sequence of items. Stops when it finds program - // text that can't be parsed as an item - // - mod_items uses extern_mod_allowed = true - // - block_tail_ uses extern_mod_allowed = false + /// Parses a sequence of items. Stops when it finds program + /// text that can't be parsed as an item + /// - mod_items uses extern_mod_allowed = true + /// - block_tail_ uses extern_mod_allowed = false fn parse_items_and_view_items(&mut self, first_item_attrs: Vec<Attribute> , mut extern_mod_allowed: bool, @@ -5267,8 +5331,8 @@ impl<'a> Parser<'a> { } } - // Parses a sequence of foreign items. Stops when it finds program - // text that can't be parsed as an item + /// Parses a sequence of foreign items. Stops when it finds program + /// text that can't be parsed as an item fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> , macros_allowed: bool) -> ParsedItemsAndViewItems { @@ -5307,8 +5371,8 @@ impl<'a> Parser<'a> { } } - // Parses a source module as a crate. This is the main - // entry point for the parser. + /// Parses a source module as a crate. This is the main + /// entry point for the parser. pub fn parse_crate_mod(&mut self) -> Crate { let lo = self.span.lo; // parse the crate's inner attrs, maybe (oops) one @@ -5329,9 +5393,9 @@ impl<'a> Parser<'a> { pub fn parse_optional_str(&mut self) -> Option<(InternedString, ast::StrStyle)> { let (s, style) = match self.token { - token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr), + token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr), token::LIT_STR_RAW(s, n) => { - (self.id_to_interned_str(s), ast::RawStr(n)) + (self.id_to_interned_str(s.ident()), ast::RawStr(n)) } _ => return None }; @@ -5346,3 +5410,4 @@ impl<'a> Parser<'a> { } } } + diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index dcf37e37ff0..5839df67022 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -10,7 +10,6 @@ use ast; use ast::{P, Ident, Name, Mrk}; -use ast_util; use ext::mtwt; use parse::token; use util::interner::{RcStr, StrInterner}; @@ -76,32 +75,40 @@ pub enum Token { RBRACE, POUND, DOLLAR, + QUESTION, /* Literals */ - LIT_BYTE(u8), - LIT_CHAR(char), - LIT_INT(i64, ast::IntTy), - LIT_UINT(u64, ast::UintTy), - LIT_INT_UNSUFFIXED(i64), - LIT_FLOAT(ast::Ident, ast::FloatTy), - LIT_FLOAT_UNSUFFIXED(ast::Ident), - LIT_STR(ast::Ident), - LIT_STR_RAW(ast::Ident, uint), /* raw str delimited by n hash symbols */ - LIT_BINARY(Rc<Vec<u8>>), - LIT_BINARY_RAW(Rc<Vec<u8>>, uint), /* raw binary str delimited by n hash symbols */ + LIT_BYTE(Name), + LIT_CHAR(Name), + LIT_INTEGER(Name), + LIT_FLOAT(Name), + LIT_STR(Name), + LIT_STR_RAW(Name, uint), /* raw str delimited by n hash symbols */ + LIT_BINARY(Name), + LIT_BINARY_RAW(Name, uint), /* raw binary str delimited by n hash symbols */ /* Name components */ - // an identifier contains an "is_mod_name" boolean, - // indicating whether :: follows this token with no - // whitespace in between. - IDENT(ast::Ident, bool), + /// An identifier contains an "is_mod_name" boolean, + /// indicating whether :: follows this token with no + /// whitespace in between. + IDENT(Ident, bool), UNDERSCORE, - LIFETIME(ast::Ident), + LIFETIME(Ident), /* For interpolation */ INTERPOLATED(Nonterminal), + DOC_COMMENT(Name), + + // Junk. These carry no data because we don't really care about the data + // they *would* carry, and don't really want to allocate a new ident for + // them. Instead, users could extract that from the associated span. + + /// Whitespace + WS, + /// Comment + COMMENT, + SHEBANG(Name), - DOC_COMMENT(ast::Ident), EOF, } @@ -114,11 +121,12 @@ pub enum Nonterminal { NtPat( Gc<ast::Pat>), NtExpr(Gc<ast::Expr>), NtTy( P<ast::Ty>), - // see IDENT, above, for meaning of bool in NtIdent: - NtIdent(Box<ast::Ident>, bool), - NtMeta(Gc<ast::MetaItem>), // stuff inside brackets for attributes + /// See IDENT, above, for meaning of bool in NtIdent: + NtIdent(Box<Ident>, bool), + /// Stuff inside brackets for attributes + NtMeta(Gc<ast::MetaItem>), NtPath(Box<ast::Path>), - NtTT( Gc<ast::TokenTree>), // needs @ed to break a circularity + NtTT( Gc<ast::TokenTree>), // needs Gc'd to break a circularity NtMatchers(Vec<ast::Matcher> ) } @@ -140,7 +148,7 @@ impl fmt::Show for Nonterminal { } } -pub fn binop_to_str(o: BinOp) -> &'static str { +pub fn binop_to_string(o: BinOp) -> &'static str { match o { PLUS => "+", MINUS => "-", @@ -155,7 +163,7 @@ pub fn binop_to_str(o: BinOp) -> &'static str { } } -pub fn to_str(t: &Token) -> String { +pub fn to_string(t: &Token) -> String { match *t { EQ => "=".to_string(), LT => "<".to_string(), @@ -168,9 +176,9 @@ pub fn to_str(t: &Token) -> String { TILDE => "~".to_string(), OROR => "||".to_string(), ANDAND => "&&".to_string(), - BINOP(op) => binop_to_str(op).to_string(), + BINOP(op) => binop_to_string(op).to_string(), BINOPEQ(op) => { - let mut s = binop_to_str(op).to_string(); + let mut s = binop_to_string(op).to_string(); s.push_str("="); s } @@ -195,57 +203,32 @@ pub fn to_str(t: &Token) -> String { RBRACE => "}".to_string(), POUND => "#".to_string(), DOLLAR => "$".to_string(), + QUESTION => "?".to_string(), /* Literals */ LIT_BYTE(b) => { - let mut res = String::from_str("b'"); - (b as char).escape_default(|c| { - res.push_char(c); - }); - res.push_char('\''); - res + format!("b'{}'", b.as_str()) } LIT_CHAR(c) => { - let mut res = String::from_str("'"); - c.escape_default(|c| { - res.push_char(c); - }); - res.push_char('\''); - res - } - LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)), - LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)), - LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() } - LIT_FLOAT(s, t) => { - let mut body = String::from_str(get_ident(s).get()); - if body.as_slice().ends_with(".") { - body.push_char('0'); // `10.f` is not a float literal - } - body.push_str(ast_util::float_ty_to_str(t).as_slice()); - body + format!("'{}'", c.as_str()) } - LIT_FLOAT_UNSUFFIXED(s) => { - let mut body = String::from_str(get_ident(s).get()); - if body.as_slice().ends_with(".") { - body.push_char('0'); // `10.f` is not a float literal - } - body + LIT_INTEGER(c) | LIT_FLOAT(c) => { + c.as_str().to_string() } + LIT_STR(s) => { - format!("\"{}\"", get_ident(s).get().escape_default()) + format!("\"{}\"", s.as_str()) } LIT_STR_RAW(s, n) => { format!("r{delim}\"{string}\"{delim}", - delim="#".repeat(n), string=get_ident(s)) + delim="#".repeat(n), string=s.as_str()) } - LIT_BINARY(ref v) => { - format!( - "b\"{}\"", - v.iter().map(|&b| b as char).collect::<String>().escape_default()) + LIT_BINARY(v) => { + format!("b\"{}\"", v.as_str()) } - LIT_BINARY_RAW(ref s, n) => { + LIT_BINARY_RAW(s, n) => { format!("br{delim}\"{string}\"{delim}", - delim="#".repeat(n), string=s.as_slice().to_ascii().as_str_ascii()) + delim="#".repeat(n), string=s.as_str()) } /* Name components */ @@ -256,12 +239,16 @@ pub fn to_str(t: &Token) -> String { UNDERSCORE => "_".to_string(), /* Other */ - DOC_COMMENT(s) => get_ident(s).get().to_string(), + DOC_COMMENT(s) => s.as_str().to_string(), EOF => "<eof>".to_string(), + WS => " ".to_string(), + COMMENT => "/* */".to_string(), + SHEBANG(s) => format!("/* shebang: {}*/", s.as_str()), + INTERPOLATED(ref nt) => { match nt { - &NtExpr(ref e) => ::print::pprust::expr_to_str(&**e), - &NtMeta(ref e) => ::print::pprust::meta_item_to_str(&**e), + &NtExpr(ref e) => ::print::pprust::expr_to_string(&**e), + &NtMeta(ref e) => ::print::pprust::meta_item_to_string(&**e), _ => { let mut s = "an interpolated ".to_string(); match *nt { @@ -294,11 +281,8 @@ pub fn can_begin_expr(t: &Token) -> bool { TILDE => true, LIT_BYTE(_) => true, LIT_CHAR(_) => true, - LIT_INT(_, _) => true, - LIT_UINT(_, _) => true, - LIT_INT_UNSUFFIXED(_) => true, - LIT_FLOAT(_, _) => true, - LIT_FLOAT_UNSUFFIXED(_) => true, + LIT_INTEGER(_) => true, + LIT_FLOAT(_) => true, LIT_STR(_) => true, LIT_STR_RAW(_, _) => true, LIT_BINARY(_) => true, @@ -335,11 +319,8 @@ pub fn is_lit(t: &Token) -> bool { match *t { LIT_BYTE(_) => true, LIT_CHAR(_) => true, - LIT_INT(_, _) => true, - LIT_UINT(_, _) => true, - LIT_INT_UNSUFFIXED(_) => true, - LIT_FLOAT(_, _) => true, - LIT_FLOAT_UNSUFFIXED(_) => true, + LIT_INTEGER(_) => true, + LIT_FLOAT(_) => true, LIT_STR(_) => true, LIT_STR_RAW(_, _) => true, LIT_BINARY(_) => true, @@ -363,10 +344,6 @@ pub fn is_plain_ident(t: &Token) -> bool { match *t { IDENT(_, false) => true, _ => false } } -pub fn is_bar(t: &Token) -> bool { - match *t { BINOP(OR) | OROR => true, _ => false } -} - // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) @@ -397,14 +374,19 @@ macro_rules! declare_special_idents_and_keywords {( $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { - static STRICT_KEYWORD_START: Name = first!($( $sk_name, )*); - static STRICT_KEYWORD_FINAL: Name = last!($( $sk_name, )*); - static RESERVED_KEYWORD_START: Name = first!($( $rk_name, )*); - static RESERVED_KEYWORD_FINAL: Name = last!($( $rk_name, )*); + static STRICT_KEYWORD_START: Name = first!($( Name($sk_name), )*); + static STRICT_KEYWORD_FINAL: Name = last!($( Name($sk_name), )*); + static RESERVED_KEYWORD_START: Name = first!($( Name($rk_name), )*); + static RESERVED_KEYWORD_FINAL: Name = last!($( Name($rk_name), )*); pub mod special_idents { - use ast::Ident; - $( pub static $si_static: Ident = Ident { name: $si_name, ctxt: 0 }; )* + use ast::{Ident, Name}; + $( pub static $si_static: Ident = Ident { name: Name($si_name), ctxt: 0 }; )* + } + + pub mod special_names { + use ast::Name; + $( pub static $si_static: Name = Name($si_name); )* } /** @@ -415,7 +397,7 @@ macro_rules! declare_special_idents_and_keywords {( * the language and may not appear as identifiers. */ pub mod keywords { - use ast::Ident; + use ast::Name; pub enum Keyword { $( $sk_variant, )* @@ -423,10 +405,10 @@ macro_rules! declare_special_idents_and_keywords {( } impl Keyword { - pub fn to_ident(&self) -> Ident { + pub fn to_name(&self) -> Name { match *self { - $( $sk_variant => Ident { name: $sk_name, ctxt: 0 }, )* - $( $rk_variant => Ident { name: $rk_name, ctxt: 0 }, )* + $( $sk_variant => Name($sk_name), )* + $( $rk_variant => Name($rk_name), )* } } } @@ -434,7 +416,7 @@ macro_rules! declare_special_idents_and_keywords {( fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in - // special_idents, in Keyword to_ident(), and in static + // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* @@ -445,8 +427,11 @@ macro_rules! declare_special_idents_and_keywords {( }} // If the special idents get renumbered, remember to modify these two as appropriate -static SELF_KEYWORD_NAME: Name = 1; -static STATIC_KEYWORD_NAME: Name = 2; +pub static SELF_KEYWORD_NAME: Name = Name(SELF_KEYWORD_NAME_NUM); +static STATIC_KEYWORD_NAME: Name = Name(STATIC_KEYWORD_NAME_NUM); + +pub static SELF_KEYWORD_NAME_NUM: u32 = 1; +static STATIC_KEYWORD_NAME_NUM: u32 = 2; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max @@ -456,8 +441,8 @@ declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); - (super::SELF_KEYWORD_NAME, self_, "self"); - (super::STATIC_KEYWORD_NAME, statik, "static"); + (super::SELF_KEYWORD_NAME_NUM, self_, "self"); + (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (3, static_lifetime, "'static"); // for matcher NTs @@ -497,8 +482,8 @@ declare_special_idents_and_keywords! { (29, Ref, "ref"); (30, Return, "return"); // Static and Self are also special idents (prefill de-dupes) - (super::STATIC_KEYWORD_NAME, Static, "static"); - (super::SELF_KEYWORD_NAME, Self, "self"); + (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); + (super::SELF_KEYWORD_NAME_NUM, Self, "self"); (31, Struct, "struct"); (32, Super, "super"); (33, True, "true"); @@ -680,49 +665,52 @@ pub fn gensym(s: &str) -> Name { /// Maps a string to an identifier with an empty syntax context. #[inline] -pub fn str_to_ident(s: &str) -> ast::Ident { - ast::Ident::new(intern(s)) +pub fn str_to_ident(s: &str) -> Ident { + Ident::new(intern(s)) } /// Maps a string to a gensym'ed identifier. #[inline] -pub fn gensym_ident(s: &str) -> ast::Ident { - ast::Ident::new(gensym(s)) +pub fn gensym_ident(s: &str) -> Ident { + Ident::new(gensym(s)) } // create a fresh name that maps to the same string as the old one. -// note that this guarantees that str_ptr_eq(ident_to_str(src),interner_get(fresh_name(src))); +// note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src))); // that is, that the new name and the old one are connected to ptr_eq strings. -pub fn fresh_name(src: &ast::Ident) -> Name { +pub fn fresh_name(src: &Ident) -> Name { let interner = get_ident_interner(); interner.gensym_copy(src.name) // following: debug version. Could work in final except that it's incompatible with // good error messages and uses of struct names in ambiguous could-be-binding // locations. Also definitely destroys the guarantee given above about ptr_eq. /*let num = rand::task_rng().gen_uint_range(0,0xffff); - gensym(format!("{}_{}",ident_to_str(src),num))*/ + gensym(format!("{}_{}",ident_to_string(src),num))*/ } // create a fresh mark. pub fn fresh_mark() -> Mrk { - gensym("mark") + gensym("mark").uint() as u32 } // See the macro above about the types of keywords pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool { match *tok { - token::IDENT(sid, false) => { kw.to_ident().name == sid.name } + token::IDENT(sid, false) => { kw.to_name() == sid.name } _ => { false } } } pub fn is_any_keyword(tok: &Token) -> bool { match *tok { - token::IDENT(sid, false) => match sid.name { - SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME | - STRICT_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true, - _ => false, + token::IDENT(sid, false) => { + let n = sid.name; + + n == SELF_KEYWORD_NAME + || n == STATIC_KEYWORD_NAME + || STRICT_KEYWORD_START <= n + && n <= RESERVED_KEYWORD_FINAL }, _ => false } @@ -730,10 +718,13 @@ pub fn is_any_keyword(tok: &Token) -> bool { pub fn is_strict_keyword(tok: &Token) -> bool { match *tok { - token::IDENT(sid, false) => match sid.name { - SELF_KEYWORD_NAME | STATIC_KEYWORD_NAME | - STRICT_KEYWORD_START .. STRICT_KEYWORD_FINAL => true, - _ => false, + token::IDENT(sid, false) => { + let n = sid.name; + + n == SELF_KEYWORD_NAME + || n == STATIC_KEYWORD_NAME + || STRICT_KEYWORD_START <= n + && n <= STRICT_KEYWORD_FINAL }, _ => false, } @@ -741,9 +732,11 @@ pub fn is_strict_keyword(tok: &Token) -> bool { pub fn is_reserved_keyword(tok: &Token) -> bool { match *tok { - token::IDENT(sid, false) => match sid.name { - RESERVED_KEYWORD_START .. RESERVED_KEYWORD_FINAL => true, - _ => false, + token::IDENT(sid, false) => { + let n = sid.name; + + RESERVED_KEYWORD_START <= n + && n <= RESERVED_KEYWORD_FINAL }, _ => false, } @@ -765,7 +758,7 @@ mod test { use ext::mtwt; fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident { - ast::Ident{name:id.name,ctxt:mtwt::apply_mark(m,id.ctxt)} + ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) } } #[test] fn mtwt_token_eq_test() { diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 24ab4b38e54..fe84eeff4f8 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -8,58 +8,56 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/* - * This pretty-printer is a direct reimplementation of Philip Karlton's - * Mesa pretty-printer, as described in appendix A of - * - * STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen. - * Stanford Department of Computer Science, 1979. - * - * The algorithm's aim is to break a stream into as few lines as possible - * while respecting the indentation-consistency requirements of the enclosing - * block, and avoiding breaking at silly places on block boundaries, for - * example, between "x" and ")" in "x)". - * - * I am implementing this algorithm because it comes with 20 pages of - * documentation explaining its theory, and because it addresses the set of - * concerns I've seen other pretty-printers fall down on. Weirdly. Even though - * it's 32 years old. What can I say? - * - * Despite some redundancies and quirks in the way it's implemented in that - * paper, I've opted to keep the implementation here as similar as I can, - * changing only what was blatantly wrong, a typo, or sufficiently - * non-idiomatic rust that it really stuck out. - * - * In particular you'll see a certain amount of churn related to INTEGER vs. - * CARDINAL in the Mesa implementation. Mesa apparently interconverts the two - * somewhat readily? In any case, I've used uint for indices-in-buffers and - * ints for character-sizes-and-indentation-offsets. This respects the need - * for ints to "go negative" while carrying a pending-calculation balance, and - * helps differentiate all the numbers flying around internally (slightly). - * - * I also inverted the indentation arithmetic used in the print stack, since - * the Mesa implementation (somewhat randomly) stores the offset on the print - * stack in terms of margin-col rather than col itself. I store col. - * - * I also implemented a small change in the String token, in that I store an - * explicit length for the string. For most tokens this is just the length of - * the accompanying string. But it's necessary to permit it to differ, for - * encoding things that are supposed to "go on their own line" -- certain - * classes of comment and blank-line -- where relying on adjacent - * hardbreak-like Break tokens with long blankness indication doesn't actually - * work. To see why, consider when there is a "thing that should be on its own - * line" between two long blocks, say functions. If you put a hardbreak after - * each function (or before each) and the breaking algorithm decides to break - * there anyways (because the functions themselves are long) you wind up with - * extra blank lines. If you don't put hardbreaks you can wind up with the - * "thing which should be on its own line" not getting its own line in the - * rare case of "really small functions" or such. This re-occurs with comments - * and explicit blank lines. So in those cases we use a string with a payload - * we want isolated to a line and an explicit length that's huge, surrounded - * by two zero-length breaks. The algorithm will try its best to fit it on a - * line (which it can't) and so naturally place the content on its own line to - * avoid combining it with other lines and making matters even worse. - */ +//! This pretty-printer is a direct reimplementation of Philip Karlton's +//! Mesa pretty-printer, as described in appendix A of +//! +//! STAN-CS-79-770: "Pretty Printing", by Derek C. Oppen. +//! Stanford Department of Computer Science, 1979. +//! +//! The algorithm's aim is to break a stream into as few lines as possible +//! while respecting the indentation-consistency requirements of the enclosing +//! block, and avoiding breaking at silly places on block boundaries, for +//! example, between "x" and ")" in "x)". +//! +//! I am implementing this algorithm because it comes with 20 pages of +//! documentation explaining its theory, and because it addresses the set of +//! concerns I've seen other pretty-printers fall down on. Weirdly. Even though +//! it's 32 years old. What can I say? +//! +//! Despite some redundancies and quirks in the way it's implemented in that +//! paper, I've opted to keep the implementation here as similar as I can, +//! changing only what was blatantly wrong, a typo, or sufficiently +//! non-idiomatic rust that it really stuck out. +//! +//! In particular you'll see a certain amount of churn related to INTEGER vs. +//! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two +//! somewhat readily? In any case, I've used uint for indices-in-buffers and +//! ints for character-sizes-and-indentation-offsets. This respects the need +//! for ints to "go negative" while carrying a pending-calculation balance, and +//! helps differentiate all the numbers flying around internally (slightly). +//! +//! I also inverted the indentation arithmetic used in the print stack, since +//! the Mesa implementation (somewhat randomly) stores the offset on the print +//! stack in terms of margin-col rather than col itself. I store col. +//! +//! I also implemented a small change in the String token, in that I store an +//! explicit length for the string. For most tokens this is just the length of +//! the accompanying string. But it's necessary to permit it to differ, for +//! encoding things that are supposed to "go on their own line" -- certain +//! classes of comment and blank-line -- where relying on adjacent +//! hardbreak-like Break tokens with long blankness indication doesn't actually +//! work. To see why, consider when there is a "thing that should be on its own +//! line" between two long blocks, say functions. If you put a hardbreak after +//! each function (or before each) and the breaking algorithm decides to break +//! there anyways (because the functions themselves are long) you wind up with +//! extra blank lines. If you don't put hardbreaks you can wind up with the +//! "thing which should be on its own line" not getting its own line in the +//! rare case of "really small functions" or such. This re-occurs with comments +//! and explicit blank lines. So in those cases we use a string with a payload +//! we want isolated to a line and an explicit length that's huge, surrounded +//! by two zero-length breaks. The algorithm will try its best to fit it on a +//! line (which it can't) and so naturally place the content on its own line to +//! avoid combining it with other lines and making matters even worse. use std::io; use std::string::String; @@ -186,107 +184,116 @@ pub fn mk_printer(out: Box<io::Writer>, linewidth: uint) -> Printer { } -/* - * In case you do not have the paper, here is an explanation of what's going - * on. - * - * There is a stream of input tokens flowing through this printer. - * - * The printer buffers up to 3N tokens inside itself, where N is linewidth. - * Yes, linewidth is chars and tokens are multi-char, but in the worst - * case every token worth buffering is 1 char long, so it's ok. - * - * Tokens are String, Break, and Begin/End to delimit blocks. - * - * Begin tokens can carry an offset, saying "how far to indent when you break - * inside here", as well as a flag indicating "consistent" or "inconsistent" - * breaking. Consistent breaking means that after the first break, no attempt - * will be made to flow subsequent breaks together onto lines. Inconsistent - * is the opposite. Inconsistent breaking example would be, say: - * - * foo(hello, there, good, friends) - * - * breaking inconsistently to become - * - * foo(hello, there - * good, friends); - * - * whereas a consistent breaking would yield: - * - * foo(hello, - * there - * good, - * friends); - * - * That is, in the consistent-break blocks we value vertical alignment - * more than the ability to cram stuff onto a line. But in all cases if it - * can make a block a one-liner, it'll do so. - * - * Carrying on with high-level logic: - * - * The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and - * 'right' indices denote the active portion of the ring buffer as well as - * describing hypothetical points-in-the-infinite-stream at most 3N tokens - * apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch - * between using 'left' and 'right' terms to denote the wrapepd-to-ring-buffer - * and point-in-infinite-stream senses freely. - * - * There is a parallel ring buffer, 'size', that holds the calculated size of - * each token. Why calculated? Because for Begin/End pairs, the "size" - * includes everything between the pair. That is, the "size" of Begin is - * actually the sum of the sizes of everything between Begin and the paired - * End that follows. Since that is arbitrarily far in the future, 'size' is - * being rewritten regularly while the printer runs; in fact most of the - * machinery is here to work out 'size' entries on the fly (and give up when - * they're so obviously over-long that "infinity" is a good enough - * approximation for purposes of line breaking). - * - * The "input side" of the printer is managed as an abstract process called - * SCAN, which uses 'scan_stack', 'scan_stack_empty', 'top' and 'bottom', to - * manage calculating 'size'. SCAN is, in other words, the process of - * calculating 'size' entries. - * - * The "output side" of the printer is managed by an abstract process called - * PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to - * do with each token/size pair it consumes as it goes. It's trying to consume - * the entire buffered window, but can't output anything until the size is >= - * 0 (sizes are set to negative while they're pending calculation). - * - * So SCAN takes input and buffers tokens and pending calculations, while - * PRINT gobbles up completed calculations and tokens from the buffer. The - * theory is that the two can never get more than 3N tokens apart, because - * once there's "obviously" too much data to fit on a line, in a size - * calculation, SCAN will write "infinity" to the size and let PRINT consume - * it. - * - * In this implementation (following the paper, again) the SCAN process is - * the method called 'pretty_print', and the 'PRINT' process is the method - * called 'print'. - */ +/// In case you do not have the paper, here is an explanation of what's going +/// on. +/// +/// There is a stream of input tokens flowing through this printer. +/// +/// The printer buffers up to 3N tokens inside itself, where N is linewidth. +/// Yes, linewidth is chars and tokens are multi-char, but in the worst +/// case every token worth buffering is 1 char long, so it's ok. +/// +/// Tokens are String, Break, and Begin/End to delimit blocks. +/// +/// Begin tokens can carry an offset, saying "how far to indent when you break +/// inside here", as well as a flag indicating "consistent" or "inconsistent" +/// breaking. Consistent breaking means that after the first break, no attempt +/// will be made to flow subsequent breaks together onto lines. Inconsistent +/// is the opposite. Inconsistent breaking example would be, say: +/// +/// foo(hello, there, good, friends) +/// +/// breaking inconsistently to become +/// +/// foo(hello, there +/// good, friends); +/// +/// whereas a consistent breaking would yield: +/// +/// foo(hello, +/// there +/// good, +/// friends); +/// +/// That is, in the consistent-break blocks we value vertical alignment +/// more than the ability to cram stuff onto a line. But in all cases if it +/// can make a block a one-liner, it'll do so. +/// +/// Carrying on with high-level logic: +/// +/// The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and +/// 'right' indices denote the active portion of the ring buffer as well as +/// describing hypothetical points-in-the-infinite-stream at most 3N tokens +/// apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch +/// between using 'left' and 'right' terms to denote the wrapepd-to-ring-buffer +/// and point-in-infinite-stream senses freely. +/// +/// There is a parallel ring buffer, 'size', that holds the calculated size of +/// each token. Why calculated? Because for Begin/End pairs, the "size" +/// includes everything betwen the pair. That is, the "size" of Begin is +/// actually the sum of the sizes of everything between Begin and the paired +/// End that follows. Since that is arbitrarily far in the future, 'size' is +/// being rewritten regularly while the printer runs; in fact most of the +/// machinery is here to work out 'size' entries on the fly (and give up when +/// they're so obviously over-long that "infinity" is a good enough +/// approximation for purposes of line breaking). +/// +/// The "input side" of the printer is managed as an abstract process called +/// SCAN, which uses 'scan_stack', 'scan_stack_empty', 'top' and 'bottom', to +/// manage calculating 'size'. SCAN is, in other words, the process of +/// calculating 'size' entries. +/// +/// The "output side" of the printer is managed by an abstract process called +/// PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to +/// do with each token/size pair it consumes as it goes. It's trying to consume +/// the entire buffered window, but can't output anything until the size is >= +/// 0 (sizes are set to negative while they're pending calculation). +/// +/// So SCAN takes input and buffers tokens and pending calculations, while +/// PRINT gobbles up completed calculations and tokens from the buffer. The +/// theory is that the two can never get more than 3N tokens apart, because +/// once there's "obviously" too much data to fit on a line, in a size +/// calculation, SCAN will write "infinity" to the size and let PRINT consume +/// it. +/// +/// In this implementation (following the paper, again) the SCAN process is +/// the method called 'pretty_print', and the 'PRINT' process is the method +/// called 'print'. pub struct Printer { pub out: Box<io::Writer>, buf_len: uint, - margin: int, // width of lines we're constrained to - space: int, // number of spaces left on line - left: uint, // index of left side of input stream - right: uint, // index of right side of input stream - token: Vec<Token> , // ring-buffr stream goes through - size: Vec<int> , // ring-buffer of calculated sizes - left_total: int, // running size of stream "...left" - right_total: int, // running size of stream "...right" - // pseudo-stack, really a ring too. Holds the - // primary-ring-buffers index of the Begin that started the - // current block, possibly with the most recent Break after that - // Begin (if there is any) on top of it. Stuff is flushed off the - // bottom as it becomes irrelevant due to the primary ring-buffer - // advancing. + /// Width of lines we're constrained to + margin: int, + /// Number of spaces left on line + space: int, + /// Index of left side of input stream + left: uint, + /// Index of right side of input stream + right: uint, + /// Ring-buffr stream goes through + token: Vec<Token> , + /// Ring-buffer of calculated sizes + size: Vec<int> , + /// Running size of stream "...left" + left_total: int, + /// Running size of stream "...right" + right_total: int, + /// Pseudo-stack, really a ring too. Holds the + /// primary-ring-buffers index of the Begin that started the + /// current block, possibly with the most recent Break after that + /// Begin (if there is any) on top of it. Stuff is flushed off the + /// bottom as it becomes irrelevant due to the primary ring-buffer + /// advancing. scan_stack: Vec<uint> , - scan_stack_empty: bool, // top==bottom disambiguator - top: uint, // index of top of scan_stack - bottom: uint, // index of bottom of scan_stack - // stack of blocks-in-progress being flushed by print + /// Top==bottom disambiguator + scan_stack_empty: bool, + /// Index of top of scan_stack + top: uint, + /// Index of bottom of scan_stack + bottom: uint, + /// Stack of blocks-in-progress being flushed by print print_stack: Vec<PrintStackElem> , - // buffered indentation to avoid writing trailing whitespace + /// Buffered indentation to avoid writing trailing whitespace pending_indentation: int, } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index bf210110829..170cb7a249c 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -88,9 +88,9 @@ pub static indent_unit: uint = 4u; pub static default_columns: uint = 78u; -// Requires you to pass an input filename and reader so that -// it can scan the input text for comments and literals to -// copy forward. +/// Requires you to pass an input filename and reader so that +/// it can scan the input text for comments and literals to +/// copy forward. pub fn print_crate<'a>(cm: &'a CodeMap, span_diagnostic: &diagnostic::SpanHandler, krate: &ast::Crate, @@ -128,6 +128,126 @@ pub fn print_crate<'a>(cm: &'a CodeMap, eof(&mut s.s) } +pub fn to_string(f: |&mut State| -> IoResult<()>) -> String { + let mut s = rust_printer(box MemWriter::new()); + f(&mut s).unwrap(); + eof(&mut s.s).unwrap(); + unsafe { + // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer` + // that we "know" to be a `MemWriter` that works around the lack of checked + // downcasts. + let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out); + let result = + str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap(); + mem::forget(wr); + result.to_string() + } +} + +pub fn ty_to_string(ty: &ast::Ty) -> String { + to_string(|s| s.print_type(ty)) +} + +pub fn pat_to_string(pat: &ast::Pat) -> String { + to_string(|s| s.print_pat(pat)) +} + +pub fn expr_to_string(e: &ast::Expr) -> String { + to_string(|s| s.print_expr(e)) +} + +pub fn lifetime_to_string(e: &ast::Lifetime) -> String { + to_string(|s| s.print_lifetime(e)) +} + +pub fn tt_to_string(tt: &ast::TokenTree) -> String { + to_string(|s| s.print_tt(tt)) +} + +pub fn tts_to_string(tts: &[ast::TokenTree]) -> String { + to_string(|s| s.print_tts(tts)) +} + +pub fn stmt_to_string(stmt: &ast::Stmt) -> String { + to_string(|s| s.print_stmt(stmt)) +} + +pub fn item_to_string(i: &ast::Item) -> String { + to_string(|s| s.print_item(i)) +} + +pub fn generics_to_string(generics: &ast::Generics) -> String { + to_string(|s| s.print_generics(generics)) +} + +pub fn ty_method_to_string(p: &ast::TypeMethod) -> String { + to_string(|s| s.print_ty_method(p)) +} + +pub fn method_to_string(p: &ast::Method) -> String { + to_string(|s| s.print_method(p)) +} + +pub fn fn_block_to_string(p: &ast::FnDecl) -> String { + to_string(|s| s.print_fn_block_args(p)) +} + +pub fn path_to_string(p: &ast::Path) -> String { + to_string(|s| s.print_path(p, false)) +} + +pub fn ident_to_string(id: &ast::Ident) -> String { + to_string(|s| s.print_ident(*id)) +} + +pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident, + opt_explicit_self: Option<ast::ExplicitSelf_>, + generics: &ast::Generics) -> String { + to_string(|s| { + try!(s.print_fn(decl, Some(fn_style), abi::Rust, + name, generics, opt_explicit_self, ast::Inherited)); + try!(s.end()); // Close the head box + s.end() // Close the outer box + }) +} + +pub fn block_to_string(blk: &ast::Block) -> String { + to_string(|s| { + // containing cbox, will be closed by print-block at } + try!(s.cbox(indent_unit)); + // head-ibox, will be closed by print-block after { + try!(s.ibox(0u)); + s.print_block(blk) + }) +} + +pub fn meta_item_to_string(mi: &ast::MetaItem) -> String { + to_string(|s| s.print_meta_item(mi)) +} + +pub fn attribute_to_string(attr: &ast::Attribute) -> String { + to_string(|s| s.print_attribute(attr)) +} + +pub fn lit_to_string(l: &ast::Lit) -> String { + to_string(|s| s.print_literal(l)) +} + +pub fn explicit_self_to_string(explicit_self: ast::ExplicitSelf_) -> String { + to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {})) +} + +pub fn variant_to_string(var: &ast::Variant) -> String { + to_string(|s| s.print_variant(var)) +} + +pub fn arg_to_string(arg: &ast::Arg) -> String { + to_string(|s| s.print_arg(arg)) +} + + + +#[cfg(stage0)] pub fn to_str(f: |&mut State| -> IoResult<()>) -> String { let mut s = rust_printer(box MemWriter::new()); f(&mut s).unwrap(); @@ -144,62 +264,72 @@ pub fn to_str(f: |&mut State| -> IoResult<()>) -> String { } } +#[cfg(stage0)] pub fn ty_to_str(ty: &ast::Ty) -> String { to_str(|s| s.print_type(ty)) } +#[cfg(stage0)] pub fn pat_to_str(pat: &ast::Pat) -> String { to_str(|s| s.print_pat(pat)) } +#[cfg(stage0)] pub fn expr_to_str(e: &ast::Expr) -> String { to_str(|s| s.print_expr(e)) } +#[cfg(stage0)] pub fn lifetime_to_str(e: &ast::Lifetime) -> String { to_str(|s| s.print_lifetime(e)) } +#[cfg(stage0)] pub fn tt_to_str(tt: &ast::TokenTree) -> String { to_str(|s| s.print_tt(tt)) } +#[cfg(stage0)] pub fn tts_to_str(tts: &[ast::TokenTree]) -> String { to_str(|s| s.print_tts(tts)) } +#[cfg(stage0)] pub fn stmt_to_str(stmt: &ast::Stmt) -> String { to_str(|s| s.print_stmt(stmt)) } +#[cfg(stage0)] pub fn item_to_str(i: &ast::Item) -> String { to_str(|s| s.print_item(i)) } +#[cfg(stage0)] pub fn generics_to_str(generics: &ast::Generics) -> String { to_str(|s| s.print_generics(generics)) } +#[cfg(stage0)] pub fn ty_method_to_str(p: &ast::TypeMethod) -> String { to_str(|s| s.print_ty_method(p)) } +#[cfg(stage0)] pub fn method_to_str(p: &ast::Method) -> String { to_str(|s| s.print_method(p)) } +#[cfg(stage0)] pub fn fn_block_to_str(p: &ast::FnDecl) -> String { to_str(|s| s.print_fn_block_args(p)) } +#[cfg(stage0)] pub fn path_to_str(p: &ast::Path) -> String { to_str(|s| s.print_path(p, false)) } -pub fn ident_to_str(id: &ast::Ident) -> String { - to_str(|s| s.print_ident(*id)) -} - +#[cfg(stage0)] pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident, opt_explicit_self: Option<ast::ExplicitSelf_>, generics: &ast::Generics) -> String { @@ -211,6 +341,7 @@ pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident, }) } +#[cfg(stage0)] pub fn block_to_str(blk: &ast::Block) -> String { to_str(|s| { // containing cbox, will be closed by print-block at } @@ -221,30 +352,39 @@ pub fn block_to_str(blk: &ast::Block) -> String { }) } +#[cfg(stage0)] pub fn meta_item_to_str(mi: &ast::MetaItem) -> String { to_str(|s| s.print_meta_item(mi)) } +#[cfg(stage0)] pub fn attribute_to_str(attr: &ast::Attribute) -> String { to_str(|s| s.print_attribute(attr)) } +#[cfg(stage0)] pub fn lit_to_str(l: &ast::Lit) -> String { to_str(|s| s.print_literal(l)) } +#[cfg(stage0)] pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> String { to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {})) } +#[cfg(stage0)] pub fn variant_to_str(var: &ast::Variant) -> String { to_str(|s| s.print_variant(var)) } +#[cfg(stage0)] pub fn arg_to_str(arg: &ast::Arg) -> String { to_str(|s| s.print_arg(arg)) } + + + pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String { match vis { ast::Public => format!("pub {}", s), @@ -674,7 +814,7 @@ impl<'a> State<'a> { } ast::ItemForeignMod(ref nmod) => { try!(self.head("extern")); - try!(self.word_nbsp(nmod.abi.to_str().as_slice())); + try!(self.word_nbsp(nmod.abi.to_string().as_slice())); try!(self.bopen()); try!(self.print_foreign_mod(nmod, item.attrs.as_slice())); try!(self.bclose(item.span)); @@ -740,14 +880,19 @@ impl<'a> State<'a> { } try!(self.bclose(item.span)); } - ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => { + ast::ItemTrait(ref generics, ref unbound, ref traits, ref methods) => { try!(self.head(visibility_qualified(item.vis, "trait").as_slice())); try!(self.print_ident(item.ident)); try!(self.print_generics(generics)); - if *sized == ast::DynSize { - try!(space(&mut self.s)); - try!(word(&mut self.s, "for type")); + match unbound { + &Some(TraitTyParamBound(ref tref)) => { + try!(space(&mut self.s)); + try!(self.word_space("for")); + try!(self.print_trait_ref(tref)); + try!(word(&mut self.s, "?")); + } + _ => {} } if traits.len() != 0u { try!(word(&mut self.s, ":")); @@ -893,7 +1038,7 @@ impl<'a> State<'a> { match *tt { ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()), ast::TTTok(_, ref tk) => { - try!(word(&mut self.s, parse::token::to_str(tk).as_slice())); + try!(word(&mut self.s, parse::token::to_string(tk).as_slice())); match *tk { parse::token::DOC_COMMENT(..) => { hardbreak(&mut self.s) @@ -910,7 +1055,7 @@ impl<'a> State<'a> { match *sep { Some(ref tk) => { try!(word(&mut self.s, - parse::token::to_str(tk).as_slice())); + parse::token::to_string(tk).as_slice())); } None => () } @@ -1308,11 +1453,11 @@ impl<'a> State<'a> { ast::ExprBinary(op, ref lhs, ref rhs) => { try!(self.print_expr(&**lhs)); try!(space(&mut self.s)); - try!(self.word_space(ast_util::binop_to_str(op))); + try!(self.word_space(ast_util::binop_to_string(op))); try!(self.print_expr(&**rhs)); } ast::ExprUnary(op, ref expr) => { - try!(word(&mut self.s, ast_util::unop_to_str(op))); + try!(word(&mut self.s, ast_util::unop_to_string(op))); try!(self.print_expr_maybe_paren(&**expr)); } ast::ExprAddrOf(m, ref expr) => { @@ -1488,7 +1633,7 @@ impl<'a> State<'a> { ast::ExprAssignOp(op, ref lhs, ref rhs) => { try!(self.print_expr(&**lhs)); try!(space(&mut self.s)); - try!(word(&mut self.s, ast_util::binop_to_str(op))); + try!(word(&mut self.s, ast_util::binop_to_string(op))); try!(self.word_space("=")); try!(self.print_expr(&**rhs)); } @@ -1822,13 +1967,13 @@ impl<'a> State<'a> { try!(self.print_mutability(mutbl)); match explicit_self { ast::SelfStatic => { return Ok(false); } - ast::SelfValue => { + ast::SelfValue(_) => { try!(word(&mut self.s, "self")); } - ast::SelfUniq => { + ast::SelfUniq(_) => { try!(word(&mut self.s, "~self")); } - ast::SelfRegion(ref lt, m) => { + ast::SelfRegion(ref lt, m, _) => { try!(word(&mut self.s, "&")); try!(self.print_opt_lifetime(lt)); try!(self.print_mutability(m)); @@ -2029,8 +2174,12 @@ impl<'a> State<'a> { } else { let idx = idx - generics.lifetimes.len(); let param = generics.ty_params.get(idx); - if param.sized == ast::DynSize { - try!(s.word_space("type")); + match param.unbound { + Some(TraitTyParamBound(ref tref)) => { + try!(s.print_trait_ref(tref)); + try!(s.word_space("?")); + } + _ => {} } try!(s.print_ident(param.ident)); try!(s.print_bounds(&None, @@ -2328,11 +2477,11 @@ impl<'a> State<'a> { } ast::LitInt(i, t) => { word(&mut self.s, - ast_util::int_ty_to_str(t, Some(i)).as_slice()) + ast_util::int_ty_to_string(t, Some(i)).as_slice()) } ast::LitUint(u, t) => { word(&mut self.s, - ast_util::uint_ty_to_str(t, Some(u)).as_slice()) + ast_util::uint_ty_to_string(t, Some(u)).as_slice()) } ast::LitIntUnsuffixed(i) => { word(&mut self.s, format!("{}", i).as_slice()) @@ -2342,7 +2491,7 @@ impl<'a> State<'a> { format!( "{}{}", f.get(), - ast_util::float_ty_to_str(t).as_slice()).as_slice()) + ast_util::float_ty_to_string(t).as_slice()).as_slice()) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitNil => word(&mut self.s, "()"), @@ -2480,7 +2629,7 @@ impl<'a> State<'a> { Some(abi::Rust) => Ok(()), Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_str().as_slice()) + self.word_nbsp(abi.to_string().as_slice()) } None => Ok(()) } @@ -2491,7 +2640,7 @@ impl<'a> State<'a> { match opt_abi { Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_str().as_slice()) + self.word_nbsp(abi.to_string().as_slice()) } None => Ok(()) } @@ -2507,7 +2656,7 @@ impl<'a> State<'a> { if abi != abi::Rust { try!(self.word_nbsp("extern")); - try!(self.word_nbsp(abi.to_str().as_slice())); + try!(self.word_nbsp(abi.to_string().as_slice())); } word(&mut self.s, "fn") @@ -2538,7 +2687,7 @@ mod test { use parse::token; #[test] - fn test_fun_to_str() { + fn test_fun_to_string() { let abba_ident = token::str_to_ident("abba"); let decl = ast::FnDecl { @@ -2550,13 +2699,13 @@ mod test { variadic: false }; let generics = ast_util::empty_generics(); - assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident, + assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident, None, &generics), &"fn abba()".to_string()); } #[test] - fn test_variant_to_str() { + fn test_variant_to_string() { let ident = token::str_to_ident("principal_skinner"); let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ { @@ -2569,7 +2718,7 @@ mod test { vis: ast::Public, }); - let varstr = variant_to_str(&var); + let varstr = variant_to_string(&var); assert_eq!(&varstr,&"pub principal_skinner".to_string()); } } diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 4d88aaca748..452b5a52512 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// An "interner" is a data structure that associates values with uint tags and -// allows bidirectional lookup; i.e. given a value, one can easily find the -// type, and vice versa. +//! An "interner" is a data structure that associates values with uint tags and +//! allows bidirectional lookup; i.e. given a value, one can easily find the +//! type, and vice versa. use ast::Name; @@ -52,7 +52,7 @@ impl<T: Eq + Hash + Clone + 'static> Interner<T> { } let mut vect = self.vect.borrow_mut(); - let new_idx = (*vect).len() as Name; + let new_idx = Name((*vect).len() as u32); (*map).insert(val.clone(), new_idx); (*vect).push(val); new_idx @@ -60,7 +60,7 @@ impl<T: Eq + Hash + Clone + 'static> Interner<T> { pub fn gensym(&self, val: T) -> Name { let mut vect = self.vect.borrow_mut(); - let new_idx = (*vect).len() as Name; + let new_idx = Name((*vect).len() as u32); // leave out of .map to avoid colliding (*vect).push(val); new_idx @@ -68,7 +68,7 @@ impl<T: Eq + Hash + Clone + 'static> Interner<T> { pub fn get(&self, idx: Name) -> T { let vect = self.vect.borrow(); - (*(*vect).get(idx as uint)).clone() + (*(*vect).get(idx.uint())).clone() } pub fn len(&self) -> uint { @@ -155,7 +155,7 @@ impl StrInterner { None => (), } - let new_idx = self.len() as Name; + let new_idx = Name(self.len() as u32); let val = RcStr::new(val); map.insert(val.clone(), new_idx); self.vect.borrow_mut().push(val); @@ -163,7 +163,7 @@ impl StrInterner { } pub fn gensym(&self, val: &str) -> Name { - let new_idx = self.len() as Name; + let new_idx = Name(self.len() as u32); // leave out of .map to avoid colliding self.vect.borrow_mut().push(RcStr::new(val)); new_idx @@ -180,23 +180,23 @@ impl StrInterner { /// Create a gensym with the same name as an existing /// entry. pub fn gensym_copy(&self, idx : Name) -> Name { - let new_idx = self.len() as Name; + let new_idx = Name(self.len() as u32); // leave out of map to avoid colliding let mut vect = self.vect.borrow_mut(); - let existing = (*vect.get(idx as uint)).clone(); + let existing = (*vect.get(idx.uint())).clone(); vect.push(existing); new_idx } pub fn get(&self, idx: Name) -> RcStr { - (*self.vect.borrow().get(idx as uint)).clone() + (*self.vect.borrow().get(idx.uint())).clone() } /// Returns this string with lifetime tied to the interner. Since /// strings may never be removed from the interner, this is safe. pub fn get_ref<'a>(&'a self, idx: Name) -> &'a str { let vect = self.vect.borrow(); - let s: &str = vect.get(idx as uint).as_slice(); + let s: &str = vect.get(idx.uint()).as_slice(); unsafe { mem::transmute(s) } @@ -222,36 +222,38 @@ impl StrInterner { #[cfg(test)] mod tests { use super::*; + use ast::Name; + #[test] #[should_fail] fn i1 () { let i : Interner<RcStr> = Interner::new(); - i.get(13); + i.get(Name(13)); } #[test] fn interner_tests () { let i : Interner<RcStr> = Interner::new(); // first one is zero: - assert_eq!(i.intern(RcStr::new("dog")), 0); + assert_eq!(i.intern(RcStr::new("dog")), Name(0)); // re-use gets the same entry: - assert_eq!(i.intern(RcStr::new("dog")), 0); + assert_eq!(i.intern(RcStr::new("dog")), Name(0)); // different string gets a different #: - assert_eq!(i.intern(RcStr::new("cat")), 1); - assert_eq!(i.intern(RcStr::new("cat")), 1); + assert_eq!(i.intern(RcStr::new("cat")), Name(1)); + assert_eq!(i.intern(RcStr::new("cat")), Name(1)); // dog is still at zero - assert_eq!(i.intern(RcStr::new("dog")), 0); + assert_eq!(i.intern(RcStr::new("dog")), Name(0)); // gensym gets 3 - assert_eq!(i.gensym(RcStr::new("zebra") ), 2); + assert_eq!(i.gensym(RcStr::new("zebra") ), Name(2)); // gensym of same string gets new number : - assert_eq!(i.gensym (RcStr::new("zebra") ), 3); + assert_eq!(i.gensym (RcStr::new("zebra") ), Name(3)); // gensym of *existing* string gets new number: - assert_eq!(i.gensym(RcStr::new("dog")), 4); - assert_eq!(i.get(0), RcStr::new("dog")); - assert_eq!(i.get(1), RcStr::new("cat")); - assert_eq!(i.get(2), RcStr::new("zebra")); - assert_eq!(i.get(3), RcStr::new("zebra")); - assert_eq!(i.get(4), RcStr::new("dog")); + assert_eq!(i.gensym(RcStr::new("dog")), Name(4)); + assert_eq!(i.get(Name(0)), RcStr::new("dog")); + assert_eq!(i.get(Name(1)), RcStr::new("cat")); + assert_eq!(i.get(Name(2)), RcStr::new("zebra")); + assert_eq!(i.get(Name(3)), RcStr::new("zebra")); + assert_eq!(i.get(Name(4)), RcStr::new("dog")); } #[test] @@ -261,39 +263,39 @@ mod tests { RcStr::new("Bob"), RcStr::new("Carol") ]); - assert_eq!(i.get(0), RcStr::new("Alan")); - assert_eq!(i.get(1), RcStr::new("Bob")); - assert_eq!(i.get(2), RcStr::new("Carol")); - assert_eq!(i.intern(RcStr::new("Bob")), 1); + assert_eq!(i.get(Name(0)), RcStr::new("Alan")); + assert_eq!(i.get(Name(1)), RcStr::new("Bob")); + assert_eq!(i.get(Name(2)), RcStr::new("Carol")); + assert_eq!(i.intern(RcStr::new("Bob")), Name(1)); } #[test] fn string_interner_tests() { let i : StrInterner = StrInterner::new(); // first one is zero: - assert_eq!(i.intern("dog"), 0); + assert_eq!(i.intern("dog"), Name(0)); // re-use gets the same entry: - assert_eq!(i.intern ("dog"), 0); + assert_eq!(i.intern ("dog"), Name(0)); // different string gets a different #: - assert_eq!(i.intern("cat"), 1); - assert_eq!(i.intern("cat"), 1); + assert_eq!(i.intern("cat"), Name(1)); + assert_eq!(i.intern("cat"), Name(1)); // dog is still at zero - assert_eq!(i.intern("dog"), 0); + assert_eq!(i.intern("dog"), Name(0)); // gensym gets 3 - assert_eq!(i.gensym("zebra"), 2); + assert_eq!(i.gensym("zebra"), Name(2)); // gensym of same string gets new number : - assert_eq!(i.gensym("zebra"), 3); + assert_eq!(i.gensym("zebra"), Name(3)); // gensym of *existing* string gets new number: - assert_eq!(i.gensym("dog"), 4); + assert_eq!(i.gensym("dog"), Name(4)); // gensym tests again with gensym_copy: - assert_eq!(i.gensym_copy(2), 5); - assert_eq!(i.get(5), RcStr::new("zebra")); - assert_eq!(i.gensym_copy(2), 6); - assert_eq!(i.get(6), RcStr::new("zebra")); - assert_eq!(i.get(0), RcStr::new("dog")); - assert_eq!(i.get(1), RcStr::new("cat")); - assert_eq!(i.get(2), RcStr::new("zebra")); - assert_eq!(i.get(3), RcStr::new("zebra")); - assert_eq!(i.get(4), RcStr::new("dog")); + assert_eq!(i.gensym_copy(Name(2)), Name(5)); + assert_eq!(i.get(Name(5)), RcStr::new("zebra")); + assert_eq!(i.gensym_copy(Name(2)), Name(6)); + assert_eq!(i.get(Name(6)), RcStr::new("zebra")); + assert_eq!(i.get(Name(0)), RcStr::new("dog")); + assert_eq!(i.get(Name(1)), RcStr::new("cat")); + assert_eq!(i.get(Name(2)), RcStr::new("zebra")); + assert_eq!(i.get(Name(3)), RcStr::new("zebra")); + assert_eq!(i.get(Name(4)), RcStr::new("dog")); } } diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 04116dec60e..f50739a7069 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -17,14 +17,14 @@ use parse::token; use std::gc::Gc; -// map a string to tts, using a made-up filename: +/// Map a string to tts, using a made-up filename: pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> { let ps = new_parse_sess(); filemap_to_tts(&ps, string_to_filemap(&ps, source_str, "bogofile".to_string())) } -// map string to parser (via tts) +/// Map string to parser (via tts) pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> { new_parser_from_source_str(ps, Vec::new(), @@ -40,51 +40,51 @@ fn with_error_checking_parse<T>(s: String, f: |&mut Parser| -> T) -> T { x } -// parse a string, return a crate. +/// Parse a string, return a crate. pub fn string_to_crate (source_str : String) -> ast::Crate { with_error_checking_parse(source_str, |p| { p.parse_crate_mod() }) } -// parse a string, return an expr +/// Parse a string, return an expr pub fn string_to_expr (source_str : String) -> Gc<ast::Expr> { with_error_checking_parse(source_str, |p| { p.parse_expr() }) } -// parse a string, return an item +/// Parse a string, return an item pub fn string_to_item (source_str : String) -> Option<Gc<ast::Item>> { with_error_checking_parse(source_str, |p| { p.parse_item(Vec::new()) }) } -// parse a string, return a stmt +/// Parse a string, return a stmt pub fn string_to_stmt(source_str : String) -> Gc<ast::Stmt> { with_error_checking_parse(source_str, |p| { p.parse_stmt(Vec::new()) }) } -// parse a string, return a pat. Uses "irrefutable"... which doesn't -// (currently) affect parsing. +/// Parse a string, return a pat. Uses "irrefutable"... which doesn't +/// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> Gc<ast::Pat> { string_to_parser(&new_parse_sess(), source_str).parse_pat() } -// convert a vector of strings to a vector of ast::Ident's +/// Convert a vector of strings to a vector of ast::Ident's pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<ast::Ident> { ids.iter().map(|u| token::str_to_ident(*u)).collect() } -// does the given string match the pattern? whitespace in the first string -// may be deleted or replaced with other whitespace to match the pattern. -// this function is unicode-ignorant; fortunately, the careful design of -// UTF-8 mitigates this ignorance. In particular, this function only collapses -// sequences of \n, \r, ' ', and \t, but it should otherwise tolerate unicode -// chars. Unsurprisingly, it doesn't do NKF-normalization(?). +/// Does the given string match the pattern? whitespace in the first string +/// may be deleted or replaced with other whitespace to match the pattern. +/// this function is unicode-ignorant; fortunately, the careful design of +/// UTF-8 mitigates this ignorance. In particular, this function only collapses +/// sequences of \n, \r, ' ', and \t, but it should otherwise tolerate unicode +/// chars. Unsurprisingly, it doesn't do NKF-normalization(?). pub fn matches_codepattern(a : &str, b : &str) -> bool { let mut idx_a = 0; let mut idx_b = 0; @@ -122,9 +122,9 @@ pub fn matches_codepattern(a : &str, b : &str) -> bool { } } -// given a string and an index, return the first uint >= idx -// that is a non-ws-char or is outside of the legal range of -// the string. +/// Given a string and an index, return the first uint >= idx +/// that is a non-ws-char or is outside of the legal range of +/// the string. fn scan_for_non_ws_or_end(a : &str, idx: uint) -> uint { let mut i = idx; let len = a.len(); @@ -134,7 +134,7 @@ fn scan_for_non_ws_or_end(a : &str, idx: uint) -> uint { i } -// copied from lexer. +/// Copied from lexer. pub fn is_whitespace(c: char) -> bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 4ab064a88b7..9298b58c426 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -8,6 +8,18 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +//! Context-passing AST walker. Each overridden visit method has full control +//! over what happens with its node, it can do its own traversal of the node's +//! children (potentially passing in different contexts to each), call +//! `visit::visit_*` to apply the default traversal algorithm (again, it can +//! override the context), or prevent deeper traversal by doing nothing. +//! +//! Note: it is an important invariant that the default visitor walks the body +//! of a function in "execution order" (more concretely, reverse post-order +//! with respect to the CFG implied by the AST), meaning that if AST node A may +//! execute before AST node B, then A is visited first. The borrow checker in +//! particular relies on this property. +//! use abi::Abi; use ast::*; use ast; @@ -17,27 +29,15 @@ use owned_slice::OwnedSlice; use std::gc::Gc; -// Context-passing AST walker. Each overridden visit method has full control -// over what happens with its node, it can do its own traversal of the node's -// children (potentially passing in different contexts to each), call -// visit::visit_* to apply the default traversal algorithm (again, it can -// override the context), or prevent deeper traversal by doing nothing. -// -// Note: it is an important invariant that the default visitor walks the body -// of a function in "execution order" (more concretely, reverse post-order -// with respect to the CFG implied by the AST), meaning that if AST node A may -// execute before AST node B, then A is visited first. The borrow checker in -// particular relies on this property. - pub enum FnKind<'a> { - // fn foo() or extern "Abi" fn foo() + /// fn foo() or extern "Abi" fn foo() FkItemFn(Ident, &'a Generics, FnStyle, Abi), - // fn foo(&self) + /// fn foo(&self) FkMethod(Ident, &'a Generics, &'a Method), - // |x, y| ... - // proc(x, y) ... + /// |x, y| ... + /// proc(x, y) ... FkFnBlock, } @@ -202,8 +202,8 @@ pub fn walk_explicit_self<E: Clone, V: Visitor<E>>(visitor: &mut V, explicit_self: &ExplicitSelf, env: E) { match explicit_self.node { - SelfStatic | SelfValue | SelfUniq => {} - SelfRegion(ref lifetime, _) => { + SelfStatic | SelfValue(_) | SelfUniq(_) => {}, + SelfRegion(ref lifetime, _, _) => { visitor.visit_opt_lifetime_ref(explicit_self.span, lifetime, env) } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 1eb13fd660e..b80f47e6c93 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -370,7 +370,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> { let matches = match getopts::getopts(args_.as_slice(), optgroups().as_slice()) { Ok(m) => m, - Err(f) => return Some(Err(f.to_str())) + Err(f) => return Some(Err(f.to_string())) }; if matches.opt_present("h") { usage(args[0].as_slice()); return None; } @@ -634,7 +634,7 @@ impl<T: Writer> ConsoleTestState<T> { let mut failures = Vec::new(); let mut fail_out = String::new(); for &(ref f, ref stdout) in self.failures.iter() { - failures.push(f.name.to_str()); + failures.push(f.name.to_string()); if stdout.len() > 0 { fail_out.push_str(format!("---- {} stdout ----\n\t", f.name.as_slice()).as_slice()); @@ -1522,7 +1522,7 @@ mod tests { let filtered = filter_tests(&opts, tests); assert_eq!(filtered.len(), 1); - assert_eq!(filtered.get(0).desc.name.to_str(), + assert_eq!(filtered.get(0).desc.name.to_string(), "1".to_string()); assert!(filtered.get(0).desc.ignore == false); } @@ -1573,7 +1573,7 @@ mod tests { "test::sort_tests".to_string()); for (a, b) in expected.iter().zip(filtered.iter()) { - assert!(*a == b.desc.name.to_str()); + assert!(*a == b.desc.name.to_string()); } } diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 8db9a4f53aa..325582ff99c 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -385,8 +385,8 @@ pub fn write_boxplot<T: Float + Show + FromPrimitive>( let range = hi - lo; - let lostr = lo.to_str(); - let histr = hi.to_str(); + let lostr = lo.to_string(); + let histr = hi.to_string(); let overhead_width = lostr.len() + histr.len() + 4; let range_width = width_hint - overhead_width; diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index 873cc7af7b6..9ed46d7a49b 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -1039,7 +1039,7 @@ pub fn strftime(format: &str, tm: &Tm) -> String { 'U' => format!("{:02d}", (tm.tm_yday - tm.tm_wday + 7) / 7), 'u' => { let i = tm.tm_wday as int; - (if i == 0 { 7 } else { i }).to_str() + (if i == 0 { 7 } else { i }).to_string() } 'V' => iso_week('V', tm), 'v' => { @@ -1052,8 +1052,8 @@ pub fn strftime(format: &str, tm: &Tm) -> String { format!("{:02d}", (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7) } - 'w' => (tm.tm_wday as int).to_str(), - 'Y' => (tm.tm_year as int + 1900).to_str(), + 'w' => (tm.tm_wday as int).to_string(), + 'Y' => (tm.tm_year as int + 1900).to_string(), 'y' => format!("{:02d}", (tm.tm_year as int + 1900) % 100), 'Z' => "".to_string(), // FIXME(pcwalton): Implement this. 'z' => { diff --git a/src/liburl/lib.rs b/src/liburl/lib.rs index e835e5b26cf..129e3d0bf0a 100644 --- a/src/liburl/lib.rs +++ b/src/liburl/lib.rs @@ -765,13 +765,13 @@ impl fmt::Show for Path { impl<S: hash::Writer> hash::Hash<S> for Url { fn hash(&self, state: &mut S) { - self.to_str().hash(state) + self.to_string().hash(state) } } impl<S: hash::Writer> hash::Hash<S> for Path { fn hash(&self, state: &mut S) { - self.to_str().hash(state) + self.to_string().hash(state) } } diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index 426b350cab9..7d93f1f52cf 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -33,7 +33,7 @@ use uuid::Uuid; fn main() { let uuid1 = Uuid::new_v4(); - println!("{}", uuid1.to_str()); + println!("{}", uuid1.to_string()); } ``` @@ -622,7 +622,7 @@ mod test { // Round-trip let uuid_orig = Uuid::new_v4(); - let orig_str = uuid_orig.to_str(); + let orig_str = uuid_orig.to_string(); let uuid_out = Uuid::parse_string(orig_str.as_slice()).unwrap(); assert!(uuid_orig == uuid_out); @@ -650,9 +650,9 @@ mod test { } #[test] - fn test_to_str() { + fn test_to_string() { let uuid1 = Uuid::new_v4(); - let s = uuid1.to_str(); + let s = uuid1.to_string(); assert!(s.len() == 32); assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16))); @@ -685,7 +685,7 @@ mod test { let uuid1 = Uuid::new_v4(); let hs = uuid1.to_hyphenated_str(); - let ss = uuid1.to_str(); + let ss = uuid1.to_string(); let hsn = str::from_chars(hs.as_slice() .chars() @@ -704,7 +704,7 @@ mod test { let uuid_hs = Uuid::parse_string(hs.as_slice()).unwrap(); assert!(uuid_hs == uuid); - let ss = uuid.to_str(); + let ss = uuid.to_string(); let uuid_ss = Uuid::parse_string(ss.as_slice()).unwrap(); assert!(uuid_ss == uuid); } @@ -833,10 +833,10 @@ mod bench { } #[bench] - pub fn uuid_to_str(b: &mut Bencher) { + pub fn uuid_to_string(b: &mut Bencher) { let u = Uuid::new_v4(); b.iter(|| { - u.to_str(); + u.to_string(); }) } diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index c3e877f8081..1d2d02d7d59 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -90,11 +90,11 @@ impl Results { let mut set = f(); timed(&mut self.sequential_strings, || { for i in range(0u, num_keys) { - set.insert(i.to_str()); + set.insert(i.to_string()); } for i in range(0u, num_keys) { - assert!(set.contains(&i.to_str())); + assert!(set.contains(&i.to_string())); } }) } @@ -103,7 +103,7 @@ impl Results { let mut set = f(); timed(&mut self.random_strings, || { for _ in range(0, num_keys) { - let s = rng.gen::<uint>().to_str(); + let s = rng.gen::<uint>().to_string(); set.insert(s); } }) @@ -112,11 +112,11 @@ impl Results { { let mut set = f(); for i in range(0u, num_keys) { - set.insert(i.to_str()); + set.insert(i.to_string()); } timed(&mut self.delete_strings, || { for i in range(0u, num_keys) { - assert!(set.remove(&i.to_str())); + assert!(set.remove(&i.to_string())); } }) } diff --git a/src/test/bench/core-uint-to-str.rs b/src/test/bench/core-uint-to-str.rs index 1c51ea055d0..f3851751566 100644 --- a/src/test/bench/core-uint-to-str.rs +++ b/src/test/bench/core-uint-to-str.rs @@ -24,7 +24,7 @@ fn main() { let n = from_str::<uint>(args.get(1).as_slice()).unwrap(); for i in range(0u, n) { - let x = i.to_str(); + let x = i.to_string(); println!("{}", x); } } diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 8095037662b..0c76d14852e 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -48,7 +48,7 @@ fn show_color_list(set: Vec<Color>) -> String { let mut out = String::new(); for col in set.iter() { out.push_char(' '); - out.push_str(col.to_str().as_slice()); + out.push_str(col.to_string().as_slice()); } out } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 195c146c12f..b3deb88543e 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -64,7 +64,7 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String { k.as_slice() .to_ascii() .to_upper() - .into_str(), v).as_slice()); + .into_string(), v).as_slice()); } return buffer @@ -72,7 +72,7 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String { // given a map, search for the frequency of a pattern fn find(mm: &HashMap<Vec<u8> , uint>, key: String) -> uint { - let key = key.to_owned().into_ascii().as_slice().to_lower().into_str(); + let key = key.to_owned().into_ascii().as_slice().to_lower().into_string(); match mm.find_equiv(&key.as_bytes()) { option::None => { return 0u; } option::Some(&num) => { return num; } diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 85f035b60cb..0e0b0b518d5 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -115,7 +115,7 @@ fn main() { let elapsed = stop - start; - println!("{}\t{}\t{}", n, fibn, elapsed.to_str()); + println!("{}\t{}\t{}", n, fibn, elapsed.to_string()); } } } diff --git a/src/test/bench/shootout-regex-dna.rs b/src/test/bench/shootout-regex-dna.rs index 19b9d5638d0..bdf6862d0b1 100644 --- a/src/test/bench/shootout-regex-dna.rs +++ b/src/test/bench/shootout-regex-dna.rs @@ -67,7 +67,7 @@ fn main() { } else { box io::stdin() as Box<io::Reader> }; - let mut seq = rdr.read_to_str().unwrap(); + let mut seq = rdr.read_to_string().unwrap(); let ilen = seq.len(); seq = regex!(">[^\n]*\n|\n").replace_all(seq.as_slice(), NoExpand("")); @@ -109,7 +109,7 @@ fn main() { let (mut variant_strs, mut counts) = (vec!(), vec!()); for variant in variants.move_iter() { let seq_arc_copy = seq_arc.clone(); - variant_strs.push(variant.to_str().to_owned()); + variant_strs.push(variant.to_string().to_owned()); counts.push(Future::spawn(proc() { count_matches(seq_arc_copy.as_slice(), &variant) })); diff --git a/src/test/compile-fail/issue-2063.rs b/src/test/compile-fail/issue-2063.rs index 2c3dda01547..00607f85034 100644 --- a/src/test/compile-fail/issue-2063.rs +++ b/src/test/compile-fail/issue-2063.rs @@ -16,18 +16,18 @@ struct t(Box<t>); //~ ERROR this type cannot be instantiated trait to_str_2 { - fn my_to_str() -> String; + fn my_to_string() -> String; } // I use an impl here because it will cause // the compiler to attempt autoderef and then // try to resolve the method. impl to_str_2 for t { - fn my_to_str() -> String { "t".to_string() } + fn my_to_string() -> String { "t".to_string() } } fn new_t(x: t) { - x.my_to_str(); //~ ERROR does not implement + x.my_to_string(); //~ ERROR does not implement } fn main() { diff --git a/src/test/compile-fail/issue-3973.rs b/src/test/compile-fail/issue-3973.rs index 9b77d62a065..57bc1137912 100644 --- a/src/test/compile-fail/issue-3973.rs +++ b/src/test/compile-fail/issue-3973.rs @@ -13,17 +13,17 @@ struct Point { y: f64, } -trait NewTrait { - fn a(&self) -> String; +trait ToString_ { + fn to_string(&self) -> String; } -impl NewTrait for Point { +impl ToString_ for Point { fn new(x: f64, y: f64) -> Point { - //~^ ERROR method `new` is not a member of trait `NewTrait` + //~^ ERROR method `new` is not a member of trait `ToString_` Point { x: x, y: y } } - fn a(&self) -> String { + fn to_string(&self) -> String { format!("({}, {})", self.x, self.y) } } @@ -32,5 +32,5 @@ fn main() { let p = Point::new(0.0, 0.0); //~^ ERROR unresolved name `Point::new` //~^^ ERROR failed to resolve. Use of undeclared module `Point` - println!("{}", p.a()); + println!("{}", p.to_string()); } diff --git a/src/test/compile-fail/lex-illegal-num-char-escape.rs b/src/test/compile-fail/lex-bad-char-literals.rs index 8f4c756c891..0eaa81bd6ab 100644 --- a/src/test/compile-fail/lex-illegal-num-char-escape.rs +++ b/src/test/compile-fail/lex-bad-char-literals.rs @@ -31,5 +31,19 @@ static s: &'static str = static s2: &'static str = "\u23q" //~ ERROR: illegal character in numeric character escape + //~^ ERROR: numeric character escape is too short +; + +static c: char = + '\●' //~ ERROR: unknown character escape +; + +static s: &'static str = + "\●" //~ ERROR: unknown character escape +; + +// THIS MUST BE LAST, since unterminated character constants kill the lexer + +static c: char = + '● //~ ERROR: unterminated character constant ; -//~^^ ERROR: numeric character escape is too short diff --git a/src/test/compile-fail/lex-bad-fp-base-3.rs b/src/test/compile-fail/lex-bad-fp-base-3.rs deleted file mode 100644 index 79c42360adb..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-3.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let c = 0o3.0f32; //~ ERROR: octal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-4.rs b/src/test/compile-fail/lex-bad-fp-base-4.rs deleted file mode 100644 index eaea61b0089..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-4.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let d = 0o4e4; //~ ERROR: octal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-5.rs b/src/test/compile-fail/lex-bad-fp-base-5.rs deleted file mode 100644 index ee25ed95639..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-5.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let e = 0o5.0e5; //~ ERROR: octal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-6.rs b/src/test/compile-fail/lex-bad-fp-base-6.rs deleted file mode 100644 index bf08ec1eae5..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-6.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let f = 0o6e6f32; //~ ERROR: octal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-7.rs b/src/test/compile-fail/lex-bad-fp-base-7.rs deleted file mode 100644 index 921ed8f1b69..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-7.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let g = 0o7.0e7f64; //~ ERROR: octal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-8.rs b/src/test/compile-fail/lex-bad-fp-base-8.rs deleted file mode 100644 index 10e334ede01..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-8.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let h = 0x8.0e+9; //~ ERROR: hexadecimal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-base-9.rs b/src/test/compile-fail/lex-bad-fp-base-9.rs deleted file mode 100644 index 3ea151cb982..00000000000 --- a/src/test/compile-fail/lex-bad-fp-base-9.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let i = 0x9.0e-9; //~ ERROR: hexadecimal float literal is not supported -} diff --git a/src/test/compile-fail/lex-bad-fp-lit.rs b/src/test/compile-fail/lex-bad-fp-lit.rs deleted file mode 100644 index 5a5e9d7d8f2..00000000000 --- a/src/test/compile-fail/lex-bad-fp-lit.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static f: float = - 1e+ //~ ERROR: scan_exponent: bad fp literal -; diff --git a/src/test/compile-fail/lex-bad-numeric-literals.rs b/src/test/compile-fail/lex-bad-numeric-literals.rs new file mode 100644 index 00000000000..9a490be6a01 --- /dev/null +++ b/src/test/compile-fail/lex-bad-numeric-literals.rs @@ -0,0 +1,35 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + 0o1.0; //~ ERROR: octal float literal is not supported + 0o2f32; //~ ERROR: octal float literal is not supported + 0o3.0f32; //~ ERROR: octal float literal is not supported + 0o4e4; //~ ERROR: octal float literal is not supported + 0o5.0e5; //~ ERROR: octal float literal is not supported + 0o6e6f32; //~ ERROR: octal float literal is not supported + 0o7.0e7f64; //~ ERROR: octal float literal is not supported + 0x8.0e+9; //~ ERROR: hexadecimal float literal is not supported + 0x9.0e-9; //~ ERROR: hexadecimal float literal is not supported + 0o; //~ ERROR: no valid digits + 1e+; //~ ERROR: expected at least one digit in exponent + 0x539.0; //~ ERROR: hexadecimal float literal is not supported + 99999999999999999999999999999999; //~ ERROR: int literal is too large + 99999999999999999999999999999999u32; //~ ERROR: int literal is too large + 0x; //~ ERROR: no valid digits + 0xu32; //~ ERROR: no valid digits + 0ou32; //~ ERROR: no valid digits + 0bu32; //~ ERROR: no valid digits + 0b; //~ ERROR: no valid digits + 0o123f64; //~ ERROR: octal float literal is not supported + 0o123.456; //~ ERROR: octal float literal is not supported + 0b101f64; //~ ERROR: binary float literal is not supported + 0b111.101; //~ ERROR: binary float literal is not supported +} diff --git a/src/test/compile-fail/lex-bad-fp-base-1.rs b/src/test/compile-fail/lex-bad-token.rs index 659cb5c8379..d28d9a20c6e 100644 --- a/src/test/compile-fail/lex-bad-fp-base-1.rs +++ b/src/test/compile-fail/lex-bad-token.rs @@ -8,6 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main() { - let a = 0o1.0; //~ ERROR: octal float literal is not supported -} +● //~ ERROR: unknown start of token diff --git a/src/test/compile-fail/lex-hex-float-lit.rs b/src/test/compile-fail/lex-hex-float-lit.rs deleted file mode 100644 index 457c6126c44..00000000000 --- a/src/test/compile-fail/lex-hex-float-lit.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static f: float = - 0x539.0 //~ ERROR: hexadecimal float literal is not supported -; diff --git a/src/test/compile-fail/lex-int-lit-too-large-2.rs b/src/test/compile-fail/lex-int-lit-too-large-2.rs deleted file mode 100644 index 39d1cba64b0..00000000000 --- a/src/test/compile-fail/lex-int-lit-too-large-2.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static i: int = - 99999999999999999999999999999999u32 //~ ERROR: int literal is too large -; diff --git a/src/test/compile-fail/lex-int-lit-too-large.rs b/src/test/compile-fail/lex-int-lit-too-large.rs deleted file mode 100644 index 6343be651fa..00000000000 --- a/src/test/compile-fail/lex-int-lit-too-large.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static i: int = - 99999999999999999999999999999999 //~ ERROR: int literal is too large -; diff --git a/src/test/compile-fail/lex-no-valid-digits-2.rs b/src/test/compile-fail/lex-no-valid-digits-2.rs deleted file mode 100644 index 549dbf5bc8c..00000000000 --- a/src/test/compile-fail/lex-no-valid-digits-2.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static i: int = - 0xu32 //~ ERROR: no valid digits -; diff --git a/src/test/compile-fail/lex-no-valid-digits.rs b/src/test/compile-fail/lex-no-valid-digits.rs deleted file mode 100644 index 6a5b8e93f01..00000000000 --- a/src/test/compile-fail/lex-no-valid-digits.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static i: int = - 0x //~ ERROR: no valid digits -; diff --git a/src/test/compile-fail/lex-unknown-char-escape.rs b/src/test/compile-fail/lex-unknown-char-escape.rs deleted file mode 100644 index f2445c2b60e..00000000000 --- a/src/test/compile-fail/lex-unknown-char-escape.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static c: char = - '\●' //~ ERROR: unknown character escape -; diff --git a/src/test/compile-fail/lex-unknown-start-tok.rs b/src/test/compile-fail/lex-unknown-start-tok.rs deleted file mode 100644 index 1bb68230345..00000000000 --- a/src/test/compile-fail/lex-unknown-start-tok.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - ● //~ ERROR: unknown start of token -} diff --git a/src/test/compile-fail/lex-unknown-str-escape.rs b/src/test/compile-fail/lex-unknown-str-escape.rs deleted file mode 100644 index 9a59c422711..00000000000 --- a/src/test/compile-fail/lex-unknown-str-escape.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static s: &'static str = - "\●" //~ ERROR: unknown character escape -; diff --git a/src/test/compile-fail/lex-unterminated-char-const.rs b/src/test/compile-fail/lex-unterminated-char-const.rs deleted file mode 100644 index 551360ff9e0..00000000000 --- a/src/test/compile-fail/lex-unterminated-char-const.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static c: char = - '● //~ ERROR: unterminated character constant -; diff --git a/src/test/compile-fail/lint-uppercase-variables.rs b/src/test/compile-fail/lint-uppercase-variables.rs index f1b36d719e9..279cf6d94cb 100644 --- a/src/test/compile-fail/lint-uppercase-variables.rs +++ b/src/test/compile-fail/lint-uppercase-variables.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// ignore-tidy-linelength + #![allow(dead_code)] #![deny(uppercase_variables)] @@ -30,7 +32,7 @@ fn main() { let mut buff = [0u8, ..16]; match f.read(buff) { Ok(cnt) => println!("read this many bytes: {}", cnt), - Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {}", EndOfFile.to_str()), + Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {}", EndOfFile.to_string()), //~^ ERROR variable names should start with a lowercase character } diff --git a/src/test/compile-fail/moves-based-on-type-block-bad.rs b/src/test/compile-fail/moves-based-on-type-block-bad.rs index 73323def28d..1a2fb33eaab 100644 --- a/src/test/compile-fail/moves-based-on-type-block-bad.rs +++ b/src/test/compile-fail/moves-based-on-type-block-bad.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// ignore-tidy-linelength struct S { x: Box<E> @@ -29,7 +30,7 @@ fn main() { f(&s, |hellothere| { match hellothere.x { //~ ERROR cannot move out box Foo(_) => {} - box Bar(x) => println!("{}", x.to_str()), //~ NOTE attempting to move value to here + box Bar(x) => println!("{}", x.to_string()), //~ NOTE attempting to move value to here box Baz => {} } }) diff --git a/src/test/compile-fail/multitrait.rs b/src/test/compile-fail/multitrait.rs index f772b96c697..c7b0bc8822b 100644 --- a/src/test/compile-fail/multitrait.rs +++ b/src/test/compile-fail/multitrait.rs @@ -12,7 +12,7 @@ struct S { y: int } -impl Cmp, ToStr for S { //~ ERROR: expected `{` but found `,` +impl Cmp, ToString for S { //~ ERROR: expected `{` but found `,` fn eq(&&other: S) { false } - fn to_str(&self) -> String { "hi".to_string() } + fn to_string(&self) -> String { "hi".to_string() } } diff --git a/src/test/compile-fail/no-implicit-prelude-nested.rs b/src/test/compile-fail/no-implicit-prelude-nested.rs index 779a1ec7a5b..2fb097f111d 100644 --- a/src/test/compile-fail/no-implicit-prelude-nested.rs +++ b/src/test/compile-fail/no-implicit-prelude-nested.rs @@ -21,7 +21,7 @@ mod foo { impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait - impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait + impl ToString for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait fn foo() { @@ -33,7 +33,7 @@ mod foo { impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait - impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait + impl ToString for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait fn foo() { @@ -48,7 +48,7 @@ fn qux() { impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait - impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait + impl ToString for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait fn foo() { diff --git a/src/test/compile-fail/no-implicit-prelude.rs b/src/test/compile-fail/no-implicit-prelude.rs index fecc597b8fd..c0f7bea25b5 100644 --- a/src/test/compile-fail/no-implicit-prelude.rs +++ b/src/test/compile-fail/no-implicit-prelude.rs @@ -20,7 +20,7 @@ struct Test; impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait -impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait +impl ToString for Test {} //~ ERROR: attempt to implement a nonexistent trait impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait fn main() { diff --git a/src/test/compile-fail/no-oct-float-literal.rs b/src/test/compile-fail/no-oct-float-literal.rs deleted file mode 100644 index 511116b1c55..00000000000 --- a/src/test/compile-fail/no-oct-float-literal.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// error-pattern:octal float literal is not supported - -fn main() { - 0o123f64; - 0o123.456; - 0o123p4f; -} diff --git a/src/test/compile-fail/uninhabited-enum-cast.rs b/src/test/compile-fail/uninhabited-enum-cast.rs index fad20a7e373..9f91337db9f 100644 --- a/src/test/compile-fail/uninhabited-enum-cast.rs +++ b/src/test/compile-fail/uninhabited-enum-cast.rs @@ -11,7 +11,7 @@ enum E {} fn f(e: E) { - println!("{}", (e as int).to_str()); //~ ERROR non-scalar cast + println!("{}", (e as int).to_string()); //~ ERROR non-scalar cast } fn main() {} diff --git a/src/test/compile-fail/unsized-bare-typaram.rs b/src/test/compile-fail/unsized-bare-typaram.rs index fd09d78a4fa..6fd749b1298 100644 --- a/src/test/compile-fail/unsized-bare-typaram.rs +++ b/src/test/compile-fail/unsized-bare-typaram.rs @@ -10,5 +10,5 @@ // error-pattern: instantiating a type parameter with an incompatible type fn bar<T: Sized>() { } -fn foo<type T>() { bar::<T>() } +fn foo<Sized? T>() { bar::<T>() } fn main() { } diff --git a/src/test/compile-fail/unsized-enum.rs b/src/test/compile-fail/unsized-enum.rs index f586fbb576b..651eb26cadc 100644 --- a/src/test/compile-fail/unsized-enum.rs +++ b/src/test/compile-fail/unsized-enum.rs @@ -10,5 +10,5 @@ // error-pattern: instantiating a type parameter with an incompatible type fn bar<T: Sized>() { } -fn foo<type T>() { bar::<Option<T>>() } +fn foo<Sized? T>() { bar::<Option<T>>() } fn main() { } diff --git a/src/test/compile-fail/unsized-struct.rs b/src/test/compile-fail/unsized-struct.rs index 9fab3accbb9..ec6aafb43f4 100644 --- a/src/test/compile-fail/unsized-struct.rs +++ b/src/test/compile-fail/unsized-struct.rs @@ -13,5 +13,5 @@ struct Foo<T> { data: T } fn bar<T: Sized>() { } -fn foo<type T>() { bar::<Foo<T>>() } +fn foo<Sized? T>() { bar::<Foo<T>>() } fn main() { } diff --git a/src/test/compile-fail/unsized3.rs b/src/test/compile-fail/unsized3.rs index c5cc7e8f716..c07dcf93683 100644 --- a/src/test/compile-fail/unsized3.rs +++ b/src/test/compile-fail/unsized3.rs @@ -12,45 +12,45 @@ // Unbounded. -fn f1<type X>(x: &X) { +fn f1<Sized? X>(x: &X) { f2::<X>(x); //~ ERROR instantiating a type parameter with an incompatible type `X`, which does n } fn f2<X>(x: &X) { } // Bounded. -trait T for type {} -fn f3<type X: T>(x: &X) { +trait T for Sized? {} +fn f3<Sized? X: T>(x: &X) { f4::<X>(x); //~ ERROR instantiating a type parameter with an incompatible type `X`, which does n } fn f4<X: T>(x: &X) { } // Test with unsized enum. -enum E<type X> { +enum E<Sized? X> { V(X), } fn f5<Y>(x: &Y) {} -fn f6<type X>(x: &X) {} -fn f7<type X>(x1: &E<X>, x2: &E<X>) { +fn f6<Sized? X>(x: &X) {} +fn f7<Sized? X>(x1: &E<X>, x2: &E<X>) { f5(x1); //~ERROR instantiating a type parameter with an incompatible type `E<X>`, which does not f6(x2); // ok } // Test with unsized struct. -struct S<type X> { +struct S<Sized? X> { x: X, } -fn f8<type X>(x1: &S<X>, x2: &S<X>) { +fn f8<Sized? X>(x1: &S<X>, x2: &S<X>) { f5(x1); //~ERROR instantiating a type parameter with an incompatible type `S<X>`, which does not f6(x2); // ok } // Test some tuples. -fn f9<type X>(x1: Box<S<X>>, x2: Box<E<X>>) { +fn f9<Sized? X>(x1: Box<S<X>>, x2: Box<E<X>>) { f5(&(*x1, 34i)); //~ERROR instantiating a type parameter with an incompatible type `(S<X>,int)`, f5(&(32i, *x2)); //~ERROR instantiating a type parameter with an incompatible type `(int,E<X>)`, } @@ -60,20 +60,20 @@ fn f9<type X>(x1: Box<S<X>>, x2: Box<E<X>>) { // impl - bounded trait T1<Z: T> { } -struct S3<type Y>; -impl<type X: T> T1<X> for S3<X> { //ERROR instantiating a type parameter with an incompatible type +struct S3<Sized? Y>; +impl<Sized? X: T> T1<X> for S3<X> { //ERROR instantiating a type parameter with an incompatible type } // impl - unbounded trait T2<Z> { } -impl<type X> T2<X> for S3<X> { //ERROR instantiating a type parameter with an incompatible type `X` +impl<Sized? X> T2<X> for S3<X> { //ERROR instantiating a type parameter with an incompatible type `X // impl - struct -trait T3<type Z> { +trait T3<Sized? Z> { } struct S4<Y>; -impl<type X> T3<X> for S4<X> { //ERROR instantiating a type parameter with an incompatible type `X` +impl<Sized? X> T3<X> for S4<X> { //ERROR instantiating a type parameter with an incompatible type `X } */ diff --git a/src/test/compile-fail/unsized4.rs b/src/test/compile-fail/unsized4.rs index 968716320fd..e377c9d5f41 100644 --- a/src/test/compile-fail/unsized4.rs +++ b/src/test/compile-fail/unsized4.rs @@ -11,7 +11,7 @@ // Test that bounds are sized-compatible. trait T {} -fn f<type Y: T>() { +fn f<Sized? Y: T>() { //~^ERROR incompatible bounds on type parameter Y, bound T does not allow unsized type } diff --git a/src/test/compile-fail/unsized5.rs b/src/test/compile-fail/unsized5.rs index 614b8e3a5ab..7028f7e798b 100644 --- a/src/test/compile-fail/unsized5.rs +++ b/src/test/compile-fail/unsized5.rs @@ -9,19 +9,19 @@ // except according to those terms. #![feature(struct_variant)] -// Test `type` types not allowed in fields. +// Test `Sized?` types not allowed in fields. -struct S1<type X> { +struct S1<Sized? X> { f1: X, //~ ERROR type `f1` is dynamically sized. dynamically sized types may only appear as the f2: int, } -struct S2<type X> { +struct S2<Sized? X> { f: int, g: X, //~ ERROR type `g` is dynamically sized. dynamically sized types may only appear as the ty h: int, } -enum E<type X> { +enum E<Sized? X> { V1(X, int), //~ERROR type `X` is dynamically sized. dynamically sized types may only appear as t V2{f1: X, f: int}, //~ERROR type `f1` is dynamically sized. dynamically sized types may only app } diff --git a/src/test/compile-fail/unsized6.rs b/src/test/compile-fail/unsized6.rs index 061b003b5e3..def1146526b 100644 --- a/src/test/compile-fail/unsized6.rs +++ b/src/test/compile-fail/unsized6.rs @@ -8,37 +8,37 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test `type` local variables. +// Test `Sized?` local variables. -trait T for type {} +trait T for Sized? {} -fn f1<type X>(x: &X) { +fn f1<Sized? X>(x: &X) { let _: X; //~ERROR variable `_` has dynamically sized type `X` let _: (int, (X, int)); //~ERROR variable `_` has dynamically sized type `(int,(X,int))` let y: X; //~ERROR variable `y` has dynamically sized type `X` let y: (int, (X, int)); //~ERROR variable `y` has dynamically sized type `(int,(X,int))` } -fn f2<type X: T>(x: &X) { +fn f2<Sized? X: T>(x: &X) { let _: X; //~ERROR variable `_` has dynamically sized type `X` let _: (int, (X, int)); //~ERROR variable `_` has dynamically sized type `(int,(X,int))` let y: X; //~ERROR variable `y` has dynamically sized type `X` let y: (int, (X, int)); //~ERROR variable `y` has dynamically sized type `(int,(X,int))` } -fn f3<type X>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { +fn f3<Sized? X>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { let y: X = *x1; //~ERROR variable `y` has dynamically sized type `X` let y = *x2; //~ERROR variable `y` has dynamically sized type `X` let (y, z) = (*x3, 4i); //~ERROR variable `y` has dynamically sized type `X` } -fn f4<type X: T>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { +fn f4<Sized? X: T>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { let y: X = *x1; //~ERROR variable `y` has dynamically sized type `X` let y = *x2; //~ERROR variable `y` has dynamically sized type `X` let (y, z) = (*x3, 4i); //~ERROR variable `y` has dynamically sized type `X` } -fn g1<type X>(x: X) {} //~ERROR variable `x` has dynamically sized type `X` -fn g2<type X: T>(x: X) {} //~ERROR variable `x` has dynamically sized type `X` +fn g1<Sized? X>(x: X) {} //~ERROR variable `x` has dynamically sized type `X` +fn g2<Sized? X: T>(x: X) {} //~ERROR variable `x` has dynamically sized type `X` pub fn main() { } diff --git a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs index 753c91d1dc9..043f3a233a6 100644 --- a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs +++ b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs @@ -23,10 +23,10 @@ impl fmt::Show for Number { } struct List { - list: Vec<Box<ToStr>> } + list: Vec<Box<ToString>> } impl List { - fn push(&mut self, n: Box<ToStr>) { + fn push(&mut self, n: Box<ToString>) { self.list.push(n); } } @@ -35,6 +35,6 @@ fn main() { let n = box Number { n: 42 }; let mut l = box List { list: Vec::new() }; l.push(n); - let x = n.to_str(); + let x = n.to_string(); //~^ ERROR: use of moved value: `n` } diff --git a/src/test/debuginfo/cross-crate-type-uniquing.rs b/src/test/debuginfo/cross-crate-type-uniquing.rs index 47de06c4856..8f718add2a3 100644 --- a/src/test/debuginfo/cross-crate-type-uniquing.rs +++ b/src/test/debuginfo/cross-crate-type-uniquing.rs @@ -21,4 +21,4 @@ pub fn p() -> C { C } -fn main() { } \ No newline at end of file +fn main() { } diff --git a/src/test/run-pass/bool.rs b/src/test/run-pass/bool.rs index cb364d23387..91075633ab8 100644 --- a/src/test/run-pass/bool.rs +++ b/src/test/run-pass/bool.rs @@ -49,9 +49,9 @@ fn main() { assert_eq!(!true, false); assert_eq!(!false, true); - let s = false.to_str(); + let s = false.to_string(); assert_eq!(s.as_slice(), "false"); - let s = true.to_str(); + let s = true.to_string(); assert_eq!(s.as_slice(), "true"); assert!(true > false); diff --git a/src/test/run-pass/capturing-logging.rs b/src/test/run-pass/capturing-logging.rs index 19186f4b46b..33ee2ffd359 100644 --- a/src/test/run-pass/capturing-logging.rs +++ b/src/test/run-pass/capturing-logging.rs @@ -45,7 +45,7 @@ fn main() { debug!("debug"); info!("info"); }); - let s = r.read_to_str().unwrap(); + let s = r.read_to_string().unwrap(); assert!(s.as_slice().contains("info")); assert!(!s.as_slice().contains("debug")); } diff --git a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs index f3d12d21684..e3dbaa62d35 100644 --- a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs +++ b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs @@ -11,16 +11,16 @@ // aux-build:cci_class_cast.rs extern crate cci_class_cast; -use std::to_str::ToStr; +use std::to_str::ToString; use cci_class_cast::kitty::cat; -fn print_out(thing: Box<ToStr>, expected: String) { - let actual = thing.to_str(); +fn print_out(thing: Box<ToString>, expected: String) { + let actual = thing.to_string(); println!("{}", actual); assert_eq!(actual.to_string(), expected); } pub fn main() { - let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_string()) as Box<ToStr>; + let nyan: Box<ToString> = box cat(0u, 2, "nyan".to_string()) as Box<ToString>; print_out(nyan, "nyan".to_string()); } diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index 3d486144c3e..71438882980 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -57,13 +57,13 @@ impl fmt::Show for cat { } } -fn print_out(thing: Box<ToStr>, expected: String) { - let actual = thing.to_str(); +fn print_out(thing: Box<ToString>, expected: String) { + let actual = thing.to_string(); println!("{}", actual); assert_eq!(actual.to_string(), expected); } pub fn main() { - let nyan: Box<ToStr> = box cat(0u, 2, "nyan".to_string()) as Box<ToStr>; + let nyan: Box<ToString> = box cat(0u, 2, "nyan".to_string()) as Box<ToString>; print_out(nyan, "nyan".to_string()); } diff --git a/src/test/run-pass/deriving-show-2.rs b/src/test/run-pass/deriving-show-2.rs index a5e86dee18e..fa82e42d793 100644 --- a/src/test/run-pass/deriving-show-2.rs +++ b/src/test/run-pass/deriving-show-2.rs @@ -41,15 +41,15 @@ impl fmt::Show for Custom { } pub fn main() { - assert_eq!(B1.to_str(), "B1".to_string()); - assert_eq!(B2.to_str(), "B2".to_string()); - assert_eq!(C1(3).to_str(), "C1(3)".to_string()); - assert_eq!(C2(B2).to_str(), "C2(B2)".to_string()); - assert_eq!(D1{ a: 2 }.to_str(), "D1 { a: 2 }".to_string()); - assert_eq!(E.to_str(), "E".to_string()); - assert_eq!(F(3).to_str(), "F(3)".to_string()); - assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_string()); - assert_eq!(G(3, 4).to_str(), "G(3, 4)".to_string()); - assert_eq!(I{ a: 2, b: 4 }.to_str(), "I { a: 2, b: 4 }".to_string()); - assert_eq!(J(Custom).to_str(), "J(yay)".to_string()); + assert_eq!(B1.to_string(), "B1".to_string()); + assert_eq!(B2.to_string(), "B2".to_string()); + assert_eq!(C1(3).to_string(), "C1(3)".to_string()); + assert_eq!(C2(B2).to_string(), "C2(B2)".to_string()); + assert_eq!(D1{ a: 2 }.to_string(), "D1 { a: 2 }".to_string()); + assert_eq!(E.to_string(), "E".to_string()); + assert_eq!(F(3).to_string(), "F(3)".to_string()); + assert_eq!(G(3, 4).to_string(), "G(3, 4)".to_string()); + assert_eq!(G(3, 4).to_string(), "G(3, 4)".to_string()); + assert_eq!(I{ a: 2, b: 4 }.to_string(), "I { a: 2, b: 4 }".to_string()); + assert_eq!(J(Custom).to_string(), "J(yay)".to_string()); } diff --git a/src/test/run-pass/exponential-notation.rs b/src/test/run-pass/exponential-notation.rs index bb236638905..7e71be41148 100644 --- a/src/test/run-pass/exponential-notation.rs +++ b/src/test/run-pass/exponential-notation.rs @@ -11,24 +11,24 @@ #![feature(macro_rules)] use s = std::num::strconv; -use to_str = std::num::strconv::float_to_str_common; +use to_string = std::num::strconv::float_to_str_common; macro_rules! t(($a:expr, $b:expr) => { { let (r, _) = $a; assert_eq!(r, $b.to_string()) } }) pub fn main() { // Basic usage - t!(to_str(1.2345678e-5f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpDec, false), + t!(to_string(1.2345678e-5f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpDec, false), "1.234568e-5") // Hexadecimal output - t!(to_str(7.281738281250e+01f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false), + t!(to_string(7.281738281250e+01f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false), "+1.2345p+6") - t!(to_str(-1.777768135071e-02f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false), + t!(to_string(-1.777768135071e-02f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false), "-1.2345p-6") // Some denormals - t!(to_str(4.9406564584124654e-324f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false), + t!(to_string(4.9406564584124654e-324f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false), "1p-1074") - t!(to_str(2.2250738585072009e-308f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false), + t!(to_string(2.2250738585072009e-308f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false), "1p-1022") } diff --git a/src/test/run-pass/fixed_length_vec_glue.rs b/src/test/run-pass/fixed_length_vec_glue.rs index 62cfd10dbfb..3b7c5083bb4 100644 --- a/src/test/run-pass/fixed_length_vec_glue.rs +++ b/src/test/run-pass/fixed_length_vec_glue.rs @@ -17,6 +17,6 @@ struct Struc { a: u8, b: [int, ..3], c: int } pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; - let s = repr::repr_to_str(&struc); + let s = repr::repr_to_string(&struc); assert_eq!(s, "Struc{a: 13u8, b: [1, 2, 3], c: 42}".to_string()); } diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index d48a944c2f0..4a89d277e9f 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -79,8 +79,8 @@ fn read_board_grid<rdr:'static + io::Reader>(mut input: rdr) mod test { #[test] - pub fn trivial_to_str() { - assert!(lambda.to_str() == "\\") + pub fn trivial_to_string() { + assert!(lambda.to_string() == "\\") } } diff --git a/src/test/run-pass/issue-3037.rs b/src/test/run-pass/issue-3037.rs index 1d442198aec..1555098f291 100644 --- a/src/test/run-pass/issue-3037.rs +++ b/src/test/run-pass/issue-3037.rs @@ -10,7 +10,7 @@ enum what { } -fn what_to_str(x: what) -> String +fn what_to_string(x: what) -> String { match x { } diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index 53f92246e54..2568d94fcbf 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -24,6 +24,6 @@ pub fn main() { let mut table = HashMap::new(); table.insert("one".to_string(), 1i); table.insert("two".to_string(), 2i); - assert!(check_strs(table.to_str().as_slice(), "{one: 1, two: 2}") || - check_strs(table.to_str().as_slice(), "{two: 2, one: 1}")); + assert!(check_strs(table.to_string().as_slice(), "{one: 1, two: 2}") || + check_strs(table.to_string().as_slice(), "{two: 2, one: 1}")); } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index ac022d5c212..e38969c2526 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -94,7 +94,7 @@ impl AsciiArt { } } -// Allows AsciiArt to be converted to a string using the libcore ToStr trait. +// Allows AsciiArt to be converted to a string using the libcore ToString trait. // Note that the %s fmt! specifier will not call this automatically. impl fmt::Show for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -159,7 +159,7 @@ pub fn check_strs(actual: &str, expected: &str) -> bool { fn test_ascii_art_ctor() { let art = AsciiArt(3, 3, '*'); - assert!(check_strs(art.to_str().as_slice(), "...\n...\n...")); + assert!(check_strs(art.to_string().as_slice(), "...\n...\n...")); } @@ -168,7 +168,7 @@ fn test_add_pt() { art.add_pt(0, 0); art.add_pt(0, -10); art.add_pt(1, 2); - assert!(check_strs(art.to_str().as_slice(), "*..\n...\n.*.")); + assert!(check_strs(art.to_string().as_slice(), "*..\n...\n.*.")); } @@ -176,7 +176,7 @@ fn test_shapes() { let mut art = AsciiArt(4, 4, '*'); art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}}); art.add_point(Point {x: 2, y: 2}); - assert!(check_strs(art.to_str().as_slice(), "****\n*..*\n*.**\n****")); + assert!(check_strs(art.to_string().as_slice(), "****\n*..*\n*.**\n****")); } pub fn main() { diff --git a/src/test/run-pass/issue-3702.rs b/src/test/run-pass/issue-3702.rs index c9cedc3b7de..3f219da0a87 100644 --- a/src/test/run-pass/issue-3702.rs +++ b/src/test/run-pass/issue-3702.rs @@ -11,11 +11,11 @@ pub fn main() { trait Text { - fn to_str(&self) -> String; + fn to_string(&self) -> String; } fn to_string(t: Box<Text>) { - println!("{}", t.to_str()); + println!("{}", t.to_string()); } } diff --git a/src/test/run-pass/issue-4241.rs b/src/test/run-pass/issue-4241.rs index b27720b8579..3ebc3e64573 100644 --- a/src/test/run-pass/issue-4241.rs +++ b/src/test/run-pass/issue-4241.rs @@ -96,19 +96,19 @@ priv fn parse_response(io: @io::Reader) -> Result { } } -priv fn cmd_to_str(cmd: ~[String]) -> String { +priv fn cmd_to_string(cmd: ~[String]) -> String { let mut res = "*".to_string(); - res.push_str(cmd.len().to_str()); + res.push_str(cmd.len().to_string()); res.push_str("\r\n"); for s in cmd.iter() { - res.push_str(["$".to_string(), s.len().to_str(), "\r\n".to_string(), + res.push_str(["$".to_string(), s.len().to_string(), "\r\n".to_string(), (*s).clone(), "\r\n".to_string()].concat() ); } res } fn query(cmd: ~[String], sb: TcpSocketBuf) -> Result { - let cmd = cmd_to_str(cmd); + let cmd = cmd_to_string(cmd); //println!("{}", cmd); sb.write_str(cmd); let res = parse_response(@sb as @io::Reader); @@ -116,7 +116,7 @@ fn query(cmd: ~[String], sb: TcpSocketBuf) -> Result { } fn query2(cmd: ~[String]) -> Result { - let _cmd = cmd_to_str(cmd); + let _cmd = cmd_to_string(cmd); io::with_str_reader("$3\r\nXXX\r\n".to_string())(|sb| { let res = parse_response(@sb as @io::Reader); println!("{:?}", res); diff --git a/src/test/run-pass/issue-5280.rs b/src/test/run-pass/issue-5280.rs index 16fd45a5615..977cd08ba37 100644 --- a/src/test/run-pass/issue-5280.rs +++ b/src/test/run-pass/issue-5280.rs @@ -11,15 +11,15 @@ type FontTableTag = u32; trait FontTableTagConversions { - fn tag_to_str(self); + fn tag_to_string(self); } impl FontTableTagConversions for FontTableTag { - fn tag_to_str(self) { + fn tag_to_string(self) { &self; } } pub fn main() { - 5.tag_to_str(); + 5.tag_to_string(); } diff --git a/src/test/run-pass/issue-7911.rs b/src/test/run-pass/issue-7911.rs index 9e43e3ef1aa..75494c47dce 100644 --- a/src/test/run-pass/issue-7911.rs +++ b/src/test/run-pass/issue-7911.rs @@ -27,19 +27,19 @@ trait Test { fn get_mut<'r>(&'r mut self) -> &'r mut FooBar; } -macro_rules! generate_test(($type_:path, $field:expr) => ( +macro_rules! generate_test(($type_:path, $slf:ident, $field:expr) => ( impl Test for $type_ { - fn get_immut<'r>(&'r self) -> &'r FooBar { + fn get_immut<'r>(&'r $slf) -> &'r FooBar { &$field as &FooBar } - fn get_mut<'r>(&'r mut self) -> &'r mut FooBar { + fn get_mut<'r>(&'r mut $slf) -> &'r mut FooBar { &mut $field as &mut FooBar } } )) -generate_test!(Foo, self.bar) +generate_test!(Foo, self, self.bar) pub fn main() { let mut foo: Foo = Foo { bar: Bar(42) }; diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs index 2b67ef09c59..783dc32426a 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -38,7 +38,7 @@ impl<A> option_monad<A> for Option<A> { } fn transform(x: Option<int>) -> Option<String> { - x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str()) ) + x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_string()) ) } pub fn main() { diff --git a/src/test/run-pass/move-out-of-field.rs b/src/test/run-pass/move-out-of-field.rs index e7d679c41e8..92c5e025b9b 100644 --- a/src/test/run-pass/move-out-of-field.rs +++ b/src/test/run-pass/move-out-of-field.rs @@ -20,7 +20,7 @@ impl StringBuffer { } } -fn to_str(sb: StringBuffer) -> String { +fn to_string(sb: StringBuffer) -> String { sb.s } @@ -30,6 +30,6 @@ pub fn main() { }; sb.append("Hello, "); sb.append("World!"); - let str = to_str(sb); + let str = to_string(sb); assert_eq!(str.as_slice(), "Hello, World!"); } diff --git a/src/test/run-pass/new-impl-syntax.rs b/src/test/run-pass/new-impl-syntax.rs index 9fd6e961675..8532b5f51dc 100644 --- a/src/test/run-pass/new-impl-syntax.rs +++ b/src/test/run-pass/new-impl-syntax.rs @@ -32,6 +32,6 @@ impl<T:fmt::Show> fmt::Show for PolymorphicThingy<T> { } pub fn main() { - println!("{}", Thingy { x: 1, y: 2 }.to_str()); - println!("{}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } }.to_str()); + println!("{}", Thingy { x: 1, y: 2 }.to_string()); + println!("{}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } }.to_string()); } diff --git a/src/test/run-pass/overloaded-deref-count.rs b/src/test/run-pass/overloaded-deref-count.rs index 49edf1bad57..283c76adf0d 100644 --- a/src/test/run-pass/overloaded-deref-count.rs +++ b/src/test/run-pass/overloaded-deref-count.rs @@ -72,7 +72,7 @@ pub fn main() { // N.B. This is required because method lookup hasn't been performed so // we don't know whether the called method takes mutable self, before // the dereference itself is type-checked (a chicken-and-egg problem). - (*n).to_str(); + (*n).to_string(); assert_eq!(n.counts(), (2, 4)); // Mutable deref used for calling a method taking &mut self. diff --git a/src/test/run-pass/send_str_treemap.rs b/src/test/run-pass/send_str_treemap.rs index 68eca8f21a7..f3a730aa2b3 100644 --- a/src/test/run-pass/send_str_treemap.rs +++ b/src/test/run-pass/send_str_treemap.rs @@ -12,7 +12,7 @@ extern crate collections; use std::collections::{ Map, MutableMap}; use std::str::{SendStr, Owned, Slice}; -use std::to_str::ToStr; +use std::to_str::ToString; use self::collections::TreeMap; use std::option::Some; diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 9267fcac011..d0dacc2ff7a 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -31,7 +31,7 @@ trait uint_utils { impl uint_utils for uint { fn str(&self) -> String { - self.to_str() + self.to_string() } fn multi(&self, f: |uint|) { let mut c = 0u; diff --git a/src/test/compile-fail/lex-bad-fp-base-2.rs b/src/test/run-pass/string-escapes.rs index b1d45f78e4a..7abe8276a97 100644 --- a/src/test/compile-fail/lex-bad-fp-base-2.rs +++ b/src/test/run-pass/string-escapes.rs @@ -9,5 +9,7 @@ // except according to those terms. fn main() { - let b = 0o2f32; //~ ERROR: octal float literal is not supported + let x = "\\\\\ + "; + assert!(x == r"\\"); // extraneous whitespace stripped } diff --git a/src/test/run-pass/task-stderr.rs b/src/test/run-pass/task-stderr.rs index 6a71f9df6e4..ceffd1e3636 100644 --- a/src/test/run-pass/task-stderr.rs +++ b/src/test/run-pass/task-stderr.rs @@ -21,6 +21,6 @@ fn main() { }); assert!(res.is_err()); - let output = reader.read_to_str().unwrap(); + let output = reader.read_to_string().unwrap(); assert!(output.as_slice().contains("Hello, world!")); } diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index ebc720aa0c8..d2408509fc5 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -54,7 +54,7 @@ macro_rules! iotest ( iotest!(fn eventual_timeout() { use native; let addr = next_test_ip4(); - let host = addr.ip.to_str(); + let host = addr.ip.to_string(); let port = addr.port; // Use a native task to receive connections because it turns out libuv is @@ -82,7 +82,7 @@ iotest!(fn eventual_timeout() { iotest!(fn timeout_success() { let addr = next_test_ip4(); - let host = addr.ip.to_str(); + let host = addr.ip.to_string(); let port = addr.port; let _l = TcpListener::bind(host.as_slice(), port).unwrap().listen(); diff --git a/src/test/run-pass/tcp-stress.rs b/src/test/run-pass/tcp-stress.rs index de3366708c5..f52a3455e41 100644 --- a/src/test/run-pass/tcp-stress.rs +++ b/src/test/run-pass/tcp-stress.rs @@ -61,7 +61,7 @@ fn main() { for _ in range(0u, 1000) { let tx = tx.clone(); TaskBuilder::new().stack_size(64 * 1024).spawn(proc() { - let host = addr.ip.to_str(); + let host = addr.ip.to_string(); let port = addr.port; match TcpStream::connect(host.as_slice(), port) { Ok(stream) => { diff --git a/src/test/run-pass/test-ignore-cfg.rs b/src/test/run-pass/test-ignore-cfg.rs index c3387a963a7..b36fbca2da0 100644 --- a/src/test/run-pass/test-ignore-cfg.rs +++ b/src/test/run-pass/test-ignore-cfg.rs @@ -27,10 +27,10 @@ fn checktests() { let tests = __test::TESTS; assert!( - tests.iter().any(|t| t.desc.name.to_str().as_slice() == "shouldignore" && + tests.iter().any(|t| t.desc.name.to_string().as_slice() == "shouldignore" && t.desc.ignore)); assert!( - tests.iter().any(|t| t.desc.name.to_str().as_slice() == "shouldnotignore" && + tests.iter().any(|t| t.desc.name.to_string().as_slice() == "shouldnotignore" && !t.desc.ignore)); } diff --git a/src/test/run-pass/trait-cast.rs b/src/test/run-pass/trait-cast.rs index daab40f5d90..43d3b591ffa 100644 --- a/src/test/run-pass/trait-cast.rs +++ b/src/test/run-pass/trait-cast.rs @@ -39,7 +39,7 @@ impl<T:to_str> to_str for Option<T> { impl to_str for int { fn to_str_(&self) -> String { - self.to_str() + self.to_string() } } diff --git a/src/test/run-pass/trait-generic.rs b/src/test/run-pass/trait-generic.rs index f3f4c556b77..eeda6e2c88b 100644 --- a/src/test/run-pass/trait-generic.rs +++ b/src/test/run-pass/trait-generic.rs @@ -11,16 +11,16 @@ trait to_str { - fn to_string(&self) -> String; + fn to_string_(&self) -> String; } impl to_str for int { - fn to_string(&self) -> String { self.to_str() } + fn to_string_(&self) -> String { self.to_string() } } impl to_str for String { - fn to_string(&self) -> String { self.clone() } + fn to_string_(&self) -> String { self.clone() } } impl to_str for () { - fn to_string(&self) -> String { "()".to_string() } + fn to_string_(&self) -> String { "()".to_string() } } trait map<T> { @@ -40,7 +40,7 @@ fn foo<U, T: map<U>>(x: T) -> Vec<String> { x.map(|_e| "hi".to_string() ) } fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> { - x.map(|_e| _e.to_string() ) + x.map(|_e| _e.to_string_() ) } pub fn main() { diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index 54a21caafa0..fbe40e837de 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -11,29 +11,29 @@ trait to_str { - fn to_string(&self) -> String; + fn to_string_(&self) -> String; } impl to_str for int { - fn to_string(&self) -> String { self.to_str() } + fn to_string_(&self) -> String { self.to_string() } } impl<T:to_str> to_str for Vec<T> { - fn to_string(&self) -> String { + fn to_string_(&self) -> String { format!("[{}]", self.iter() - .map(|e| e.to_string()) + .map(|e| e.to_string_()) .collect::<Vec<String>>() .connect(", ")) } } pub fn main() { - assert!(1.to_string() == "1".to_string()); - assert!((vec!(2i, 3, 4)).to_string() == "[2, 3, 4]".to_string()); + assert!(1.to_string_() == "1".to_string()); + assert!((vec!(2i, 3, 4)).to_string_() == "[2, 3, 4]".to_string()); fn indirect<T:to_str>(x: T) -> String { - format!("{}!", x.to_string()) + format!("{}!", x.to_string_()) } assert!(indirect(vec!(10i, 20)) == "[10, 20]!".to_string()); diff --git a/src/test/run-pass/unsized.rs b/src/test/run-pass/unsized.rs index db0cc83d786..f49e8f46e78 100644 --- a/src/test/run-pass/unsized.rs +++ b/src/test/run-pass/unsized.rs @@ -8,20 +8,20 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test syntax checks for `type` keyword. +// Test syntax checks for `Sized?` syntax. -trait T1 for type {} -pub trait T2 for type {} -trait T3<X: T1> for type: T2 {} -trait T4<type X> {} -trait T5<type X, Y> {} -trait T6<Y, type X> {} -trait T7<type X, type Y> {} -trait T8<type X: T2> {} -struct S1<type X>; -enum E<type X> {} -impl <type X> T1 for S1<X> {} -fn f<type X>() {} +trait T1 for Sized? {} +pub trait T2 for Sized? {} +trait T3<X: T1> for Sized?: T2 {} +trait T4<Sized? X> {} +trait T5<Sized? X, Y> {} +trait T6<Y, Sized? X> {} +trait T7<Sized? X, Sized? Y> {} +trait T8<Sized? X: T2> {} +struct S1<Sized? X>; +enum E<Sized? X> {} +impl <Sized? X> T1 for S1<X> {} +fn f<Sized? X>() {} pub fn main() { } diff --git a/src/test/run-pass/unsized2.rs b/src/test/run-pass/unsized2.rs index 53db7f37e8d..9703b55cda7 100644 --- a/src/test/run-pass/unsized2.rs +++ b/src/test/run-pass/unsized2.rs @@ -13,7 +13,7 @@ // Test sized-ness checking in substitution. // Unbounded. -fn f1<type X>(x: &X) { +fn f1<Sized? X>(x: &X) { f1::<X>(x); } fn f2<X>(x: &X) { @@ -22,8 +22,8 @@ fn f2<X>(x: &X) { } // Bounded. -trait T for type {} -fn f3<type X: T>(x: &X) { +trait T for Sized? {} +fn f3<Sized? X: T>(x: &X) { f3::<X>(x); } fn f4<X: T>(x: &X) { @@ -32,7 +32,7 @@ fn f4<X: T>(x: &X) { } // Self type. -trait T2 for type { +trait T2 for Sized? { fn f() -> Box<Self>; } struct S; @@ -41,14 +41,14 @@ impl T2 for S { box S } } -fn f5<type X: T2>(x: &X) { +fn f5<Sized? X: T2>(x: &X) { let _: Box<X> = T2::f(); } fn f6<X: T2>(x: &X) { let _: Box<X> = T2::f(); } -trait T3 for type { +trait T3 for Sized? { fn f() -> Box<Self>; } impl T3 for S { @@ -56,7 +56,7 @@ impl T3 for S { box S } } -fn f7<type X: T3>(x: &X) { +fn f7<Sized? X: T3>(x: &X) { // This is valid, but the unsized bound on X is irrelevant because any type // which implements T3 must have statically known size. let _: Box<X> = T3::f(); @@ -66,7 +66,7 @@ trait T4<X> { fn m1(x: &T4<X>); fn m2(x: &T5<X>); } -trait T5<type X> { +trait T5<Sized? X> { // not an error (for now) fn m1(x: &T4<X>); fn m2(x: &T5<X>); @@ -76,21 +76,21 @@ trait T6<X: T> { fn m1(x: &T4<X>); fn m2(x: &T5<X>); } -trait T7<type X: T> { +trait T7<Sized? X: T> { // not an error (for now) fn m1(x: &T4<X>); fn m2(x: &T5<X>); } // The last field in a struct or variant may be unsized -struct S2<type X> { +struct S2<Sized? X> { f: X, } -struct S3<type X> { +struct S3<Sized? X> { f1: int, f2: X, } -enum E<type X> { +enum E<Sized? X> { V1(X), V2{x: X}, V3(int, X), diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index 4d9f80cec6a..deb08a4608c 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -9,12 +9,12 @@ // except according to those terms. pub fn main() { - assert_eq!((vec!(0i, 1)).to_str(), "[0, 1]".to_string()); - assert_eq!((&[1i, 2]).to_str(), "[1, 2]".to_string()); + assert_eq!((vec!(0i, 1)).to_string(), "[0, 1]".to_string()); + assert_eq!((&[1i, 2]).to_string(), "[1, 2]".to_string()); let foo = vec!(3i, 4); let bar = &[4i, 5]; - assert_eq!(foo.to_str(), "[3, 4]".to_string()); - assert_eq!(bar.to_str(), "[4, 5]".to_string()); + assert_eq!(foo.to_string(), "[3, 4]".to_string()); + assert_eq!(bar.to_string(), "[4, 5]".to_string()); } |
