diff options
| author | Alex Crichton <alex@alexcrichton.com> | 2014-07-02 11:08:21 -0700 |
|---|---|---|
| committer | Alex Crichton <alex@alexcrichton.com> | 2014-07-02 11:08:21 -0700 |
| commit | ff1dd44b40a7243f43a8d32ba8bd6026197c320b (patch) | |
| tree | 4460cbf0a917a289d1d3744d9645c5ab131ea9df /src | |
| parent | aa1163b92de7717eb7c5eba002b4012e0574a7fe (diff) | |
| parent | ca2778ede7c21efc3cf2e4e1152875ec09360770 (diff) | |
| download | rust-ff1dd44b40a7243f43a8d32ba8bd6026197c320b.tar.gz rust-ff1dd44b40a7243f43a8d32ba8bd6026197c320b.zip | |
Merge remote-tracking branch 'origin/master' into 0.11.0-release
Conflicts: src/libstd/lib.rs
Diffstat (limited to 'src')
710 files changed, 10301 insertions, 8181 deletions
diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 4de7b89ba6f..9eac38e4cd5 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -42,7 +42,7 @@ pub mod common; pub mod errors; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/doc/guide-ffi.md b/src/doc/guide-ffi.md index 13e44765d59..bba9594afeb 100644 --- a/src/doc/guide-ffi.md +++ b/src/doc/guide-ffi.md @@ -50,19 +50,19 @@ use libc::{c_int, size_t}; #[link(name = "snappy")] extern { - fn snappy_compress(input: *u8, + fn snappy_compress(input: *const u8, input_length: size_t, compressed: *mut u8, compressed_length: *mut size_t) -> c_int; - fn snappy_uncompress(compressed: *u8, + fn snappy_uncompress(compressed: *const u8, compressed_length: size_t, uncompressed: *mut u8, uncompressed_length: *mut size_t) -> c_int; fn snappy_max_compressed_length(source_length: size_t) -> size_t; - fn snappy_uncompressed_length(compressed: *u8, + fn snappy_uncompressed_length(compressed: *const u8, compressed_length: size_t, result: *mut size_t) -> c_int; - fn snappy_validate_compressed_buffer(compressed: *u8, + fn snappy_validate_compressed_buffer(compressed: *const u8, compressed_length: size_t) -> c_int; } # fn main() {} @@ -82,7 +82,7 @@ the allocated memory. The length is less than or equal to the capacity. ~~~~ # extern crate libc; # use libc::{c_int, size_t}; -# unsafe fn snappy_validate_compressed_buffer(_: *u8, _: size_t) -> c_int { 0 } +# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 } # fn main() {} pub fn validate_compressed_buffer(src: &[u8]) -> bool { unsafe { @@ -106,7 +106,7 @@ the true length after compression for setting the length. ~~~~ # extern crate libc; # use libc::{size_t, c_int}; -# unsafe fn snappy_compress(a: *u8, b: size_t, c: *mut u8, +# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8, # d: *mut size_t) -> c_int { 0 } # unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a } # fn main() {} @@ -132,11 +132,11 @@ format and `snappy_uncompressed_length` will retrieve the exact buffer size requ ~~~~ # extern crate libc; # use libc::{size_t, c_int}; -# unsafe fn snappy_uncompress(compressed: *u8, +# unsafe fn snappy_uncompress(compressed: *const u8, # compressed_length: size_t, # uncompressed: *mut u8, # uncompressed_length: *mut size_t) -> c_int { 0 } -# unsafe fn snappy_uncompressed_length(compressed: *u8, +# unsafe fn snappy_uncompressed_length(compressed: *const u8, # compressed_length: size_t, # result: *mut size_t) -> c_int { 0 } # fn main() {} @@ -418,7 +418,7 @@ Unsafe functions, on the other hand, advertise it to the world. An unsafe functi this: ~~~~ -unsafe fn kaboom(ptr: *int) -> int { *ptr } +unsafe fn kaboom(ptr: *const int) -> int { *ptr } ~~~~ This function can only be called from an `unsafe` block or another `unsafe` function. @@ -453,7 +453,7 @@ use std::ptr; #[link(name = "readline")] extern { - static mut rl_prompt: *libc::c_char; + static mut rl_prompt: *const libc::c_char; } fn main() { @@ -478,7 +478,7 @@ extern crate libc; #[link(name = "kernel32")] #[allow(non_snake_case_functions)] extern "stdcall" { - fn SetEnvironmentVariableA(n: *u8, v: *u8) -> libc::c_int; + fn SetEnvironmentVariableA(n: *const u8, v: *const u8) -> libc::c_int; } # fn main() { } ~~~~ diff --git a/src/doc/guide-macros.md b/src/doc/guide-macros.md index 45745c7b7bc..6d3825f8ecf 100644 --- a/src/doc/guide-macros.md +++ b/src/doc/guide-macros.md @@ -355,6 +355,7 @@ macro_rules! biased_match_rec ( _ => { $err } } ); + // Produce the requested values ( binds $( $bind_res:ident ),* ) => ( ($( $bind_res ),*) ) ) @@ -364,7 +365,7 @@ macro_rules! biased_match ( ( $( ($e:expr) ~ ($p:pat) else $err:stmt ; )* binds $bind_res:ident ) => ( - let ( $( $bind_res ),* ) = biased_match_rec!( + let $bind_res = biased_match_rec!( $( ($e) ~ ($p) else $err ; )* binds $bind_res ); diff --git a/src/doc/guide-runtime.md b/src/doc/guide-runtime.md index 0050bd2d77f..1367bdc0755 100644 --- a/src/doc/guide-runtime.md +++ b/src/doc/guide-runtime.md @@ -245,7 +245,7 @@ extern crate green; extern crate rustuv; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } @@ -261,7 +261,9 @@ inside of an OS thread. extern crate native; #[start] -fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } +fn start(argc: int, argv: *const *const u8) -> int { + native::start(argc, argv, main) +} fn main() {} ~~~ diff --git a/src/doc/guide-tasks.md b/src/doc/guide-tasks.md index 81d7f37d6fb..9021b761954 100644 --- a/src/doc/guide-tasks.md +++ b/src/doc/guide-tasks.md @@ -457,6 +457,8 @@ the string in response. The child terminates when it receives `0`. Here is the function that implements the child task: ~~~ +#![allow(deprecated)] + use std::comm::DuplexStream; # fn main() { fn stringifier(channel: &DuplexStream<String, uint>) { @@ -481,6 +483,8 @@ response itself is simply the stringified version of the received value, Here is the code for the parent task: ~~~ +#![allow(deprecated)] + use std::comm::duplex; # use std::task::spawn; # use std::comm::DuplexStream; diff --git a/src/doc/guide-unsafe.md b/src/doc/guide-unsafe.md index 609d8937c80..3852591da5b 100644 --- a/src/doc/guide-unsafe.md +++ b/src/doc/guide-unsafe.md @@ -79,7 +79,7 @@ let ref_2: &mut u8 = unsafe { mem::transmute(&mut *ref_1) }; ## Raw pointers Rust offers two additional pointer types "raw pointers", written as -`*T` and `*mut T`. They're an approximation of C's `const T*` and `T*` +`*const T` and `*mut T`. They're an approximation of C's `const T*` and `T*` respectively; indeed, one of their most common uses is for FFI, interfacing with external C libraries. @@ -100,7 +100,7 @@ offered by the Rust language and libraries. For example, they - lack any form of lifetimes, unlike `&`, and so the compiler cannot reason about dangling pointers; and - have no guarantees about aliasing or mutability other than mutation - not being allowed directly through a `*T`. + not being allowed directly through a `*const T`. Fortunately, they come with a redeeming feature: the weaker guarantees mean weaker restrictions. The missing restrictions make raw pointers @@ -131,13 +131,13 @@ unsafe, and neither is converting to an integer. At runtime, a raw pointer `*` and a reference pointing to the same piece of data have an identical representation. In fact, an `&T` -reference will implicitly coerce to an `*T` raw pointer in safe code +reference will implicitly coerce to an `*const T` raw pointer in safe code and similarly for the `mut` variants (both coercions can be performed -explicitly with, respectively, `value as *T` and `value as *mut T`). +explicitly with, respectively, `value as *const T` and `value as *mut T`). -Going the opposite direction, from `*` to a reference `&`, is not +Going the opposite direction, from `*const` to a reference `&`, is not safe. A `&T` is always valid, and so, at a minimum, the raw pointer -`*T` has to be a valid to a valid instance of type `T`. Furthermore, +`*const T` has to be a valid to a valid instance of type `T`. Furthermore, the resulting pointer must satisfy the aliasing and mutability laws of references. The compiler assumes these properties are true for any references, no matter how they are created, and so any conversion from @@ -149,7 +149,7 @@ The recommended method for the conversion is ``` let i: u32 = 1; // explicit cast -let p_imm: *u32 = &i as *u32; +let p_imm: *const u32 = &i as *const u32; let mut m: u32 = 2; // implicit coercion let p_mut: *mut u32 = &mut m; @@ -256,7 +256,7 @@ impl<T: Send> Drop for Unique<T> { // Copy the object out from the pointer onto the stack, // where it is covered by normal Rust destructor semantics // and cleans itself up, if necessary - ptr::read(self.ptr as *T); + ptr::read(self.ptr as *const T); // clean-up our allocation free(self.ptr as *mut c_void) @@ -267,12 +267,12 @@ impl<T: Send> Drop for Unique<T> { // A comparison between the built-in `Box` and this reimplementation fn main() { { - let mut x = box 5; + let mut x = box 5i; *x = 10; } // `x` is freed here { - let mut y = Unique::new(5); + let mut y = Unique::new(5i); *y.borrow_mut() = 10; } // `y` is freed here } @@ -457,7 +457,7 @@ extern crate libc; // Entry point for this program #[start] -fn start(_argc: int, _argv: **u8) -> int { +fn start(_argc: int, _argv: *const *const u8) -> int { 0 } @@ -482,7 +482,7 @@ compiler's name mangling too: extern crate libc; #[no_mangle] // ensure that this symbol is called `main` in the output -pub extern fn main(argc: int, argv: **u8) -> int { +pub extern fn main(argc: int, argv: *const *const u8) -> int { 0 } @@ -540,8 +540,8 @@ use core::mem; use core::raw::Slice; #[no_mangle] -pub extern fn dot_product(a: *u32, a_len: u32, - b: *u32, b_len: u32) -> u32 { +pub extern fn dot_product(a: *const u32, a_len: u32, + b: *const u32, b_len: u32) -> u32 { // Convert the provided arrays into Rust slices. // The core::raw module guarantees that the Slice // structure has the same memory layout as a &[T] @@ -573,7 +573,7 @@ extern fn begin_unwind(args: &core::fmt::Arguments, #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} -# #[start] fn start(argc: int, argv: **u8) -> int { 0 } +# #[start] fn start(argc: int, argv: *const *const u8) -> int { 0 } # fn main() {} ``` @@ -595,7 +595,7 @@ standard library itself. > parts of the language may never be full specified and so details may > differ wildly between implementations (and even versions of `rustc` > itself). -> +> > Furthermore, this is just an overview; the best form of > documentation for specific instances of these features are their > definitions and uses in `std`. @@ -627,7 +627,7 @@ via a declaration like extern "rust-intrinsic" { fn transmute<T, U>(x: T) -> U; - fn offset<T>(dst: *T, offset: int) -> *T; + fn offset<T>(dst: *const T, offset: int) -> *const T; } ``` @@ -677,8 +677,8 @@ unsafe fn deallocate(ptr: *mut u8, _size: uint, _align: uint) { } #[start] -fn main(argc: int, argv: **u8) -> int { - let x = box 1; +fn main(argc: int, argv: *const *const u8) -> int { + let x = box 1i; 0 } diff --git a/src/doc/guide.md b/src/doc/guide.md index e5a753f55d0..cadbd8ee9ad 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -160,7 +160,7 @@ Save the file, and then type this into your terminal window: ```{bash} $ rustc hello_world.rs -$ ./hello_world # just 'hello_world' on Windows +$ ./hello_world # or hello_world.exe on Windows Hello, world ``` @@ -243,7 +243,7 @@ There are now two files: our source code, with the `.rs` extension, and the executable (`hello_world.exe` on Windows, `hello_world` everywhere else) ```{bash} -$ ./hello_world # or ./hello_world.exe on Windows +$ ./hello_world # or hello_world.exe on Windows ``` This prints out our `Hello, world!` text to our terminal. @@ -285,8 +285,9 @@ At first, your program doesn't have any dependencies, so we'll only be using the first part of its functionality. Eventually, we'll add more. Since we started off by using Cargo, it'll be easy to add later. -Let's convert Hello World to Cargo. The first thing we need to do is install -it. To do this, we need to build it from source. There are no binaries yet. +Let's convert Hello World to Cargo. The first thing we need to do to begin using Cargo +is to install Cargo. To do this, we need to build it from source. There are no binaries +yet. First, let's go back to our projects directory. We don't want Cargo to live in our project! @@ -412,23 +413,209 @@ rest of your Rust career. Next, we'll learn more about Rust itself, by starting to write a more complicated program. We hope you want to do more with Rust than just print "Hello, world!" -## If +## Guessing Game -## Functions +Let's write a bigger program in Rust. We could just go through a laundry list +of Rust features, but that's boring. Instead, we'll learn more about how to +code in Rust by writing a few example projects. -return +For our first project, we'll implement a classic beginner programming problem: +the guessing game. Here's how it works: Our program will generate a random +integer between one and a hundred. It will then prompt us to enter a guess. +Upon entering our guess, it will tell us if we're too low or too high. Once we +guess correctly, it will congratulate us, and print the number of guesses we've +taken to the screen. Sound good? It sounds easy, but it'll end up showing off a +number of basic features of Rust. -comments +### Set up -## Testing +Let's set up a new project. Go to your projects directory, and make a new +directory for the project, as well as a `src` directory for our code: -attributes +```{bash} +$ cd ~/projects +$ mkdir guessing_game +$ cd guessing_game +$ mkdir src +``` -stability markers +Great. Next, let's make a `Cargo.toml` file so Cargo knows how to build our +project: -## Crates and Modules +```{ignore} +[package] -visibility +name = "guessing_game" +version = "0.1.0" +authors = [ "someone@example.com" ] + +[[bin]] + +name = "guessing_game" +``` + +Finally, we need our source file. Let's just make it hello world for now, so we +can check that our setup works. In `src/guessing_game.rs`: + +```{rust} +fn main() { + println!("Hello world!"); +} +``` + +Let's make sure that worked: + +```{bash} +$ cargo build + Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game) +$ +``` + +Excellent! Open up your `src/guessing_game.rs` again. We'll be writing all of +our code in this file. The next section of the tutorial will show you how to +build multiple-file projects. + +## Variable bindings + +The first thing we'll learn about are 'variable bindings.' They look like this: + +```{rust} +let x = 5i; +``` + +In many languages, this is called a 'variable.' But Rust's variable bindings +have a few tricks up their sleeves. Rust has a very powerful feature called +'pattern matching' that we'll get into detail with later, but the left +hand side of a `let` expression is a full pattern, not just a variable name. +This means we can do things like: + +```{rust} +let (x, y) = (1i, 2i); +``` + +After this expression is evaluated, `x` will be one, and `y` will be two. +Patterns are really powerful, but this is about all we can do with them so far. +So let's just keep this in the back of our minds as we go forward. + +By the way, in these examples, `i` indicates that the number is an integer. + +Rust is a statically typed language, which means that we specify our types up +front. So why does our first example compile? Well, Rust has this thing called +"[Hindley-Milner type +inference](http://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system)", +named after some really smart type theorists. If you clicked that link, don't +be scared: what this means for you is that Rust will attempt to infer the types +in your program, and it's pretty good at it. If it can infer the type, Rust +doesn't require you to actually type it out. + +We can add the type if we want to. Types come after a colon (`:`): + +```{rust} +let x: int = 5; +``` + +If I asked you to read this out loud to the rest of the class, you'd say "`x` +is a binding with the type `int` and the value `five`." Rust requires you to +initialize the binding with a value before you're allowed to use it. If +we try... + +```{ignore} +let x; +``` + +...we'll get an error: + +```{ignore} +src/guessing_game.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type +src/guessing_game.rs:2 let x; + ^ +``` + +Giving it a type will compile, though: + +```{ignore} +let x: int; +``` + +Let's try it out. Change your `src/guessing_game.rs` file to look like this: + +```{rust} +fn main() { + let x: int; + + println!("Hello world!"); +} +``` + +You can use `cargo build` on the command line to build it. You'll get a warning, +but it will still print "Hello, world!": + +```{ignore,notrust} + Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game) +src/guessing_game.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default +src/guessing_game.rs:2 let x: int; + ^ +``` + +Rust warns us that we never use the variable binding, but since we never use it, +no harm, no foul. Things change if we try to actually use this `x`, however. Let's +do that. Change your program to look like this: + +```{rust,ignore} +fn main() { + let x: int; + + println!("The value of x is: {}", x); +} +``` + +And try to build it. You'll get an error: + +```{bash} +$ cargo build + Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game) +src/guessing_game.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` +src/guessing_game.rs:4 println!("The value of x is: {}", x); + ^ +note: in expansion of format_args! +<std macros>:2:23: 2:77 note: expansion site +<std macros>:1:1: 3:2 note: in expansion of println! +src/guessing_game.rs:4:5: 4:42 note: expansion site +error: aborting due to previous error +Could not execute process `rustc src/guessing_game.rs --crate-type bin --out-dir /home/you/projects/guessing_game/target -L /home/you/projects/guessing_game/target -L /home/you/projects/guessing_game/target/deps` (status=101) +``` + +Rust will not let us use a value that has not been initialized. So why let us +declare a binding without initializing it? You'd think our first example would +have errored. Well, Rust is smarter than that. Before we get to that, let's talk +about this stuff we've added to `println!`. + +If you include two curly braces (`{}`, some call them moustaches...) in your +string to print, Rust will interpret this as a request to interpolate some sort +of value. **String interpolation** is a computer science term that means "stick +in the middle of a string." We add a comma, and then `x`, to indicate that we +want `x` to be the value we're interpolating. The comma is used to separate +arguments we pass to functions and macros, if you're passing more than one. + +When you just use the double curly braces, Rust will attempt to display the +value in a meaningful way by checking out its type. If you want to specify the +format in a more detailed manner, there are a [wide number of options +available](/std/fmt/index.html). Fow now, we'll just stick to the default: +integers aren't very complicated to print. + +So, we've cleared up all of the confusion around bindings, with one exception: +why does Rust let us declare a variable binding without an initial value if we +must initialize the binding before we use it? And how does it know that we have +or have not initialized the binding? For that, we need to learn our next +concept: `if`. + +## If + +## Functions + +return + +comments ## Compound Data Types @@ -450,10 +637,35 @@ loop break/continue -iterators +## Guessing Game: complete + +At this point, you have successfully built the Guessing Game! Congratulations! +For reference, [We've placed the sample code on +GitHub](https://github.com/steveklabnik/guessing_game). + +You've now learned the basic syntax of Rust. All of this is relatively close to +various other programming languages you have used in the past. These +fundamental syntactical and semantic elements will form the foundation for the +rest of your Rust education. + +Now that you're an expert at the basics, it's time to learn about some of +Rust's more unique features. + +## iterators ## Lambdas +## Testing + +attributes + +stability markers + +## Crates and Modules + +visibility + + ## Generics ## Traits diff --git a/src/doc/intro.md b/src/doc/intro.md index 1e577a91131..e8928cb5505 100644 --- a/src/doc/intro.md +++ b/src/doc/intro.md @@ -133,7 +133,7 @@ Check it out: ``` fn dangling() -> Box<int> { - let i = box 1234; + let i = box 1234i; return i; } @@ -143,8 +143,8 @@ fn add_one() -> int { } ``` -Now instead of a stack allocated `1234`, -we have a heap allocated `box 1234`. +Now instead of a stack allocated `1234i`, +we have a heap allocated `box 1234i`. Whereas `&` borrows a pointer to existing memory, creating an owned box allocates memory on the heap and places a value in it, giving you the sole pointer to that memory. @@ -152,7 +152,7 @@ You can roughly compare these two lines: ``` // Rust -let i = box 1234; +let i = box 1234i; ``` ```cpp @@ -252,7 +252,7 @@ fn main() { } ``` -This will result an error indicating that the value is no longer in scope: +The compiler will produce an error indicating that the value is no longer in scope: ```text concurrency.rs:12:20: 12:27 error: use of moved value: 'numbers' diff --git a/src/doc/rust.md b/src/doc/rust.md index 9dc5c66a08d..58819a3cf48 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -442,17 +442,14 @@ of integer literal suffix: The type of an _unsuffixed_ integer literal is determined by type inference. If an integer type can be _uniquely_ determined from the surrounding program context, the unsuffixed integer literal has that type. If the program context -underconstrains the type, the unsuffixed integer literal's type is `int`; if -the program context overconstrains the type, it is considered a static type -error. +underconstrains the type, it is considered a static type error; +if the program context overconstrains the type, +it is also considered a static type error. Examples of integer literals of various forms: ~~~~ -123; 0xff00; // type determined by program context - // defaults to int in absence of type - // information - +123i; // type int 123u; // type uint 123_u; // type uint 0xff_u8; // type u8 @@ -469,8 +466,10 @@ A _floating-point literal_ has one of two forms: second decimal literal. * A single _decimal literal_ followed by an _exponent_. -By default, a floating-point literal has a generic type, but will fall back to -`f64`. A floating-point literal may be followed (immediately, without any +By default, a floating-point literal has a generic type, +and, like integer literals, the type must be uniquely determined +from the context. +A floating-point literal may be followed (immediately, without any spaces) by a _floating-point suffix_, which changes the type of the literal. There are two floating-point suffixes: `f32`, and `f64` (the 32-bit and 64-bit floating point types). @@ -478,8 +477,8 @@ floating point types). Examples of floating-point literals of various forms: ~~~~ -123.0; // type f64 -0.1; // type f64 +123.0f64; // type f64 +0.1f64; // type f64 0.1f32; // type f32 12E+99_f64; // type f64 ~~~~ @@ -1614,7 +1613,7 @@ extern crate libc; use libc::{c_char, FILE}; extern { - fn fopen(filename: *c_char, mode: *c_char) -> *FILE; + fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE; } # fn main() {} ~~~~ @@ -2700,9 +2699,9 @@ must be a constant expression that can be evaluated at compile time, such as a [literal](#literals) or a [static item](#static-items). ~~~~ -[1, 2, 3, 4]; +[1i, 2, 3, 4]; ["a", "b", "c", "d"]; -[0, ..128]; // vector with 128 zeros +[0i, ..128]; // vector with 128 zeros [0u8, 0u8, 0u8, 0u8]; ~~~~ @@ -2881,7 +2880,7 @@ equals sign (`=`) and an [rvalue](#lvalues-rvalues-and-temporaries) expression. Evaluating an assignment expression [either copies or moves](#moved-and-copied-types) its right-hand operand to its left-hand operand. ~~~~ -# let mut x = 0; +# let mut x = 0i; # let y = 0; x = y; @@ -2932,7 +2931,7 @@ paren_expr : '(' expr ')' ; An example of a parenthesized expression: ~~~~ -let x = (2 + 3) * 4; +let x: int = (2 + 3) * 4; ~~~~ @@ -3016,7 +3015,7 @@ conditional expression evaluates to `false`, the `while` expression completes. An example: ~~~~ -let mut i = 0; +let mut i = 0u; while i < 10 { println!("hello"); @@ -3262,7 +3261,7 @@ Patterns can also dereference pointers by using the `&`, on `x: &int` are equivalent: ~~~~ -# let x = &3; +# let x = &3i; let y = match *x { 0 => "zero", _ => "some" }; let z = match x { &0 => "zero", _ => "some" }; @@ -3285,7 +3284,7 @@ A range of values may be specified with `..`. For example: ~~~~ -# let x = 2; +# let x = 2i; let message = match x { 0 | 1 => "not many", diff --git a/src/doc/rustdoc.md b/src/doc/rustdoc.md index 2287bcabff7..8199eaea82c 100644 --- a/src/doc/rustdoc.md +++ b/src/doc/rustdoc.md @@ -103,6 +103,17 @@ rustdoc can also generate JSON, for consumption by other tools, with `rustdoc --output-format json`, and also consume already-generated JSON with `rustdoc --input-format json`. +rustdoc also supports personalizing the output from crates' documentation, +similar to markdown options. + +- `--html-in-header FILE`: includes the contents of `FILE` at the + end of the `<head>...</head>` section. +- `--html-before-content FILE`: includes the contents of `FILE` + directly after `<body>`, before the rendered content (including the + search bar). +- `--html-after-content FILE`: includes the contents of `FILE` + after all the rendered content. + # Using the Documentation The web pages generated by rustdoc present the same logical hierarchy that one @@ -238,16 +249,16 @@ detected by a `.md` or `.markdown` extension. There are 4 options to modify the output that Rustdoc creates. - `--markdown-css PATH`: adds a `<link rel="stylesheet">` tag pointing to `PATH`. -- `--markdown-in-header FILE`: includes the contents of `FILE` at the +- `--html-in-header FILE`: includes the contents of `FILE` at the end of the `<head>...</head>` section. -- `--markdown-before-content FILE`: includes the contents of `FILE` +- `--html-before-content FILE`: includes the contents of `FILE` directly after `<body>`, before the rendered content (including the title). -- `--markdown-after-content FILE`: includes the contents of `FILE` +- `--html-after-content FILE`: includes the contents of `FILE` directly before `</body>`, after all the rendered content. All of these can be specified multiple times, and they are output in -the order in which they are specified. The first line of the file must +the order in which they are specified. The first line of the file being rendered must be the title, prefixed with `%` (e.g. this page has `% Rust Documentation` on the first line). diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 456726984bc..5fe6a5f14c2 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -262,7 +262,7 @@ write function, variable, and module names with lowercase letters, using underscores where they help readability, while writing types in camel case. ~~~ -let my_variable = 100; +let my_variable = 100i; type MyType = int; // primitive types are _not_ camel case ~~~ @@ -276,7 +276,7 @@ write a piece of code like this: ~~~~ # let item = "salad"; -let price; +let price: f64; if item == "salad" { price = 3.50; } else if item == "muffin" { @@ -290,7 +290,7 @@ But, in Rust, you don't have to repeat the name `price`: ~~~~ # let item = "salad"; -let price = +let price: f64 = if item == "salad" { 3.50 } else if item == "muffin" { @@ -337,11 +337,10 @@ suffix that can be used to indicate the type of a literal: `i` for `int`, In the absence of an integer literal suffix, Rust will infer the integer type based on type annotations and function signatures in the surrounding program. In the absence of any type information at all, -Rust will assume that an unsuffixed integer literal has type -`int`. +Rust will report an error and request that the type be specified explicitly. ~~~~ -let a = 1; // `a` is an `int` +let a: int = 1; // `a` is an `int` let b = 10i; // `b` is an `int`, due to the `i` suffix let c = 100u; // `c` is a `uint` let d = 1000i32; // `d` is an `i32` @@ -475,7 +474,7 @@ against each pattern in order until one matches. The matching pattern executes its corresponding arm. ~~~~ -let my_number = 1; +let my_number = 1i; match my_number { 0 => println!("zero"), 1 | 2 => println!("one or two"), @@ -501,7 +500,7 @@ matches any single value. (`..`) is a different wildcard that can match one or more fields in an `enum` variant. ~~~ -# let my_number = 1; +# let my_number = 1i; match my_number { 0 => { println!("zero") } _ => { println!("something else") } @@ -584,7 +583,7 @@ keyword `break` aborts the loop, and `continue` aborts the current iteration and continues with the next. ~~~~ -let mut cake_amount = 8; +let mut cake_amount = 8i; while cake_amount > 0 { cake_amount -= 1; } @@ -944,7 +943,7 @@ The `box` operator performs memory allocation on the heap: ~~~~ { // an integer allocated on the heap - let y = box 10; + let y = box 10i; } // the destructor frees the heap memory as soon as `y` goes out of scope ~~~~ @@ -1165,7 +1164,7 @@ let z = x; The mutability of a value may be changed by moving it to a new owner: ~~~~ -let r = box 13; +let r = box 13i; let mut s = r; // box becomes mutable *s += 1; let t = s; // box becomes immutable @@ -1285,9 +1284,9 @@ Using the generic `List<T>` works much like before, thanks to type inference: # Cons(value, box xs) # } let mut xs = Nil; // Unknown type! This is a `List<T>`, but `T` can be anything. -xs = prepend(xs, 10); // Here the compiler infers `xs`'s type as `List<int>`. -xs = prepend(xs, 15); -xs = prepend(xs, 20); +xs = prepend(xs, 10i); // Here the compiler infers `xs`'s type as `List<int>`. +xs = prepend(xs, 15i); +xs = prepend(xs, 20i); ~~~ The code sample above demonstrates type inference making most type annotations optional. It is @@ -1410,12 +1409,12 @@ Beyond the properties granted by the size, an owned box behaves as a regular value by inheriting the mutability and lifetime of the owner: ~~~~ -let x = 5; // immutable -let mut y = 5; // mutable +let x = 5i; // immutable +let mut y = 5i; // mutable y += 2; -let x = box 5; // immutable -let mut y = box 5; // mutable +let x = box 5i; // immutable +let mut y = box 5i; // mutable *y += 2; // the `*` operator is needed to access the contained value ~~~~ @@ -1507,7 +1506,7 @@ freezing enforced statically at compile-time. An example of a non-`Freeze` type is [`RefCell<T>`][refcell]. ~~~~ -let mut x = 5; +let mut x = 5i; { let y = &x; // `x` is now frozen. It cannot be modified or re-assigned. } @@ -1523,8 +1522,8 @@ Rust uses the unary star operator (`*`) to access the contents of a box or pointer, similarly to C. ~~~ -let owned = box 10; -let borrowed = &20; +let owned = box 10i; +let borrowed = &20i; let sum = *owned + *borrowed; ~~~ @@ -1534,9 +1533,9 @@ assignments. Such an assignment modifies the value that the pointer points to. ~~~ -let mut owned = box 10; +let mut owned = box 10i; -let mut value = 20; +let mut value = 20i; let borrowed = &mut value; *owned = *borrowed + 100; @@ -1654,12 +1653,12 @@ Unicode code points, so they cannot be freely mutated without the ability to alter the length. ~~~ -let mut xs = [1, 2, 3]; +let mut xs = [1i, 2i, 3i]; let view = xs.mut_slice(0, 2); view[0] = 5; // The type of a mutable slice is written as `&mut [T]` -let ys: &mut [int] = &mut [1, 2, 3]; +let ys: &mut [int] = &mut [1i, 2i, 3i]; ~~~ Square brackets denote indexing into a slice or fixed-size vector: diff --git a/src/etc/licenseck.py b/src/etc/licenseck.py index c2f56c6a807..2110f19bf86 100644 --- a/src/etc/licenseck.py +++ b/src/etc/licenseck.py @@ -44,6 +44,7 @@ exceptions = [ "libsync/mpsc_intrusive.rs", # BSD "test/bench/shootout-binarytrees.rs", # BSD "test/bench/shootout-fannkuch-redux.rs", # BSD + "test/bench/shootout-mandelbrot.rs", # BSD "test/bench/shootout-meteor.rs", # BSD "test/bench/shootout-pidigits.rs", # BSD "test/bench/shootout-regex-dna.rs", # BSD diff --git a/src/etc/vim/syntax/rust.vim b/src/etc/vim/syntax/rust.vim index d8f00ac6b30..a15bd3ca60f 100644 --- a/src/etc/vim/syntax/rust.vim +++ b/src/etc/vim/syntax/rust.vim @@ -77,34 +77,39 @@ syn keyword rustEnumVariant Ok Err "syn keyword rustFunction drop " Types and traits {{{3 -syn keyword rustTrait Ascii AsciiCast OwnedAsciiCast AsciiStr IntoBytes +syn keyword rustTrait Ascii AsciiCast OwnedAsciiCast AsciiStr +syn keyword rustTrait IntoBytes syn keyword rustTrait ToCStr syn keyword rustTrait Char syn keyword rustTrait Clone -syn keyword rustTrait Eq Ord PartialEq PartialOrd Ordering Equiv +syn keyword rustTrait PartialEq PartialOrd Eq Ord Equiv +syn keyword rustEnum Ordering syn keyword rustEnumVariant Less Equal Greater -syn keyword rustTrait Container Mutable Map MutableMap Set MutableSet -syn keyword rustTrait FromIterator Extendable -syn keyword rustTrait Iterator DoubleEndedIterator RandomAccessIterator CloneableIterator -syn keyword rustTrait OrdIterator MutableDoubleEndedIterator ExactSize -syn keyword rustTrait Num NumCast CheckedAdd CheckedSub CheckedMul -syn keyword rustTrait Signed Unsigned -syn keyword rustTrait Primitive Int Float FloatMath ToPrimitive FromPrimitive -"syn keyword rustTrait Expect +syn keyword rustTrait Collection Mutable Map MutableMap +syn keyword rustTrait Set MutableSet +syn keyword rustTrait FromIterator Extendable ExactSize +syn keyword rustTrait Iterator DoubleEndedIterator +syn keyword rustTrait RandomAccessIterator CloneableIterator +syn keyword rustTrait OrdIterator MutableDoubleEndedIterator +syn keyword rustTrait Num NumCast CheckedAdd CheckedSub CheckedMul CheckedDiv +syn keyword rustTrait Signed Unsigned Primitive Int Float +syn keyword rustTrait FloatMath ToPrimitive FromPrimitive syn keyword rustTrait Box syn keyword rustTrait GenericPath Path PosixPath WindowsPath syn keyword rustTrait RawPtr syn keyword rustTrait Buffer Writer Reader Seek -syn keyword rustTrait Str StrVector StrSlice OwnedStr IntoMaybeOwned -syn keyword rustTrait StrAllocating +syn keyword rustTrait Str StrVector StrSlice OwnedStr +syn keyword rustTrait IntoMaybeOwned StrAllocating syn keyword rustTrait ToStr IntoStr syn keyword rustTrait Tuple1 Tuple2 Tuple3 Tuple4 syn keyword rustTrait Tuple5 Tuple6 Tuple7 Tuple8 syn keyword rustTrait Tuple9 Tuple10 Tuple11 Tuple12 -syn keyword rustTrait CloneableVector ImmutableCloneableVector MutableCloneableVector +syn keyword rustTrait CloneableVector ImmutableCloneableVector +syn keyword rustTrait MutableCloneableVector MutableOrdVector syn keyword rustTrait ImmutableVector MutableVector -syn keyword rustTrait ImmutableEqVector ImmutableOrdVector MutableOrdVector -syn keyword rustTrait Vector VectorVector OwnedVector MutableVectorAllocating +syn keyword rustTrait ImmutableEqVector ImmutableOrdVector +syn keyword rustTrait Vector VectorVector +syn keyword rustTrait MutableVectorAllocating syn keyword rustTrait String syn keyword rustTrait Vec diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 6af4083edb2..38ed511c458 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -376,14 +376,14 @@ mod tests { #[test] fn test_live() { - let x = Arc::new(5); + let x = Arc::new(5i); let y = x.downgrade(); assert!(y.upgrade().is_some()); } #[test] fn test_dead() { - let x = Arc::new(5); + let x = Arc::new(5i); let y = x.downgrade(); drop(x); assert!(y.upgrade().is_none()); diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index b4d0057778a..dc8280e9b83 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -99,7 +99,7 @@ pub static mut EMPTY: uint = 12345; #[inline] unsafe fn exchange_malloc(size: uint, align: uint) -> *mut u8 { if size == 0 { - &EMPTY as *uint as *mut u8 + &EMPTY as *const uint as *mut u8 } else { allocate(size, align) } @@ -144,9 +144,10 @@ mod imp { flags: c_int) -> size_t; fn je_dallocx(ptr: *mut c_void, flags: c_int); fn je_nallocx(size: size_t, flags: c_int) -> size_t; - fn je_malloc_stats_print(write_cb: Option<extern "C" fn(cbopaque: *mut c_void, *c_char)>, + fn je_malloc_stats_print(write_cb: Option<extern "C" fn(cbopaque: *mut c_void, + *const c_char)>, cbopaque: *mut c_void, - opts: *c_char); + opts: *const c_char); } // -lpthread needs to occur after -ljemalloc, the earlier argument isn't enough @@ -226,7 +227,7 @@ mod imp { // a block of memory, so we special case everything under `*uint` to // just pass it to malloc, which is guaranteed to align to at least the // size of `*uint`. - if align < mem::size_of::<*uint>() { + if align < mem::size_of::<uint>() { libc_heap::malloc_raw(size) } else { let mut out = 0 as *mut libc::c_void; @@ -244,7 +245,7 @@ mod imp { pub unsafe fn reallocate(ptr: *mut u8, size: uint, align: uint, old_size: uint) -> *mut u8 { let new_ptr = allocate(size, align); - ptr::copy_memory(new_ptr, ptr as *u8, old_size); + ptr::copy_memory(new_ptr, ptr as *const u8, old_size); deallocate(ptr, old_size, align); return new_ptr; } @@ -328,7 +329,7 @@ mod bench { #[bench] fn alloc_owned_small(b: &mut Bencher) { b.iter(|| { - box 10 + box 10i }) } } diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 29293366e50..26b8ccaf573 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -70,7 +70,6 @@ #![no_std] #![feature(lang_items, phase, unsafe_destructor)] -#![allow(unknown_features)] // NOTE: remove after a stage0 snap #[phase(plugin, link)] extern crate core; diff --git a/src/liballoc/owned.rs b/src/liballoc/owned.rs index 6f5d3293556..addec396bbe 100644 --- a/src/liballoc/owned.rs +++ b/src/liballoc/owned.rs @@ -16,7 +16,9 @@ use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::intrinsics; +use core::kinds::Send; use core::mem; +use core::option::Option; use core::raw::TraitObject; use core::result::{Ok, Err, Result}; @@ -36,7 +38,7 @@ pub static HEAP: () = (); /// A type that represents a uniquely-owned value. #[lang="owned_box"] -pub struct Box<T>(*T); +pub struct Box<T>(*mut T); impl<T: Default> Default for Box<T> { fn default() -> Box<T> { box Default::default() } @@ -64,6 +66,10 @@ impl<T:PartialEq> PartialEq for Box<T> { } impl<T:PartialOrd> PartialOrd for Box<T> { #[inline] + fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> { + (**self).partial_cmp(*other) + } + #[inline] fn lt(&self, other: &Box<T>) -> bool { *(*self) < *(*other) } #[inline] fn le(&self, other: &Box<T>) -> bool { *(*self) <= *(*other) } @@ -106,6 +112,34 @@ impl AnyOwnExt for Box<Any> { } } +/// Extension methods for an owning `Any+Send` trait object +pub trait AnySendOwnExt { + /// Returns the boxed value if it is of type `T`, or + /// `Err(Self)` if it isn't. + fn move_send<T: 'static>(self) -> Result<Box<T>, Self>; +} + +impl AnySendOwnExt for Box<Any+Send> { + #[inline] + fn move_send<T: 'static>(self) -> Result<Box<T>, Box<Any+Send>> { + if self.is::<T>() { + unsafe { + // Get the raw representation of the trait object + let to: TraitObject = + *mem::transmute::<&Box<Any+Send>, &TraitObject>(&self); + + // Prevent destructor on self being run + intrinsics::forget(self); + + // Extract the data pointer + Ok(mem::transmute(to.data)) + } + } else { + Err(self) + } + } +} + impl<T: fmt::Show> fmt::Show for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) @@ -117,3 +151,51 @@ impl fmt::Show for Box<Any> { f.pad("Box<Any>") } } + +#[cfg(test)] +mod test { + #[test] + fn test_owned_clone() { + let a = box 5i; + let b: Box<int> = a.clone(); + assert!(a == b); + } + + #[test] + fn any_move() { + let a = box 8u as Box<Any>; + let b = box Test as Box<Any>; + + match a.move::<uint>() { + Ok(a) => { assert!(a == box 8u); } + Err(..) => fail!() + } + match b.move::<Test>() { + Ok(a) => { assert!(a == box Test); } + Err(..) => fail!() + } + + let a = box 8u as Box<Any>; + let b = box Test as Box<Any>; + + assert!(a.move::<Box<Test>>().is_err()); + assert!(b.move::<Box<uint>>().is_err()); + } + + #[test] + fn test_show() { + let a = box 8u as Box<Any>; + let b = box Test as Box<Any>; + let a_str = a.to_str(); + let b_str = b.to_str(); + assert_eq!(a_str.as_slice(), "Box<Any>"); + assert_eq!(b_str.as_slice(), "Box<Any>"); + + let a = &8u as &Any; + let b = &Test as &Any; + let s = format!("{}", a); + assert_eq!(s.as_slice(), "&Any"); + let s = format!("{}", b); + assert_eq!(s.as_slice(), "&Any"); + } +} diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index a3ca72f1547..d97bce39c2d 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -10,16 +10,141 @@ /*! Task-local reference-counted boxes (`Rc` type) -The `Rc` type provides shared ownership of an immutable value. Destruction is deterministic, and -will occur as soon as the last owner is gone. It is marked as non-sendable because it avoids the -overhead of atomic reference counting. +The `Rc` type provides shared ownership of an immutable value. Destruction is +deterministic, and will occur as soon as the last owner is gone. It is marked +as non-sendable because it avoids the overhead of atomic reference counting. -The `downgrade` method can be used to create a non-owning `Weak` pointer to the box. A `Weak` -pointer can be upgraded to an `Rc` pointer, but will return `None` if the value has already been -freed. +The `downgrade` method can be used to create a non-owning `Weak` pointer to the +box. A `Weak` pointer can be upgraded to an `Rc` pointer, but will return +`None` if the value has already been freed. -For example, a tree with parent pointers can be represented by putting the nodes behind `Strong` -pointers, and then storing the parent pointers as `Weak` pointers. +For example, a tree with parent pointers can be represented by putting the +nodes behind strong `Rc` pointers, and then storing the parent pointers as +`Weak` pointers. + + +## Examples + +Consider a scenario where a set of Gadgets are owned by a given Owner. We want +to have our Gadgets point to their Owner. We can't do this with unique +ownership, because more than one gadget may belong to the same Owner. Rc +allows us to share an Owner between multiple Gadgets, and have the Owner kept +alive as long as any Gadget points at it. + +```rust +use std::rc::Rc; + +struct Owner { + name: String + // ...other fields +} + +struct Gadget { + id: int, + owner: Rc<Owner> + // ...other fields +} + +fn main() { + // Create a reference counted Owner. + let gadget_owner : Rc<Owner> = Rc::new( + Owner { name: String::from_str("Gadget Man") } + ); + + // Create Gadgets belonging to gadget_owner. To increment the reference + // count we clone the Rc object. + let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() }; + let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() }; + + drop(gadget_owner); + + // Despite dropping gadget_owner, we're still able to print out the name of + // the Owner of the Gadgets. This is because we've only dropped the + // reference count object, not the Owner it wraps. As long as there are + // other Rc objects pointing at the same Owner, it will stay alive. Notice + // that the Rc wrapper around Gadget.owner gets automatically dereferenced + // for us. + println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name); + println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name); + + // At the end of the method, gadget1 and gadget2 get destroyed, and with + // them the last counted references to our Owner. Gadget Man now gets + // destroyed as well. +} +``` + +If our requirements change, and we also need to be able to traverse from +Owner->Gadget, we will run into problems: an Rc pointer from Owner->Gadget +introduces a cycle between the objects. This means that their reference counts +can never reach 0, and the objects will stay alive: a memory leak. In order to +get around this, we can use `Weak` pointers. These are reference counted +pointers that don't keep an object alive if there are no normal `Rc` (or +*strong*) pointers left. + +Rust actually makes it somewhat difficult to produce this loop in the first +place: in order to end up with two objects that point at each other, one of +them needs to be mutable. This is problematic because Rc enforces memory +safety by only giving out shared references to the object it wraps, and these +don't allow direct mutation. We need to wrap the part of the object we wish to +mutate in a `RefCell`, which provides *interior mutability*: a method to +achieve mutability through a shared reference. `RefCell` enforces Rust's +borrowing rules at runtime. Read the `Cell` documentation for more details on +interior mutability. + +```rust +use std::rc::Rc; +use std::rc::Weak; +use std::cell::RefCell; + +struct Owner { + name: String, + gadgets: RefCell<Vec<Weak<Gadget>>> + // ...other fields +} + +struct Gadget { + id: int, + owner: Rc<Owner> + // ...other fields +} + +fn main() { + // Create a reference counted Owner. Note the fact that we've put the + // Owner's vector of Gadgets inside a RefCell so that we can mutate it + // through a shared reference. + let gadget_owner : Rc<Owner> = Rc::new( + Owner { + name: "Gadget Man".to_string(), + gadgets: RefCell::new(Vec::new()) + } + ); + + // Create Gadgets belonging to gadget_owner as before. + let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()}); + let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()}); + + // Add the Gadgets to their Owner. To do this we mutably borrow from + // the RefCell holding the Owner's Gadgets. + gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade()); + gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade()); + + // Iterate over our Gadgets, printing their details out + for gadget_opt in gadget_owner.gadgets.borrow().iter() { + + // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee + // that their object is still alive, we need to call upgrade() on them + // to turn them into a strong reference. This returns an Option, which + // contains a reference to our object if it still exists. + let gadget = gadget_opt.upgrade().unwrap(); + println!("Gadget {} owned by {}", gadget.id, gadget.owner.name); + } + + // At the end of the method, gadget_owner, gadget1 and gadget2 get + // destroyed. There are now no strong (Rc) references to the gadgets. + // Once they get destroyed, the Gadgets get destroyed. This zeroes the + // reference count on Gadget Man, so he gets destroyed as well. +} +``` */ @@ -27,6 +152,7 @@ use core::mem::transmute; use core::cell::Cell; use core::clone::Clone; use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; +use core::default::Default; use core::kinds::marker; use core::ops::{Deref, Drop}; use core::option::{Option, Some, None}; @@ -152,6 +278,13 @@ impl<T> Clone for Rc<T> { } } +impl<T: Default> Default for Rc<T> { + #[inline] + fn default() -> Rc<T> { + Rc::new(Default::default()) + } +} + impl<T: PartialEq> PartialEq for Rc<T> { #[inline(always)] fn eq(&self, other: &Rc<T>) -> bool { **self == **other } @@ -163,6 +296,11 @@ impl<T: Eq> Eq for Rc<T> {} impl<T: PartialOrd> PartialOrd for Rc<T> { #[inline(always)] + fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> { + (**self).partial_cmp(&**other) + } + + #[inline(always)] fn lt(&self, other: &Rc<T>) -> bool { **self < **other } #[inline(always)] diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index f7c4831b5bf..917de94470b 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -55,7 +55,7 @@ impl Chunk { self.data.borrow().capacity() } - unsafe fn as_ptr(&self) -> *u8 { + unsafe fn as_ptr(&self) -> *const u8 { self.data.borrow().as_ptr() } } @@ -140,22 +140,22 @@ unsafe fn destroy_chunk(chunk: &Chunk) { let fill = chunk.fill.get(); while idx < fill { - let tydesc_data: *uint = mem::transmute(buf.offset(idx as int)); + let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int)); let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data); let (size, align) = ((*tydesc).size, (*tydesc).align); - let after_tydesc = idx + mem::size_of::<*TyDesc>(); + let after_tydesc = idx + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", // start, size, align, is_done); if is_done { - ((*tydesc).drop_glue)(buf.offset(start as int) as *i8); + ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8); } // Find where the next tydesc lives - idx = round_up(start + size, mem::align_of::<*TyDesc>()); + idx = round_up(start + size, mem::align_of::<*const TyDesc>()); } } @@ -164,12 +164,12 @@ unsafe fn destroy_chunk(chunk: &Chunk) { // is necessary in order to properly do cleanup if a failure occurs // during an initializer. #[inline] -fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint { +fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { p as uint | (is_done as uint) } #[inline] -fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) { - ((p & !1) as *TyDesc, p & 1 == 1) +fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) { + ((p & !1) as *const TyDesc, p & 1 == 1) } impl Arena { @@ -178,7 +178,7 @@ impl Arena { } // Functions for the POD part of the arena - fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *u8 { + fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.copy_head.borrow().clone()); @@ -190,7 +190,7 @@ impl Arena { } #[inline] - fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *u8 { + fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 { let start = round_up(self.copy_head.borrow().fill.get(), align); let end = start + n_bytes; @@ -218,7 +218,8 @@ impl Arena { } // Functions for the non-POD part of the arena - fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*u8, *u8) { + fn alloc_noncopy_grow(&self, n_bytes: uint, + align: uint) -> (*const u8, *const u8) { // Allocate a new chunk. let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size()); self.chunks.borrow_mut().push(self.head.borrow().clone()); @@ -230,7 +231,8 @@ impl Arena { } #[inline] - fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*u8, *u8) { + fn alloc_noncopy_inner(&self, n_bytes: uint, + align: uint) -> (*const u8, *const u8) { // Be careful to not maintain any `head` borrows active, because // `alloc_noncopy_grow` borrows it mutably. let (start, end, tydesc_start, head_capacity) = { @@ -238,7 +240,7 @@ impl Arena { let fill = head.fill.get(); let tydesc_start = fill; - let after_tydesc = fill + mem::size_of::<*TyDesc>(); + let after_tydesc = fill + mem::size_of::<*const TyDesc>(); let start = round_up(after_tydesc, align); let end = start + n_bytes; @@ -250,7 +252,7 @@ impl Arena { } let head = self.head.borrow(); - head.fill.set(round_up(end, mem::align_of::<*TyDesc>())); + head.fill.set(round_up(end, mem::align_of::<*const TyDesc>())); unsafe { let buf = head.as_ptr(); @@ -348,11 +350,11 @@ fn test_arena_destructors_fail() { /// run again for these objects. pub struct TypedArena<T> { /// A pointer to the next object to be allocated. - ptr: Cell<*T>, + ptr: Cell<*const T>, /// A pointer to the end of the allocated area. When this pointer is /// reached, a new chunk is allocated. - end: Cell<*T>, + end: Cell<*const T>, /// A pointer to the first arena segment. first: RefCell<TypedArenaChunkRef<T>>, @@ -398,7 +400,7 @@ impl<T> TypedArenaChunk<T> { if intrinsics::needs_drop::<T>() { let mut start = self.start(); for _ in range(0, len) { - ptr::read(start as *T); // run the destructor on the pointer + ptr::read(start as *const T); // run the destructor on the pointer start = start.offset(mem::size_of::<T>() as int) } } @@ -417,8 +419,8 @@ impl<T> TypedArenaChunk<T> { // Returns a pointer to the first allocated object. #[inline] - fn start(&self) -> *u8 { - let this: *TypedArenaChunk<T> = self; + fn start(&self) -> *const u8 { + let this: *const TypedArenaChunk<T> = self; unsafe { mem::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>())) @@ -427,7 +429,7 @@ impl<T> TypedArenaChunk<T> { // Returns a pointer to the end of the allocated space. #[inline] - fn end(&self) -> *u8 { + fn end(&self) -> *const u8 { unsafe { let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap(); self.start().offset(size as int) @@ -448,8 +450,8 @@ impl<T> TypedArena<T> { pub fn with_capacity(capacity: uint) -> TypedArena<T> { let chunk = TypedArenaChunk::<T>::new(None, capacity); TypedArena { - ptr: Cell::new(chunk.start() as *T), - end: Cell::new(chunk.end() as *T), + ptr: Cell::new(chunk.start() as *const T), + end: Cell::new(chunk.end() as *const T), first: RefCell::new(Some(chunk)), } } @@ -477,8 +479,8 @@ impl<T> TypedArena<T> { let chunk = self.first.borrow_mut().take_unwrap(); let new_capacity = chunk.capacity.checked_mul(&2).unwrap(); let chunk = TypedArenaChunk::<T>::new(Some(chunk), new_capacity); - self.ptr.set(chunk.start() as *T); - self.end.set(chunk.end() as *T); + self.ptr.set(chunk.start() as *const T); + self.end.set(chunk.end() as *const T); *self.first.borrow_mut() = Some(chunk) } } diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index 64bee05a379..92abfaad348 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -107,8 +107,8 @@ impl<K: Ord, V: Eq> PartialEq for BTree<K, V> { impl<K: Ord, V: Eq> Eq for BTree<K, V> {} impl<K: Ord, V: Eq> PartialOrd for BTree<K, V> { - fn lt(&self, other: &BTree<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &BTree<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -229,8 +229,8 @@ impl<K: Ord, V: Eq> PartialEq for Node<K, V> { impl<K: Ord, V: Eq> Eq for Node<K, V> {} impl<K: Ord, V: Eq> PartialOrd for Node<K, V> { - fn lt(&self, other: &Node<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &Node<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -408,8 +408,8 @@ impl<K: Ord, V: Eq> PartialEq for Leaf<K, V> { impl<K: Ord, V: Eq> Eq for Leaf<K, V> {} impl<K: Ord, V: Eq> PartialOrd for Leaf<K, V> { - fn lt(&self, other: &Leaf<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &Leaf<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -638,8 +638,8 @@ impl<K: Ord, V: Eq> PartialEq for Branch<K, V> { impl<K: Ord, V: Eq> Eq for Branch<K, V> {} impl<K: Ord, V: Eq> PartialOrd for Branch<K, V> { - fn lt(&self, other: &Branch<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &Branch<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -706,8 +706,8 @@ impl<K: Ord, V: Eq> PartialEq for LeafElt<K, V> { impl<K: Ord, V: Eq> Eq for LeafElt<K, V> {} impl<K: Ord, V: Eq> PartialOrd for LeafElt<K, V> { - fn lt(&self, other: &LeafElt<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &LeafElt<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -755,8 +755,8 @@ impl<K: Ord, V: Eq> PartialEq for BranchElt<K, V>{ impl<K: Ord, V: Eq> Eq for BranchElt<K, V>{} impl<K: Ord, V: Eq> PartialOrd for BranchElt<K, V> { - fn lt(&self, other: &BranchElt<K, V>) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &BranchElt<K, V>) -> Option<Ordering> { + Some(self.cmp(other)) } } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 0ae0f906893..4114c8cb1c4 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -595,17 +595,8 @@ impl<A: PartialEq> PartialEq for DList<A> { } impl<A: PartialOrd> PartialOrd for DList<A> { - fn lt(&self, other: &DList<A>) -> bool { - iter::order::lt(self.iter(), other.iter()) - } - fn le(&self, other: &DList<A>) -> bool { - iter::order::le(self.iter(), other.iter()) - } - fn gt(&self, other: &DList<A>) -> bool { - iter::order::gt(self.iter(), other.iter()) - } - fn ge(&self, other: &DList<A>) -> bool { - iter::order::ge(self.iter(), other.iter()) + fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> { + iter::order::partial_cmp(self.iter(), other.iter()) } } @@ -652,7 +643,7 @@ mod tests { (None , None ) => {} (None , _ ) => fail!("prev link for list_head"), (Some(p), Some(pptr)) => { - assert_eq!(p as *Node<T>, pptr as *Node<T>); + assert_eq!(p as *const Node<T>, pptr as *const Node<T>); } _ => fail!("prev link is none, not good"), } diff --git a/src/libcollections/hash/mod.rs b/src/libcollections/hash/mod.rs index a0c0c9f9735..e3d1c9a3216 100644 --- a/src/libcollections/hash/mod.rs +++ b/src/libcollections/hash/mod.rs @@ -247,7 +247,7 @@ impl<S: Writer, T: Hash<S>> Hash<S> for Option<T> { } } -impl<S: Writer, T> Hash<S> for *T { +impl<S: Writer, T> Hash<S> for *const T { #[inline] fn hash(&self, state: &mut S) { // NB: raw-pointer Hash does _not_ dereference @@ -342,12 +342,12 @@ mod tests { assert_eq!(hasher.hash(& &[1u8, 2u8, 3u8]), 9); unsafe { - let ptr: *int = mem::transmute(5); + let ptr: *const int = mem::transmute(5i); assert_eq!(hasher.hash(&ptr), 5); } unsafe { - let ptr: *mut int = mem::transmute(5); + let ptr: *mut int = mem::transmute(5i); assert_eq!(hasher.hash(&ptr), 5); } } diff --git a/src/libcollections/hash/sip.rs b/src/libcollections/hash/sip.rs index 887b0fb0b8a..4fd98538af7 100644 --- a/src/libcollections/hash/sip.rs +++ b/src/libcollections/hash/sip.rs @@ -265,8 +265,6 @@ pub fn hash_with_keys<T: Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 { state.result() } - - #[cfg(test)] mod tests { use test::Bencher; diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs index be0d603696b..5e19accdd67 100644 --- a/src/libcollections/ringbuf.rs +++ b/src/libcollections/ringbuf.rs @@ -572,7 +572,7 @@ mod tests { fn bench_push_back(b: &mut test::Bencher) { let mut deq = RingBuf::new(); b.iter(|| { - deq.push_back(0); + deq.push_back(0i); }) } @@ -580,7 +580,7 @@ mod tests { fn bench_push_front(b: &mut test::Bencher) { let mut deq = RingBuf::new(); b.iter(|| { - deq.push_front(0); + deq.push_front(0i); }) } @@ -589,7 +589,7 @@ mod tests { let mut deq = RingBuf::new(); b.iter(|| { for _ in range(0i, 65) { - deq.push_front(1); + deq.push_front(1i); } }) } @@ -651,10 +651,10 @@ mod tests { #[test] fn test_with_capacity() { let mut d = RingBuf::with_capacity(0); - d.push_back(1); + d.push_back(1i); assert_eq!(d.len(), 1); let mut d = RingBuf::with_capacity(50); - d.push_back(1); + d.push_back(1i); assert_eq!(d.len(), 1); } diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index ac8ac6102f3..40cf8495a40 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -17,7 +17,7 @@ Vectors are Rust's list type. Vectors contain zero or more values of homogeneous types: ```rust -let int_vector = [1,2,3]; +let int_vector = [1i, 2i, 3i]; let str_vector = ["one", "two", "three"]; ``` @@ -41,9 +41,9 @@ An example is the method `.slice(a, b)` that returns an immutable "view" into a vector or a vector slice from the index interval `[a, b)`: ```rust -let numbers = [0, 1, 2]; +let numbers = [0i, 1i, 2i]; let last_numbers = numbers.slice(1, 3); -// last_numbers is now &[1, 2] +// last_numbers is now &[1i, 2i] ``` Traits defined for the `~[T]` type, like `OwnedVector`, can only be called @@ -54,9 +54,9 @@ An example is the method `.push(element)` that will add an element at the end of the vector: ```rust -let mut numbers = vec![0, 1, 2]; +let mut numbers = vec![0i, 1i, 2i]; numbers.push(7); -// numbers is now vec![0, 1, 2, 7]; +// numbers is now vec![0i, 1i, 2i, 7i]; ``` ## Implementations of other traits @@ -341,7 +341,7 @@ fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) { let mut j = i; unsafe { // `i` is in bounds. - let read_ptr = buf_v.offset(i) as *T; + let read_ptr = buf_v.offset(i) as *const T; // find where to insert, we need to do strict <, // rather than <=, to maintain stability. @@ -365,7 +365,7 @@ fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) { &*buf_v.offset(j), (i - j) as uint); ptr::copy_nonoverlapping_memory(buf_v.offset(j), - &tmp as *T, + &tmp as *const T, 1); mem::forget(tmp); } @@ -779,7 +779,7 @@ mod tests { fn test_is_empty() { let xs: [int, ..0] = []; assert!(xs.is_empty()); - assert!(![0].is_empty()); + assert!(![0i].is_empty()); } #[test] @@ -1528,7 +1528,7 @@ mod tests { fn test_permute_fail() { let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))]; - let mut i = 0; + let mut i = 0u; for _ in v.permutations() { if i == 2 { fail!() @@ -1870,16 +1870,16 @@ mod tests { fn test_overflow_does_not_cause_segfault() { let mut v = vec![]; v.reserve_exact(-1); - v.push(1); + v.push(1i); v.push(2); } #[test] #[should_fail] fn test_overflow_does_not_cause_segfault_managed() { - let mut v = vec![Rc::new(1)]; + let mut v = vec![Rc::new(1i)]; v.reserve_exact(-1); - v.push(Rc::new(2)); + v.push(Rc::new(2i)); } #[test] @@ -2279,7 +2279,7 @@ mod bench { v.set_len(1024); } for x in v.mut_iter() { - *x = 0; + *x = 0i; } v }); diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 642e7cfc9a3..fd8ce11d0b5 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -97,6 +97,15 @@ Section: Creating a string /// /// Returns `Err` with the original vector if the vector contains invalid /// UTF-8. +/// +/// # Example +/// +/// ```rust +/// use std::str; +/// let hello_vec = vec![104, 101, 108, 108, 111]; +/// let string = str::from_utf8_owned(hello_vec); +/// assert_eq!(string, Ok("hello".to_string())); +/// ``` pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> { String::from_utf8(vv) } @@ -106,12 +115,28 @@ pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> { /// # Failure /// /// Fails if invalid UTF-8 +/// +/// # Example +/// +/// ```rust +/// use std::str; +/// let string = str::from_byte(104); +/// assert_eq!(string.as_slice(), "h"); +/// ``` pub fn from_byte(b: u8) -> String { assert!(b < 128u8); String::from_char(1, b as char) } /// Convert a char to a string +/// +/// # Example +/// +/// ```rust +/// use std::str; +/// let string = str::from_char('b'); +/// assert_eq!(string.as_slice(), "b"); +/// ``` pub fn from_char(ch: char) -> String { let mut buf = String::new(); buf.push_char(ch); @@ -119,6 +144,15 @@ pub fn from_char(ch: char) -> String { } /// Convert a vector of chars to a string +/// +/// # Example +/// +/// ```rust +/// use std::str; +/// let chars = ['h', 'e', 'l', 'l', 'o']; +/// let string = str::from_chars(chars); +/// assert_eq!(string.as_slice(), "hello"); +/// ``` pub fn from_chars(chs: &[char]) -> String { chs.iter().map(|c| *c).collect() } @@ -572,8 +606,8 @@ impl<'a> Eq for MaybeOwned<'a> {} impl<'a> PartialOrd for MaybeOwned<'a> { #[inline] - fn lt(&self, other: &MaybeOwned) -> bool { - self.as_slice().lt(&other.as_slice()) + fn partial_cmp(&self, other: &MaybeOwned) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -661,7 +695,7 @@ pub mod raw { pub use core::str::raw::{slice_unchecked}; /// Create a Rust string from a *u8 buffer of the given length - pub unsafe fn from_buf_len(buf: *u8, len: uint) -> String { + pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String { let mut result = String::new(); result.push_bytes(mem::transmute(Slice { data: buf, @@ -671,7 +705,7 @@ pub mod raw { } /// Create a Rust string from a null-terminated C string - pub unsafe fn from_c_str(c_string: *i8) -> String { + pub unsafe fn from_c_str(c_string: *const i8) -> String { let mut buf = String::new(); let mut len = 0; while *c_string.offset(len) != 0 { @@ -803,15 +837,9 @@ pub trait StrAllocating: Str { } /// Converts to a vector of `u16` encoded as UTF-16. + #[deprecated = "use `utf16_units` instead"] fn to_utf16(&self) -> Vec<u16> { - let me = self.as_slice(); - let mut u = Vec::new(); - for ch in me.chars() { - let mut buf = [0u16, ..2]; - let n = ch.encode_utf16(buf /* as mut slice! */); - u.push_all(buf.slice_to(n)); - } - u + self.as_slice().utf16_units().collect::<Vec<u16>>() } /// Given a string, make a new string with repeated copies of it. @@ -1103,7 +1131,7 @@ mod tests { assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)}); assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)}); fn a_million_letter_a() -> String { - let mut i = 0; + let mut i = 0u; let mut rs = String::new(); while i < 100000 { rs.push_str("aaaaaaaaaa"); @@ -1112,7 +1140,7 @@ mod tests { rs } fn half_a_million_letter_a() -> String { - let mut i = 0; + let mut i = 0u; let mut rs = String::new(); while i < 100000 { rs.push_str("aaaaa"); @@ -1220,7 +1248,7 @@ mod tests { assert_eq!("华", data.slice(30, 33)); fn a_million_letter_x() -> String { - let mut i = 0; + let mut i = 0u; let mut rs = String::new(); while i < 100000 { rs.push_str("华华华华华华华华华华"); @@ -1229,7 +1257,7 @@ mod tests { rs } fn half_a_million_letter_x() -> String { - let mut i = 0; + let mut i = 0u; let mut rs = String::new(); while i < 100000 { rs.push_str("华华华华华"); @@ -1541,8 +1569,8 @@ mod tests { let n2: uint = v.len(); assert_eq!(n1, n2); while i < n1 { - let a: u8 = s1.as_slice()[i]; - let b: u8 = s2.as_slice()[i]; + let a: u8 = s1.as_bytes()[i]; + let b: u8 = s2.as_bytes()[i]; debug!("{}", a); debug!("{}", b); assert_eq!(a, b); @@ -1619,14 +1647,17 @@ mod tests { for p in pairs.iter() { let (s, u) = (*p).clone(); + let s_as_utf16 = s.as_slice().utf16_units().collect::<Vec<u16>>(); + let u_as_string = from_utf16(u.as_slice()).unwrap(); + assert!(is_utf16(u.as_slice())); - assert_eq!(s.to_utf16(), u); + assert_eq!(s_as_utf16, u); - assert_eq!(from_utf16(u.as_slice()).unwrap(), s); + assert_eq!(u_as_string, s); assert_eq!(from_utf16_lossy(u.as_slice()), s); - assert_eq!(from_utf16(s.to_utf16().as_slice()).unwrap(), s); - assert_eq!(from_utf16(u.as_slice()).unwrap().to_utf16(), u); + assert_eq!(from_utf16(s_as_utf16.as_slice()).unwrap(), s); + assert_eq!(u_as_string.as_slice().utf16_units().collect::<Vec<u16>>(), u); } } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 6d1fc43a4f1..936e60388a6 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -222,7 +222,7 @@ impl String { return None } - let byte = self.as_slice()[len - 1]; + let byte = self.as_bytes()[len - 1]; self.vec.set_len(len - 1); Some(byte) } diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs index 78770b6db8d..becceffe6d0 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/treemap.rs @@ -56,23 +56,11 @@ impl<K: PartialEq + Ord, V: PartialEq> PartialEq for TreeMap<K, V> { } } -// Lexicographical comparison -fn lt<K: PartialOrd + Ord, V: PartialOrd>(a: &TreeMap<K, V>, - b: &TreeMap<K, V>) -> bool { - // the Zip iterator is as long as the shortest of a and b. - for ((key_a, value_a), (key_b, value_b)) in a.iter().zip(b.iter()) { - if *key_a < *key_b { return true; } - if *key_a > *key_b { return false; } - if *value_a < *value_b { return true; } - if *value_a > *value_b { return false; } - } - - a.len() < b.len() -} - -impl<K: PartialOrd + Ord, V: PartialOrd> PartialOrd for TreeMap<K, V> { +impl<K: Ord, V: PartialOrd> PartialOrd for TreeMap<K, V> { #[inline] - fn lt(&self, other: &TreeMap<K, V>) -> bool { lt(self, other) } + fn partial_cmp(&self, other: &TreeMap<K, V>) -> Option<Ordering> { + iter::order::partial_cmp(self.iter(), other.iter()) + } } impl<K: Ord + Show, V: Show> Show for TreeMap<K, V> { @@ -287,7 +275,7 @@ pub struct Entries<'a, K, V> { // See the comment on MutEntries; this is just to allow // code-sharing (for this immutable-values iterator it *could* very // well be Option<&'a TreeNode<K,V>>). - node: *TreeNode<K, V>, + node: *const TreeNode<K, V>, remaining_min: uint, remaining_max: uint } @@ -468,11 +456,11 @@ define_iterator! { addr_mut = mut } -fn deref<'a, K, V>(node: &'a Option<Box<TreeNode<K, V>>>) -> *TreeNode<K, V> { +fn deref<'a, K, V>(node: &'a Option<Box<TreeNode<K, V>>>) -> *const TreeNode<K, V> { match *node { Some(ref n) => { let n: &TreeNode<K, V> = *n; - n as *TreeNode<K, V> + n as *const TreeNode<K, V> } None => ptr::null() } @@ -568,9 +556,11 @@ impl<T: PartialEq + Ord> PartialEq for TreeSet<T> { fn eq(&self, other: &TreeSet<T>) -> bool { self.map == other.map } } -impl<T: PartialOrd + Ord> PartialOrd for TreeSet<T> { +impl<T: Ord> PartialOrd for TreeSet<T> { #[inline] - fn lt(&self, other: &TreeSet<T>) -> bool { self.map < other.map } + fn partial_cmp(&self, other: &TreeSet<T>) -> Option<Ordering> { + self.map.partial_cmp(&other.map) + } } impl<T: Ord + Show> Show for TreeSet<T> { diff --git a/src/libcollections/trie.rs b/src/libcollections/trie.rs index 350c284e1d3..9b6355e121b 100644 --- a/src/libcollections/trie.rs +++ b/src/libcollections/trie.rs @@ -189,7 +189,9 @@ macro_rules! bound { // We like sharing code so much that even a little unsafe won't // stop us. let this = $this; - let mut node = addr!(& $($mut_)* this.root as * $($mut_)* TrieNode<T>); + let mut node = unsafe { + mem::transmute::<_, uint>(&this.root) as *mut TrieNode<T> + }; let key = $key; @@ -205,7 +207,10 @@ macro_rules! bound { let child_id = chunk(key, it.length); let (slice_idx, ret) = match children[child_id] { Internal(ref $($mut_)* n) => { - node = addr!(& $($mut_)* **n as * $($mut_)* TrieNode<T>); + node = unsafe { + mem::transmute::<_, uint>(&**n) + as *mut TrieNode<T> + }; (child_id + 1, false) } External(stored, _) => { diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 0ee0c5b87ae..2ffc168f82c 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -389,8 +389,8 @@ impl<T: PartialEq> PartialEq for Vec<T> { impl<T: PartialOrd> PartialOrd for Vec<T> { #[inline] - fn lt(&self, other: &Vec<T>) -> bool { - self.as_slice() < other.as_slice() + fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> { + self.as_slice().partial_cmp(&other.as_slice()) } } @@ -615,7 +615,7 @@ impl<T> Vec<T> { } unsafe { - let end = (self.ptr as *T).offset(self.len as int) as *mut T; + let end = (self.ptr as *const T).offset(self.len as int) as *mut T; ptr::write(&mut *end, value); self.len += 1; } @@ -674,7 +674,10 @@ impl<T> Vec<T> { #[inline] pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { - mem::transmute(Slice { data: self.as_mut_ptr() as *T, len: self.len }) + mem::transmute(Slice { + data: self.as_mut_ptr() as *const T, + len: self.len, + }) } } @@ -956,7 +959,8 @@ impl<T> Vec<T> { /// /// # Failure /// - /// Fails if `index` is out of bounds of the vector. + /// Fails if `index` is not between `0` and the vector's length (both + /// bounds inclusive). /// /// # Example /// @@ -964,6 +968,8 @@ impl<T> Vec<T> { /// let mut vec = vec!(1i, 2, 3); /// vec.insert(1, 4); /// assert_eq!(vec, vec!(1, 4, 2, 3)); + /// vec.insert(4, 5); + /// assert_eq!(vec, vec!(1, 4, 2, 3, 5)); /// ``` pub fn insert(&mut self, index: uint, element: T) { let len = self.len(); @@ -1011,7 +1017,7 @@ impl<T> Vec<T> { let ptr = self.as_mut_ptr().offset(index as int); // copy it out, unsafely having a copy of the value on // the stack and in the vector at the same time. - ret = Some(ptr::read(ptr as *T)); + ret = Some(ptr::read(ptr as *const T)); // Shift everything down to fill in that spot. ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1); @@ -1200,15 +1206,15 @@ impl<T> Vec<T> { /// Modifying the vector may cause its buffer to be reallocated, which /// would also make any pointers to it invalid. #[inline] - pub fn as_ptr(&self) -> *T { + pub fn as_ptr(&self) -> *const T { // If we have a 0-sized vector, then the base pointer should not be NULL // because an iterator over the slice will attempt to yield the base // pointer as the first element in the vector, but this will end up // being Some(NULL) which is optimized to None. if mem::size_of::<T>() == 0 { - 1 as *T + 1 as *const T } else { - self.ptr as *T + self.ptr as *const T } } @@ -1542,7 +1548,7 @@ pub mod raw { /// The elements of the buffer are copied into the vector without cloning, /// as if `ptr::read()` were called on them. #[inline] - pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> Vec<T> { + pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> { let mut dst = Vec::with_capacity(elts); dst.set_len(elts); ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts); diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 4a35dde08eb..8021fa50d8f 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -115,179 +115,3 @@ impl<'a> AnyMutRefExt<'a> for &'a mut Any { } } } - -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - use realstd::owned::{Box, AnyOwnExt}; - use realstd::str::Str; - - #[deriving(PartialEq, Show)] - struct Test; - - static TEST: &'static str = "Test"; - - #[test] - fn any_referenced() { - let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any); - - assert!(a.is::<uint>()); - assert!(!b.is::<uint>()); - assert!(!c.is::<uint>()); - - assert!(!a.is::<&'static str>()); - assert!(b.is::<&'static str>()); - assert!(!c.is::<&'static str>()); - - assert!(!a.is::<Test>()); - assert!(!b.is::<Test>()); - assert!(c.is::<Test>()); - } - - #[test] - fn any_owning() { - let (a, b, c) = (box 5u as Box<Any>, box TEST as Box<Any>, box Test as Box<Any>); - - assert!(a.is::<uint>()); - assert!(!b.is::<uint>()); - assert!(!c.is::<uint>()); - - assert!(!a.is::<&'static str>()); - assert!(b.is::<&'static str>()); - assert!(!c.is::<&'static str>()); - - assert!(!a.is::<Test>()); - assert!(!b.is::<Test>()); - assert!(c.is::<Test>()); - } - - #[test] - fn any_as_ref() { - let a = &5u as &Any; - - match a.as_ref::<uint>() { - Some(&5) => {} - x => fail!("Unexpected value {}", x) - } - - match a.as_ref::<Test>() { - None => {} - x => fail!("Unexpected value {}", x) - } - } - - #[test] - fn any_as_mut() { - let mut a = 5u; - let mut b = box 7u; - - let a_r = &mut a as &mut Any; - let tmp: &mut uint = &mut *b; - let b_r = tmp as &mut Any; - - match a_r.as_mut::<uint>() { - Some(x) => { - assert_eq!(*x, 5u); - *x = 612; - } - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::<uint>() { - Some(x) => { - assert_eq!(*x, 7u); - *x = 413; - } - x => fail!("Unexpected value {}", x) - } - - match a_r.as_mut::<Test>() { - None => (), - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::<Test>() { - None => (), - x => fail!("Unexpected value {}", x) - } - - match a_r.as_mut::<uint>() { - Some(&612) => {} - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::<uint>() { - Some(&413) => {} - x => fail!("Unexpected value {}", x) - } - } - - #[test] - fn any_move() { - use realstd::any::Any; - use realstd::result::{Ok, Err}; - let a = box 8u as Box<Any>; - let b = box Test as Box<Any>; - - match a.move::<uint>() { - Ok(a) => { assert!(a == box 8u); } - Err(..) => fail!() - } - match b.move::<Test>() { - Ok(a) => { assert!(a == box Test); } - Err(..) => fail!() - } - - let a = box 8u as Box<Any>; - let b = box Test as Box<Any>; - - assert!(a.move::<Box<Test>>().is_err()); - assert!(b.move::<Box<uint>>().is_err()); - } - - #[test] - fn test_show() { - use realstd::to_str::ToStr; - let a = box 8u as Box<::realstd::any::Any>; - let b = box Test as Box<::realstd::any::Any>; - let a_str = a.to_str(); - let b_str = b.to_str(); - assert_eq!(a_str.as_slice(), "Box<Any>"); - assert_eq!(b_str.as_slice(), "Box<Any>"); - - let a = &8u as &Any; - let b = &Test as &Any; - let s = format!("{}", a); - assert_eq!(s.as_slice(), "&Any"); - let s = format!("{}", b); - assert_eq!(s.as_slice(), "&Any"); - } - - #[test] - fn any_fixed_vec() { - let test = [0u, ..8]; - let test = &test as &Any; - assert!(test.is::<[uint, ..8]>()); - assert!(!test.is::<[uint, ..10]>()); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - - use any::{Any, AnyRefExt}; - use option::Some; - use self::test::Bencher; - - #[bench] - fn bench_as_ref(b: &mut Bencher) { - b.iter(|| { - let mut x = 0i; - let mut y = &mut x as &mut Any; - test::black_box(&mut y); - test::black_box(y.as_ref::<int>() == Some(&0)); - }); - } -} diff --git a/src/libcore/atomics.rs b/src/libcore/atomics.rs index 65ba11f89ad..971799acc78 100644 --- a/src/libcore/atomics.rs +++ b/src/libcore/atomics.rs @@ -94,7 +94,7 @@ impl AtomicBool { /// Load the value #[inline] pub fn load(&self, order: Ordering) -> bool { - unsafe { atomic_load(self.v.get() as *uint, order) > 0 } + unsafe { atomic_load(self.v.get() as *const uint, order) > 0 } } /// Store the value @@ -295,7 +295,7 @@ impl AtomicInt { /// Load the value #[inline] pub fn load(&self, order: Ordering) -> int { - unsafe { atomic_load(self.v.get() as *int, order) } + unsafe { atomic_load(self.v.get() as *const int, order) } } /// Store the value @@ -407,7 +407,7 @@ impl AtomicUint { /// Load the value #[inline] pub fn load(&self, order: Ordering) -> uint { - unsafe { atomic_load(self.v.get() as *uint, order) } + unsafe { atomic_load(self.v.get() as *const uint, order) } } /// Store the value @@ -520,7 +520,7 @@ impl<T> AtomicPtr<T> { #[inline] pub fn load(&self, order: Ordering) -> *mut T { unsafe { - atomic_load(self.p.get() as **mut T, order) as *mut T + atomic_load(self.p.get() as *const *mut T, order) as *mut T } } @@ -560,7 +560,7 @@ unsafe fn atomic_store<T>(dst: *mut T, val: T, order:Ordering) { } #[inline] -unsafe fn atomic_load<T>(dst: *T, order:Ordering) -> T { +unsafe fn atomic_load<T>(dst: *const T, order:Ordering) -> T { match order { Acquire => intrinsics::atomic_load_acq(dst), Relaxed => intrinsics::atomic_load_relaxed(dst), @@ -693,97 +693,3 @@ pub fn fence(order: Ordering) { } } } - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn bool_() { - let a = AtomicBool::new(false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), true); - - a.store(false, SeqCst); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - } - - #[test] - fn bool_and() { - let a = AtomicBool::new(true); - assert_eq!(a.fetch_and(false, SeqCst),true); - assert_eq!(a.load(SeqCst),false); - } - - #[test] - fn uint_and() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); - } - - #[test] - fn uint_or() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); - } - - #[test] - fn uint_xor() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); - } - - #[test] - fn int_and() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); - } - - #[test] - fn int_or() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); - } - - #[test] - fn int_xor() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); - } - - static mut S_BOOL : AtomicBool = INIT_ATOMIC_BOOL; - static mut S_INT : AtomicInt = INIT_ATOMIC_INT; - static mut S_UINT : AtomicUint = INIT_ATOMIC_UINT; - - #[test] - fn static_init() { - unsafe { - assert!(!S_BOOL.load(SeqCst)); - assert!(S_INT.load(SeqCst) == 0); - assert!(S_UINT.load(SeqCst) == 0); - } - } - - #[test] - fn different_sizes() { - unsafe { - let mut slot = 0u16; - assert_eq!(super::atomic_swap(&mut slot, 1, SeqCst), 0); - - let mut slot = 0u8; - assert_eq!(super::atomic_compare_and_swap(&mut slot, 1, 2, SeqCst), 0); - - let slot = 0u32; - assert_eq!(super::atomic_load(&slot, SeqCst), 0); - - let mut slot = 0u64; - super::atomic_store(&mut slot, 2, SeqCst); - } - } -} diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index ab701b76026..355ee7c7a16 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -67,10 +67,10 @@ //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); -//! shared_map.borrow_mut().insert("africa", 92388); -//! shared_map.borrow_mut().insert("kyoto", 11837); -//! shared_map.borrow_mut().insert("piccadilly", 11826); -//! shared_map.borrow_mut().insert("marbles", 38); +//! shared_map.borrow_mut().insert("africa", 92388i); +//! shared_map.borrow_mut().insert("kyoto", 11837i); +//! shared_map.borrow_mut().insert("piccadilly", 11826i); +//! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! @@ -383,132 +383,3 @@ impl<'b, T> DerefMut<T> for RefMut<'b, T> { unsafe { &mut *self._parent.value.get() } } } - -#[cfg(test)] -mod test { - use super::*; - use mem::drop; - - #[test] - fn smoketest_cell() { - let x = Cell::new(10i); - assert!(x == Cell::new(10)); - assert!(x.get() == 10); - x.set(20); - assert!(x == Cell::new(20)); - assert!(x.get() == 20); - - let y = Cell::new((30i, 40i)); - assert!(y == Cell::new((30, 40))); - assert!(y.get() == (30, 40)); - } - - #[test] - fn cell_has_sensible_show() { - use str::StrSlice; - use realstd::str::Str; - - let x = Cell::new("foo bar"); - assert!(format!("{}", x).as_slice().contains(x.get())); - - x.set("baz qux"); - assert!(format!("{}", x).as_slice().contains(x.get())); - } - - #[test] - fn ref_and_refmut_have_sensible_show() { - use str::StrSlice; - use realstd::str::Str; - - let refcell = RefCell::new("foo"); - - let refcell_refmut = refcell.borrow_mut(); - assert!(format!("{}", refcell_refmut).as_slice().contains("foo")); - drop(refcell_refmut); - - let refcell_ref = refcell.borrow(); - assert!(format!("{}", refcell_ref).as_slice().contains("foo")); - drop(refcell_ref); - } - - #[test] - fn double_imm_borrow() { - let x = RefCell::new(0); - let _b1 = x.borrow(); - x.borrow(); - } - - #[test] - fn no_mut_then_imm_borrow() { - let x = RefCell::new(0); - let _b1 = x.borrow_mut(); - assert!(x.try_borrow().is_none()); - } - - #[test] - fn no_imm_then_borrow_mut() { - let x = RefCell::new(0); - let _b1 = x.borrow(); - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - fn no_double_borrow_mut() { - let x = RefCell::new(0); - let _b1 = x.borrow_mut(); - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - fn imm_release_borrow_mut() { - let x = RefCell::new(0); - { - let _b1 = x.borrow(); - } - x.borrow_mut(); - } - - #[test] - fn mut_release_borrow_mut() { - let x = RefCell::new(0); - { - let _b1 = x.borrow_mut(); - } - x.borrow(); - } - - #[test] - fn double_borrow_single_release_no_borrow_mut() { - let x = RefCell::new(0); - let _b1 = x.borrow(); - { - let _b2 = x.borrow(); - } - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - #[should_fail] - fn discard_doesnt_unborrow() { - let x = RefCell::new(0); - let _b = x.borrow(); - let _ = _b; - let _b = x.borrow_mut(); - } - - #[test] - #[allow(experimental)] - fn clone_ref_updates_flag() { - let x = RefCell::new(0); - { - let b1 = x.borrow(); - assert!(x.try_borrow_mut().is_none()); - { - let _b2 = clone_ref(&b1); - assert!(x.try_borrow_mut().is_none()); - } - assert!(x.try_borrow_mut().is_none()); - } - assert!(x.try_borrow_mut().is_some()); - } -} diff --git a/src/libcore/char.rs b/src/libcore/char.rs index c188ec75ddd..da67772d0f1 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -602,205 +602,3 @@ impl Char for char { } -#[cfg(test)] -mod test { - use super::{escape_unicode, escape_default}; - - use char::Char; - use slice::ImmutableVector; - use option::{Some, None}; - use realstd::string::String; - use realstd::str::Str; - - #[test] - fn test_is_lowercase() { - assert!('a'.is_lowercase()); - assert!('ö'.is_lowercase()); - assert!('ß'.is_lowercase()); - assert!(!'Ü'.is_lowercase()); - assert!(!'P'.is_lowercase()); - } - - #[test] - fn test_is_uppercase() { - assert!(!'h'.is_uppercase()); - assert!(!'ä'.is_uppercase()); - assert!(!'ß'.is_uppercase()); - assert!('Ö'.is_uppercase()); - assert!('T'.is_uppercase()); - } - - #[test] - fn test_is_whitespace() { - assert!(' '.is_whitespace()); - assert!('\u2007'.is_whitespace()); - assert!('\t'.is_whitespace()); - assert!('\n'.is_whitespace()); - assert!(!'a'.is_whitespace()); - assert!(!'_'.is_whitespace()); - assert!(!'\u0000'.is_whitespace()); - } - - #[test] - fn test_to_digit() { - assert_eq!('0'.to_digit(10u), Some(0u)); - assert_eq!('1'.to_digit(2u), Some(1u)); - assert_eq!('2'.to_digit(3u), Some(2u)); - assert_eq!('9'.to_digit(10u), Some(9u)); - assert_eq!('a'.to_digit(16u), Some(10u)); - assert_eq!('A'.to_digit(16u), Some(10u)); - assert_eq!('b'.to_digit(16u), Some(11u)); - assert_eq!('B'.to_digit(16u), Some(11u)); - assert_eq!('z'.to_digit(36u), Some(35u)); - assert_eq!('Z'.to_digit(36u), Some(35u)); - assert_eq!(' '.to_digit(10u), None); - assert_eq!('$'.to_digit(36u), None); - } - - #[test] - fn test_to_lowercase() { - assert_eq!('A'.to_lowercase(), 'a'); - assert_eq!('Ö'.to_lowercase(), 'ö'); - assert_eq!('ß'.to_lowercase(), 'ß'); - assert_eq!('Ü'.to_lowercase(), 'ü'); - assert_eq!('💩'.to_lowercase(), '💩'); - assert_eq!('Σ'.to_lowercase(), 'σ'); - assert_eq!('Τ'.to_lowercase(), 'τ'); - assert_eq!('Ι'.to_lowercase(), 'ι'); - assert_eq!('Γ'.to_lowercase(), 'γ'); - assert_eq!('Μ'.to_lowercase(), 'μ'); - assert_eq!('Α'.to_lowercase(), 'α'); - assert_eq!('Σ'.to_lowercase(), 'σ'); - } - - #[test] - fn test_to_uppercase() { - assert_eq!('a'.to_uppercase(), 'A'); - assert_eq!('ö'.to_uppercase(), 'Ö'); - assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s - assert_eq!('ü'.to_uppercase(), 'Ü'); - assert_eq!('💩'.to_uppercase(), '💩'); - - assert_eq!('σ'.to_uppercase(), 'Σ'); - assert_eq!('τ'.to_uppercase(), 'Τ'); - assert_eq!('ι'.to_uppercase(), 'Ι'); - assert_eq!('γ'.to_uppercase(), 'Γ'); - assert_eq!('μ'.to_uppercase(), 'Μ'); - assert_eq!('α'.to_uppercase(), 'Α'); - assert_eq!('ς'.to_uppercase(), 'Σ'); - } - - #[test] - fn test_is_control() { - assert!('\u0000'.is_control()); - assert!('\u0003'.is_control()); - assert!('\u0006'.is_control()); - assert!('\u0009'.is_control()); - assert!('\u007f'.is_control()); - assert!('\u0092'.is_control()); - assert!(!'\u0020'.is_control()); - assert!(!'\u0055'.is_control()); - assert!(!'\u0068'.is_control()); - } - - #[test] - fn test_is_digit() { - assert!('2'.is_digit()); - assert!('7'.is_digit()); - assert!(!'c'.is_digit()); - assert!(!'i'.is_digit()); - assert!(!'z'.is_digit()); - assert!(!'Q'.is_digit()); - } - - #[test] - fn test_escape_default() { - fn string(c: char) -> String { - let mut result = String::new(); - escape_default(c, |c| { result.push_char(c); }); - return result; - } - let s = string('\n'); - assert_eq!(s.as_slice(), "\\n"); - let s = string('\r'); - assert_eq!(s.as_slice(), "\\r"); - let s = string('\''); - assert_eq!(s.as_slice(), "\\'"); - let s = string('"'); - assert_eq!(s.as_slice(), "\\\""); - let s = string(' '); - assert_eq!(s.as_slice(), " "); - let s = string('a'); - assert_eq!(s.as_slice(), "a"); - let s = string('~'); - assert_eq!(s.as_slice(), "~"); - let s = string('\x00'); - assert_eq!(s.as_slice(), "\\x00"); - let s = string('\x1f'); - assert_eq!(s.as_slice(), "\\x1f"); - let s = string('\x7f'); - assert_eq!(s.as_slice(), "\\x7f"); - let s = string('\xff'); - assert_eq!(s.as_slice(), "\\xff"); - let s = string('\u011b'); - assert_eq!(s.as_slice(), "\\u011b"); - let s = string('\U0001d4b6'); - assert_eq!(s.as_slice(), "\\U0001d4b6"); - } - - #[test] - fn test_escape_unicode() { - fn string(c: char) -> String { - let mut result = String::new(); - escape_unicode(c, |c| { result.push_char(c); }); - return result; - } - let s = string('\x00'); - assert_eq!(s.as_slice(), "\\x00"); - let s = string('\n'); - assert_eq!(s.as_slice(), "\\x0a"); - let s = string(' '); - assert_eq!(s.as_slice(), "\\x20"); - let s = string('a'); - assert_eq!(s.as_slice(), "\\x61"); - let s = string('\u011b'); - assert_eq!(s.as_slice(), "\\u011b"); - let s = string('\U0001d4b6'); - assert_eq!(s.as_slice(), "\\U0001d4b6"); - } - - #[test] - fn test_to_str() { - use realstd::to_str::ToStr; - let s = 't'.to_str(); - assert_eq!(s.as_slice(), "t"); - } - - #[test] - fn test_encode_utf8() { - fn check(input: char, expect: &[u8]) { - let mut buf = [0u8, ..4]; - let n = input.encode_utf8(buf /* as mut slice! */); - assert_eq!(buf.slice_to(n), expect); - } - - check('x', [0x78]); - check('\u00e9', [0xc3, 0xa9]); - check('\ua66e', [0xea, 0x99, 0xae]); - check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]); - } - - #[test] - fn test_encode_utf16() { - fn check(input: char, expect: &[u16]) { - let mut buf = [0u16, ..2]; - let n = input.encode_utf16(buf /* as mut slice! */); - assert_eq!(buf.slice_to(n), expect); - } - - check('x', [0x0078]); - check('\u00e9', [0x00e9]); - check('\ua66e', [0xa66e]); - check('\U0001f4a9', [0xd83d, 0xdca9]); - } -} diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 04f01db3147..247f63115a7 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -110,63 +110,3 @@ extern_fn_clone!(A, B, C, D, E, F) extern_fn_clone!(A, B, C, D, E, F, G) extern_fn_clone!(A, B, C, D, E, F, G, H) -#[cfg(test)] -mod test { - use prelude::*; - use realstd::owned::Box; - use realstd::gc::{Gc, GC}; - - fn realclone<T: ::realstd::clone::Clone>(t: &T) -> T { - use realstd::clone::Clone; - t.clone() - } - - fn realclone_from<T: ::realstd::clone::Clone>(t1: &mut T, t2: &T) { - use realstd::clone::Clone; - t1.clone_from(t2) - } - - #[test] - fn test_owned_clone() { - let a = box 5i; - let b: Box<int> = realclone(&a); - assert!(a == b); - } - - #[test] - fn test_managed_clone() { - let a = box(GC) 5i; - let b: Gc<int> = realclone(&a); - assert!(a == b); - } - - #[test] - fn test_borrowed_clone() { - let x = 5i; - let y: &int = &x; - let z: &int = (&y).clone(); - assert_eq!(*z, 5); - } - - #[test] - fn test_clone_from() { - let a = box 5i; - let mut b = box 10i; - realclone_from(&mut b, &a); - assert_eq!(*b, 5); - } - - #[test] - fn test_extern_fn_clone() { - trait Empty {} - impl Empty for int {} - - fn test_fn_a() -> f64 { 1.0 } - fn test_fn_b<T: Empty>(x: T) -> T { x } - fn test_fn_c(_: int, _: f64, _: int, _: int, _: int) {} - - let _ = test_fn_a.clone(); - let _ = test_fn_b::<int>.clone(); - let _ = test_fn_c.clone(); - } -} diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index d7a3edccfd8..8696d385c44 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -37,6 +37,10 @@ //! assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); //! ``` +use option::{Option, Some}; +#[cfg(stage0)] +use option::None; + /// Trait for values that can be compared for equality and inequality. /// /// This trait allows for partial equality, for types that do not have an @@ -86,11 +90,11 @@ pub trait Eq: PartialEq { #[deriving(Clone, PartialEq, Show)] pub enum Ordering { /// An ordering where a compared value is less [than another]. - Less = -1, + Less = -1i, /// An ordering where a compared value is equal [to another]. - Equal = 0, + Equal = 0i, /// An ordering where a compared value is greater [than another]. - Greater = 1 + Greater = 1i, } /// Trait for types that form a [total order]( @@ -127,7 +131,9 @@ impl Ord for Ordering { impl PartialOrd for Ordering { #[inline] - fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) } + fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> { + (*self as int).partial_cmp(&(*other as int)) + } } /// Combine orderings, lexically. @@ -145,7 +151,7 @@ pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering { /// Trait for values that can be compared for a sort-order. /// -/// PartialOrd only requires implementation of the `lt` method, +/// PartialOrd only requires implementation of the `partial_cmp` method, /// with the others generated from default implementations. /// /// However it remains possible to implement the others separately for types @@ -154,20 +160,57 @@ pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering { /// 5.11). #[lang="ord"] pub trait PartialOrd: PartialEq { + /// This method returns an ordering between `self` and `other` values + /// if one exists. + #[cfg(stage0)] + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + match (!self.lt(other), !other.lt(self)) { + (false, false) => None, + (false, true) => Some(Less), + (true, false) => Some(Greater), + (true, true) => Some(Equal), + } + } + + /// This method returns an ordering between `self` and `other` values + /// if one exists. + #[cfg(not(stage0))] + fn partial_cmp(&self, other: &Self) -> Option<Ordering>; + /// This method tests less than (for `self` and `other`) and is used by the `<` operator. - fn lt(&self, other: &Self) -> bool; + fn lt(&self, other: &Self) -> bool { + match self.partial_cmp(other) { + Some(Less) => true, + _ => false, + } + } /// This method tests less than or equal to (`<=`). #[inline] - fn le(&self, other: &Self) -> bool { !other.lt(self) } + fn le(&self, other: &Self) -> bool { + match self.partial_cmp(other) { + Some(Less) | Some(Equal) => true, + _ => false, + } + } /// This method tests greater than (`>`). #[inline] - fn gt(&self, other: &Self) -> bool { other.lt(self) } + fn gt(&self, other: &Self) -> bool { + match self.partial_cmp(other) { + Some(Greater) => true, + _ => false, + } + } /// This method tests greater than or equal to (`>=`). #[inline] - fn ge(&self, other: &Self) -> bool { !self.lt(other) } + fn ge(&self, other: &Self) -> bool { + match self.partial_cmp(other) { + Some(Greater) | Some(Equal) => true, + _ => false, + } + } } /// The equivalence relation. Two values may be equivalent even if they are @@ -192,10 +235,10 @@ pub fn max<T: Ord>(v1: T, v2: T) -> T { } // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types -#[cfg(not(test))] mod impls { use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering, Less, Greater, Equal}; + use option::{Option, Some, None}; macro_rules! eq_impl( ($($t:ty)*) => ($( @@ -229,6 +272,15 @@ mod impls { ($($t:ty)*) => ($( impl PartialOrd for $t { #[inline] + fn partial_cmp(&self, other: &$t) -> Option<Ordering> { + match (self <= other, self >= other) { + (false, false) => None, + (false, true) => Some(Greater), + (true, false) => Some(Less), + (true, true) => Some(Equal), + } + } + #[inline] fn lt(&self, other: &$t) -> bool { (*self) < (*other) } #[inline] fn le(&self, other: &$t) -> bool { (*self) <= (*other) } @@ -242,13 +294,15 @@ mod impls { impl PartialOrd for () { #[inline] - fn lt(&self, _other: &()) -> bool { false } + fn partial_cmp(&self, _: &()) -> Option<Ordering> { + Some(Equal) + } } impl PartialOrd for bool { #[inline] - fn lt(&self, other: &bool) -> bool { - (*self as u8) < (*other as u8) + fn partial_cmp(&self, other: &bool) -> Option<Ordering> { + (*self as u8).partial_cmp(&(*other as u8)) } } @@ -290,6 +344,10 @@ mod impls { } impl<'a, T: PartialOrd> PartialOrd for &'a T { #[inline] + fn partial_cmp(&self, other: &&'a T) -> Option<Ordering> { + (**self).partial_cmp(*other) + } + #[inline] fn lt(&self, other: & &'a T) -> bool { *(*self) < *(*other) } #[inline] fn le(&self, other: & &'a T) -> bool { *(*self) <= *(*other) } @@ -313,6 +371,10 @@ mod impls { } impl<'a, T: PartialOrd> PartialOrd for &'a mut T { #[inline] + fn partial_cmp(&self, other: &&'a mut T) -> Option<Ordering> { + (**self).partial_cmp(*other) + } + #[inline] fn lt(&self, other: &&'a mut T) -> bool { **self < **other } #[inline] fn le(&self, other: &&'a mut T) -> bool { **self <= **other } @@ -327,66 +389,3 @@ mod impls { } impl<'a, T: Eq> Eq for &'a mut T {} } - -#[cfg(test)] -mod test { - use super::lexical_ordering; - - #[test] - fn test_int_totalord() { - assert_eq!(5u.cmp(&10), Less); - assert_eq!(10u.cmp(&5), Greater); - assert_eq!(5u.cmp(&5), Equal); - assert_eq!((-5u).cmp(&12), Less); - assert_eq!(12u.cmp(-5), Greater); - } - - #[test] - fn test_mut_int_totalord() { - assert_eq!((&mut 5u).cmp(&10), Less); - assert_eq!((&mut 10u).cmp(&5), Greater); - assert_eq!((&mut 5u).cmp(&5), Equal); - assert_eq!((&mut -5u).cmp(&12), Less); - assert_eq!((&mut 12u).cmp(-5), Greater); - } - - #[test] - fn test_ordering_order() { - assert!(Less < Equal); - assert_eq!(Greater.cmp(&Less), Greater); - } - - #[test] - fn test_lexical_ordering() { - fn t(o1: Ordering, o2: Ordering, e: Ordering) { - assert_eq!(lexical_ordering(o1, o2), e); - } - - let xs = [Less, Equal, Greater]; - for &o in xs.iter() { - t(Less, o, Less); - t(Equal, o, o); - t(Greater, o, Greater); - } - } - - #[test] - fn test_user_defined_eq() { - // Our type. - struct SketchyNum { - num : int - } - - // Our implementation of `PartialEq` to support `==` and `!=`. - impl PartialEq for SketchyNum { - // Our custom eq allows numbers which are near each other to be equal! :D - fn eq(&self, other: &SketchyNum) -> bool { - (self.num - other.num).abs() < 5 - } - } - - // Now these binary operators will work when applied! - assert!(SketchyNum {num: 37} == SketchyNum {num: 34}); - assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); - } -} diff --git a/src/libcore/failure.rs b/src/libcore/failure.rs index c64bd6201fa..4bc39db8ecf 100644 --- a/src/libcore/failure.rs +++ b/src/libcore/failure.rs @@ -31,11 +31,10 @@ #![allow(dead_code, missing_doc)] use fmt; -#[cfg(not(test))] use intrinsics; +use intrinsics; #[cold] #[inline(never)] // this is the slow path, always #[lang="fail_"] -#[cfg(not(test))] fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! { format_args!(|args| -> () { begin_unwind(args, file, line); @@ -46,7 +45,6 @@ fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! { #[cold] #[lang="fail_bounds_check"] -#[cfg(not(test))] fn fail_bounds_check(file: &'static str, line: uint, index: uint, len: uint) -> ! { format_args!(|args| -> () { diff --git a/src/libcore/finally.rs b/src/libcore/finally.rs index ab151460537..514b3f90df7 100644 --- a/src/libcore/finally.rs +++ b/src/libcore/finally.rs @@ -115,55 +115,3 @@ impl<'a,A> Drop for Finallyalizer<'a,A> { } } -#[cfg(test)] -mod test { - use super::{try_finally, Finally}; - use realstd::task::failing; - - #[test] - fn test_success() { - let mut i = 0i; - try_finally( - &mut i, (), - |i, ()| { - *i = 10; - }, - |i| { - assert!(!failing()); - assert_eq!(*i, 10); - *i = 20; - }); - assert_eq!(i, 20); - } - - #[test] - #[should_fail] - fn test_fail() { - let mut i = 0i; - try_finally( - &mut i, (), - |i, ()| { - *i = 10; - fail!(); - }, - |i| { - assert!(failing()); - assert_eq!(*i, 10); - }) - } - - #[test] - fn test_retval() { - let mut closure: || -> int = || 10; - let i = closure.finally(|| { }); - assert_eq!(i, 10); - } - - #[test] - fn test_compact() { - fn do_some_fallible_work() {} - fn but_always_run_this_function() { } - let mut f = do_some_fallible_work; - f.finally(but_always_run_this_function); - } -} diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index d778f3b47a1..7b84c005db5 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -314,11 +314,11 @@ impl<'a> Formatter<'a> { rt::CountImplied => { None } rt::CountIsParam(i) => { let v = self.args[i].value; - unsafe { Some(*(v as *any::Void as *uint)) } + unsafe { Some(*(v as *const _ as *const uint)) } } rt::CountIsNextParam => { let v = self.curarg.next().unwrap().value; - unsafe { Some(*(v as *any::Void as *uint)) } + unsafe { Some(*(v as *const _ as *const uint)) } } } } @@ -496,31 +496,6 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, } } -#[cfg(test)] -pub fn format(args: &Arguments) -> ::realstd::string::String { - use str; - use realstd::io::MemWriter; - - fn mywrite<T: ::realstd::io::Writer>(t: &mut T, b: &[u8]) { - use realstd::io::Writer; - let _ = t.write(b); - } - - impl FormatWriter for MemWriter { - fn write(&mut self, bytes: &[u8]) -> Result { - mywrite(self, bytes); - Ok(()) - } - } - - let mut i = MemWriter::new(); - let _ = write(&mut i, args); - - let mut result = ::realstd::string::String::new(); - result.push_str(str::from_utf8(i.get_ref()).unwrap()); - result -} - /// When the compiler determines that the type of an argument *must* be a string /// (such as for select), then it invokes this method. #[doc(hidden)] #[inline] @@ -543,6 +518,9 @@ impl<'a, T: Show> Show for &'a T { impl<'a, T: Show> Show for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) } } +impl<'a> Show for &'a Show { + fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) } +} impl Bool for bool { fn fmt(&self, f: &mut Formatter) -> Result { @@ -565,7 +543,7 @@ impl Char for char { } } -impl<T> Pointer for *T { +impl<T> Pointer for *const T { fn fmt(&self, f: &mut Formatter) -> Result { f.flags |= 1 << (rt::FlagAlternate as uint); secret_lower_hex::<uint>(&(*self as uint), f) @@ -573,17 +551,17 @@ impl<T> Pointer for *T { } impl<T> Pointer for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { - secret_pointer::<*T>(&(*self as *T), f) + secret_pointer::<*const T>(&(*self as *const T), f) } } impl<'a, T> Pointer for &'a T { fn fmt(&self, f: &mut Formatter) -> Result { - secret_pointer::<*T>(&(&**self as *T), f) + secret_pointer::<*const T>(&(&**self as *const T), f) } } impl<'a, T> Pointer for &'a mut T { fn fmt(&self, f: &mut Formatter) -> Result { - secret_pointer::<*T>(&(&**self as *T), f) + secret_pointer::<*const T>(&(&**self as *const T), f) } } @@ -669,7 +647,7 @@ delegate!(char to char) delegate!(f32 to float) delegate!(f64 to float) -impl<T> Show for *T { +impl<T> Show for *const T { fn fmt(&self, f: &mut Formatter) -> Result { secret_pointer(self, f) } } impl<T> Show for *mut T { @@ -686,7 +664,7 @@ macro_rules! tuple ( fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "(")); let ($(ref $name,)*) = *self; - let mut n = 0; + let mut n = 0i; $( if n > 0 { try!(write!(f, ", ")); diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 56d0817dd00..d52791f6b0e 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -188,283 +188,3 @@ integer!(i8, u8) integer!(i16, u16) integer!(i32, u32) integer!(i64, u64) - -#[cfg(test)] -mod tests { - use fmt::radix; - use super::{Binary, Octal, Decimal, LowerHex, UpperHex}; - use super::{GenericRadix, Radix}; - use realstd::str::Str; - - #[test] - fn test_radix_base() { - assert_eq!(Binary.base(), 2); - assert_eq!(Octal.base(), 8); - assert_eq!(Decimal.base(), 10); - assert_eq!(LowerHex.base(), 16); - assert_eq!(UpperHex.base(), 16); - assert_eq!(Radix { base: 36 }.base(), 36); - } - - #[test] - fn test_radix_prefix() { - assert_eq!(Binary.prefix(), "0b"); - assert_eq!(Octal.prefix(), "0o"); - assert_eq!(Decimal.prefix(), ""); - assert_eq!(LowerHex.prefix(), "0x"); - assert_eq!(UpperHex.prefix(), "0x"); - assert_eq!(Radix { base: 36 }.prefix(), ""); - } - - #[test] - fn test_radix_digit() { - assert_eq!(Binary.digit(0), '0' as u8); - assert_eq!(Binary.digit(2), '2' as u8); - assert_eq!(Octal.digit(0), '0' as u8); - assert_eq!(Octal.digit(7), '7' as u8); - assert_eq!(Decimal.digit(0), '0' as u8); - assert_eq!(Decimal.digit(9), '9' as u8); - assert_eq!(LowerHex.digit(0), '0' as u8); - assert_eq!(LowerHex.digit(10), 'a' as u8); - assert_eq!(LowerHex.digit(15), 'f' as u8); - assert_eq!(UpperHex.digit(0), '0' as u8); - assert_eq!(UpperHex.digit(10), 'A' as u8); - assert_eq!(UpperHex.digit(15), 'F' as u8); - assert_eq!(Radix { base: 36 }.digit(0), '0' as u8); - assert_eq!(Radix { base: 36 }.digit(15), 'f' as u8); - assert_eq!(Radix { base: 36 }.digit(35), 'z' as u8); - } - - #[test] - #[should_fail] - fn test_hex_radix_digit_overflow() { - let _ = LowerHex.digit(16); - } - - #[test] - fn test_format_int() { - // Formatting integers should select the right implementation based off - // the type of the argument. Also, hex/octal/binary should be defined - // for integers, but they shouldn't emit the negative sign. - assert!(format!("{}", 1i).as_slice() == "1"); - assert!(format!("{}", 1i8).as_slice() == "1"); - assert!(format!("{}", 1i16).as_slice() == "1"); - assert!(format!("{}", 1i32).as_slice() == "1"); - assert!(format!("{}", 1i64).as_slice() == "1"); - assert!(format!("{:d}", -1i).as_slice() == "-1"); - assert!(format!("{:d}", -1i8).as_slice() == "-1"); - assert!(format!("{:d}", -1i16).as_slice() == "-1"); - assert!(format!("{:d}", -1i32).as_slice() == "-1"); - assert!(format!("{:d}", -1i64).as_slice() == "-1"); - assert!(format!("{:t}", 1i).as_slice() == "1"); - assert!(format!("{:t}", 1i8).as_slice() == "1"); - assert!(format!("{:t}", 1i16).as_slice() == "1"); - assert!(format!("{:t}", 1i32).as_slice() == "1"); - assert!(format!("{:t}", 1i64).as_slice() == "1"); - assert!(format!("{:x}", 1i).as_slice() == "1"); - assert!(format!("{:x}", 1i8).as_slice() == "1"); - assert!(format!("{:x}", 1i16).as_slice() == "1"); - assert!(format!("{:x}", 1i32).as_slice() == "1"); - assert!(format!("{:x}", 1i64).as_slice() == "1"); - assert!(format!("{:X}", 1i).as_slice() == "1"); - assert!(format!("{:X}", 1i8).as_slice() == "1"); - assert!(format!("{:X}", 1i16).as_slice() == "1"); - assert!(format!("{:X}", 1i32).as_slice() == "1"); - assert!(format!("{:X}", 1i64).as_slice() == "1"); - assert!(format!("{:o}", 1i).as_slice() == "1"); - assert!(format!("{:o}", 1i8).as_slice() == "1"); - assert!(format!("{:o}", 1i16).as_slice() == "1"); - assert!(format!("{:o}", 1i32).as_slice() == "1"); - assert!(format!("{:o}", 1i64).as_slice() == "1"); - - assert!(format!("{}", 1u).as_slice() == "1"); - assert!(format!("{}", 1u8).as_slice() == "1"); - assert!(format!("{}", 1u16).as_slice() == "1"); - assert!(format!("{}", 1u32).as_slice() == "1"); - assert!(format!("{}", 1u64).as_slice() == "1"); - assert!(format!("{:u}", 1u).as_slice() == "1"); - assert!(format!("{:u}", 1u8).as_slice() == "1"); - assert!(format!("{:u}", 1u16).as_slice() == "1"); - assert!(format!("{:u}", 1u32).as_slice() == "1"); - assert!(format!("{:u}", 1u64).as_slice() == "1"); - assert!(format!("{:t}", 1u).as_slice() == "1"); - assert!(format!("{:t}", 1u8).as_slice() == "1"); - assert!(format!("{:t}", 1u16).as_slice() == "1"); - assert!(format!("{:t}", 1u32).as_slice() == "1"); - assert!(format!("{:t}", 1u64).as_slice() == "1"); - assert!(format!("{:x}", 1u).as_slice() == "1"); - assert!(format!("{:x}", 1u8).as_slice() == "1"); - assert!(format!("{:x}", 1u16).as_slice() == "1"); - assert!(format!("{:x}", 1u32).as_slice() == "1"); - assert!(format!("{:x}", 1u64).as_slice() == "1"); - assert!(format!("{:X}", 1u).as_slice() == "1"); - assert!(format!("{:X}", 1u8).as_slice() == "1"); - assert!(format!("{:X}", 1u16).as_slice() == "1"); - assert!(format!("{:X}", 1u32).as_slice() == "1"); - assert!(format!("{:X}", 1u64).as_slice() == "1"); - assert!(format!("{:o}", 1u).as_slice() == "1"); - assert!(format!("{:o}", 1u8).as_slice() == "1"); - assert!(format!("{:o}", 1u16).as_slice() == "1"); - assert!(format!("{:o}", 1u32).as_slice() == "1"); - assert!(format!("{:o}", 1u64).as_slice() == "1"); - - // Test a larger number - assert!(format!("{:t}", 55i).as_slice() == "110111"); - assert!(format!("{:o}", 55i).as_slice() == "67"); - assert!(format!("{:d}", 55i).as_slice() == "55"); - assert!(format!("{:x}", 55i).as_slice() == "37"); - assert!(format!("{:X}", 55i).as_slice() == "37"); - } - - #[test] - fn test_format_int_zero() { - assert!(format!("{}", 0i).as_slice() == "0"); - assert!(format!("{:d}", 0i).as_slice() == "0"); - assert!(format!("{:t}", 0i).as_slice() == "0"); - assert!(format!("{:o}", 0i).as_slice() == "0"); - assert!(format!("{:x}", 0i).as_slice() == "0"); - assert!(format!("{:X}", 0i).as_slice() == "0"); - - assert!(format!("{}", 0u).as_slice() == "0"); - assert!(format!("{:u}", 0u).as_slice() == "0"); - assert!(format!("{:t}", 0u).as_slice() == "0"); - assert!(format!("{:o}", 0u).as_slice() == "0"); - assert!(format!("{:x}", 0u).as_slice() == "0"); - assert!(format!("{:X}", 0u).as_slice() == "0"); - } - - #[test] - fn test_format_int_flags() { - assert!(format!("{:3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>+3d}", 1i).as_slice() == " +1"); - assert!(format!("{:<3d}", 1i).as_slice() == "1 "); - assert!(format!("{:#d}", 1i).as_slice() == "1"); - assert!(format!("{:#x}", 10i).as_slice() == "0xa"); - assert!(format!("{:#X}", 10i).as_slice() == "0xA"); - assert!(format!("{:#5x}", 10i).as_slice() == " 0xa"); - assert!(format!("{:#o}", 10i).as_slice() == "0o12"); - assert!(format!("{:08x}", 10i).as_slice() == "0000000a"); - assert!(format!("{:8x}", 10i).as_slice() == " a"); - assert!(format!("{:<8x}", 10i).as_slice() == "a "); - assert!(format!("{:>8x}", 10i).as_slice() == " a"); - assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a"); - assert!(format!("{:08d}", -10i).as_slice() == "-0000010"); - assert!(format!("{:x}", -1u8).as_slice() == "ff"); - assert!(format!("{:X}", -1u8).as_slice() == "FF"); - assert!(format!("{:t}", -1u8).as_slice() == "11111111"); - assert!(format!("{:o}", -1u8).as_slice() == "377"); - assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); - assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); - assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); - assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); - } - - #[test] - fn test_format_int_sign_padding() { - assert!(format!("{:+5d}", 1i).as_slice() == " +1"); - assert!(format!("{:+5d}", -1i).as_slice() == " -1"); - assert!(format!("{:05d}", 1i).as_slice() == "00001"); - assert!(format!("{:05d}", -1i).as_slice() == "-0001"); - assert!(format!("{:+05d}", 1i).as_slice() == "+0001"); - assert!(format!("{:+05d}", -1i).as_slice() == "-0001"); - } - - #[test] - fn test_format_int_twos_complement() { - use {i8, i16, i32, i64}; - assert!(format!("{}", i8::MIN).as_slice() == "-128"); - assert!(format!("{}", i16::MIN).as_slice() == "-32768"); - assert!(format!("{}", i32::MIN).as_slice() == "-2147483648"); - assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808"); - } - - #[test] - fn test_format_radix() { - assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011"); - assert!(format!("{}", radix(55i, 36)).as_slice() == "1j"); - } - - #[test] - #[should_fail] - fn test_radix_base_too_large() { - let _ = radix(55, 37); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - - mod uint { - use super::test::Bencher; - use fmt::radix; - use realstd::rand::{weak_rng, Rng}; - - #[bench] - fn format_bin(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::<uint>()); }) - } - - #[bench] - fn format_oct(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:o}", rng.gen::<uint>()); }) - } - - #[bench] - fn format_dec(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:u}", rng.gen::<uint>()); }) - } - - #[bench] - fn format_hex(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:x}", rng.gen::<uint>()); }) - } - - #[bench] - fn format_base_36(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{}", radix(rng.gen::<uint>(), 36)); }) - } - } - - mod int { - use super::test::Bencher; - use fmt::radix; - use realstd::rand::{weak_rng, Rng}; - - #[bench] - fn format_bin(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::<int>()); }) - } - - #[bench] - fn format_oct(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:o}", rng.gen::<int>()); }) - } - - #[bench] - fn format_dec(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:d}", rng.gen::<int>()); }) - } - - #[bench] - fn format_hex(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:x}", rng.gen::<int>()); }) - } - - #[bench] - fn format_base_36(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{}", radix(rng.gen::<int>(), 36)); }) - } - } -} diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 6519d3b749d..161dd7cef7e 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -44,14 +44,9 @@ A quick refresher on memory ordering: #![experimental] #![allow(missing_doc)] -// This is needed to prevent duplicate lang item definitions. -#[cfg(test)] -pub use realcore::intrinsics::{TyDesc, Opaque, TyVisitor, TypeId}; - -pub type GlueFn = extern "Rust" fn(*i8); +pub type GlueFn = extern "Rust" fn(*const i8); #[lang="ty_desc"] -#[cfg(not(test))] pub struct TyDesc { // sizeof(T) pub size: uint, @@ -70,13 +65,11 @@ pub struct TyDesc { } #[lang="opaque"] -#[cfg(not(test))] pub enum Opaque { } pub type Disr = u64; #[lang="ty_visitor"] -#[cfg(not(test))] pub trait TyVisitor { fn visit_bot(&mut self) -> bool; fn visit_nil(&mut self) -> bool; @@ -102,55 +95,58 @@ pub trait TyVisitor { fn visit_estr_slice(&mut self) -> bool; fn visit_estr_fixed(&mut self, n: uint, sz: uint, align: uint) -> bool; - fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool; - fn visit_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool; - fn visit_ptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool; - fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool; + fn visit_box(&mut self, mtbl: uint, inner: *const TyDesc) -> bool; + fn visit_uniq(&mut self, mtbl: uint, inner: *const TyDesc) -> bool; + fn visit_ptr(&mut self, mtbl: uint, inner: *const TyDesc) -> bool; + fn visit_rptr(&mut self, mtbl: uint, inner: *const TyDesc) -> bool; - fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool; + fn visit_evec_slice(&mut self, mtbl: uint, inner: *const TyDesc) -> bool; fn visit_evec_fixed(&mut self, n: uint, sz: uint, align: uint, - mtbl: uint, inner: *TyDesc) -> bool; + mtbl: uint, inner: *const TyDesc) -> bool; fn visit_enter_rec(&mut self, n_fields: uint, sz: uint, align: uint) -> bool; fn visit_rec_field(&mut self, i: uint, name: &str, - mtbl: uint, inner: *TyDesc) -> bool; + mtbl: uint, inner: *const TyDesc) -> bool; fn visit_leave_rec(&mut self, n_fields: uint, sz: uint, align: uint) -> bool; fn visit_enter_class(&mut self, name: &str, named_fields: bool, n_fields: uint, sz: uint, align: uint) -> bool; fn visit_class_field(&mut self, i: uint, name: &str, named: bool, - mtbl: uint, inner: *TyDesc) -> bool; + mtbl: uint, inner: *const TyDesc) -> bool; fn visit_leave_class(&mut self, name: &str, named_fields: bool, n_fields: uint, sz: uint, align: uint) -> bool; fn visit_enter_tup(&mut self, n_fields: uint, sz: uint, align: uint) -> bool; - fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool; + fn visit_tup_field(&mut self, i: uint, inner: *const TyDesc) -> bool; fn visit_leave_tup(&mut self, n_fields: uint, sz: uint, align: uint) -> bool; fn visit_enter_enum(&mut self, n_variants: uint, - get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, sz: uint, align: uint) -> bool; fn visit_enter_enum_variant(&mut self, variant: uint, disr_val: Disr, n_fields: uint, name: &str) -> bool; - fn visit_enum_variant_field(&mut self, i: uint, offset: uint, inner: *TyDesc) -> bool; + fn visit_enum_variant_field(&mut self, i: uint, offset: uint, + inner: *const TyDesc) -> bool; fn visit_leave_enum_variant(&mut self, variant: uint, disr_val: Disr, n_fields: uint, name: &str) -> bool; fn visit_leave_enum(&mut self, n_variants: uint, - get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, sz: uint, align: uint) -> bool; fn visit_enter_fn(&mut self, purity: uint, proto: uint, n_inputs: uint, retstyle: uint) -> bool; - fn visit_fn_input(&mut self, i: uint, mode: uint, inner: *TyDesc) -> bool; - fn visit_fn_output(&mut self, retstyle: uint, variadic: bool, inner: *TyDesc) -> bool; + fn visit_fn_input(&mut self, i: uint, mode: uint, + inner: *const TyDesc) -> bool; + fn visit_fn_output(&mut self, retstyle: uint, variadic: bool, + inner: *const TyDesc) -> bool; fn visit_leave_fn(&mut self, purity: uint, proto: uint, n_inputs: uint, retstyle: uint) -> bool; @@ -170,9 +166,9 @@ extern "rust-intrinsic" { pub fn atomic_cxchg_acqrel<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_relaxed<T>(dst: *mut T, old: T, src: T) -> T; - pub fn atomic_load<T>(src: *T) -> T; - pub fn atomic_load_acq<T>(src: *T) -> T; - pub fn atomic_load_relaxed<T>(src: *T) -> T; + pub fn atomic_load<T>(src: *const T) -> T; + pub fn atomic_load_acq<T>(src: *const T) -> T; + pub fn atomic_load_relaxed<T>(src: *const T) -> T; pub fn atomic_store<T>(dst: *mut T, val: T); pub fn atomic_store_rel<T>(dst: *mut T, val: T); @@ -276,7 +272,7 @@ extern "rust-intrinsic" { pub fn pref_align_of<T>() -> uint; /// Get a static pointer to a type descriptor. - pub fn get_tydesc<T>() -> *TyDesc; + pub fn get_tydesc<T>() -> *const TyDesc; /// Gets an identifier which is globally unique to the specified type. This /// function will return the same value for a type regardless of whichever @@ -320,7 +316,7 @@ extern "rust-intrinsic" { /// Returns `true` if a type is managed (will be allocated on the local heap) pub fn owns_managed<T>() -> bool; - pub fn visit_tydesc(td: *TyDesc, tv: &mut TyVisitor); + pub fn visit_tydesc(td: *const TyDesc, tv: &mut TyVisitor); /// Calculates the offset from a pointer. The offset *must* be in-bounds of /// the object, or one-byte-past-the-end. An arithmetic overflow is also @@ -328,17 +324,17 @@ extern "rust-intrinsic" { /// /// This is implemented as an intrinsic to avoid converting to and from an /// integer, since the conversion would throw away aliasing information. - pub fn offset<T>(dst: *T, offset: int) -> *T; + pub fn offset<T>(dst: *const T, offset: int) -> *const T; /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` - pub fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *T, count: uint); + pub fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: uint); /// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` - pub fn copy_memory<T>(dst: *mut T, src: *T, count: uint); + pub fn copy_memory<T>(dst: *mut T, src: *const T, count: uint); /// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a /// size of `count` * `size_of::<T>()` and an alignment of @@ -350,13 +346,14 @@ extern "rust-intrinsic" { /// `min_align_of::<T>()` /// /// The volatile parameter parameter is set to `true`, so it will not be optimized out. - pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *T, count: uint); + pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, + count: uint); /// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` /// /// The volatile parameter parameter is set to `true`, so it will not be optimized out. - pub fn volatile_copy_memory<T>(dst: *mut T, src: *T, count: uint); + pub fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: uint); /// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a /// size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()`. @@ -365,7 +362,7 @@ extern "rust-intrinsic" { pub fn volatile_set_memory<T>(dst: *mut T, val: u8, count: uint); /// Perform a volatile load from the `src` pointer. - pub fn volatile_load<T>(src: *T) -> T; + pub fn volatile_load<T>(src: *const T) -> T; /// Perform a volatile store to the `dst` pointer. pub fn volatile_store<T>(dst: *mut T, val: T); @@ -560,12 +557,10 @@ extern "rust-intrinsic" { #[lang="type_id"] // This needs to be kept in lockstep with the code in trans/intrinsic.rs and // middle/lang_items.rs #[deriving(PartialEq, Eq, Show)] -#[cfg(not(test))] pub struct TypeId { t: u64, } -#[cfg(not(test))] impl TypeId { /// Returns the `TypeId` of the type this generic function has been instantiated with pub fn of<T: 'static>() -> TypeId { diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 3f4d3020815..5895d871dbe 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -135,7 +135,8 @@ pub trait Iterator<A> { /// let a = [0i]; /// let b = [1i]; /// let mut it = a.iter().zip(b.iter()); - /// assert_eq!(it.next().unwrap(), (&0, &1)); + /// let (x0, x1) = (0i, 1i); + /// assert_eq!(it.next().unwrap(), (&x0, &x1)); /// assert!(it.next().is_none()); /// ``` #[inline] @@ -202,8 +203,9 @@ pub trait Iterator<A> { /// ```rust /// let a = [100i, 200]; /// let mut it = a.iter().enumerate(); - /// assert_eq!(it.next().unwrap(), (0, &100)); - /// assert_eq!(it.next().unwrap(), (1, &200)); + /// let (x100, x200) = (100i, 200i); + /// assert_eq!(it.next().unwrap(), (0, &x100)); + /// assert_eq!(it.next().unwrap(), (1, &x200)); /// assert!(it.next().is_none()); /// ``` #[inline] @@ -220,11 +222,11 @@ pub trait Iterator<A> { /// ```rust /// let xs = [100i, 200, 300]; /// let mut it = xs.iter().map(|x| *x).peekable(); - /// assert_eq!(it.peek().unwrap(), &100); + /// assert_eq!(*it.peek().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 200); - /// assert_eq!(it.peek().unwrap(), &300); - /// assert_eq!(it.peek().unwrap(), &300); + /// assert_eq!(*it.peek().unwrap(), 300); + /// assert_eq!(*it.peek().unwrap(), 300); /// assert_eq!(it.next().unwrap(), 300); /// assert!(it.peek().is_none()); /// assert!(it.next().is_none()); @@ -2181,7 +2183,7 @@ impl<A: Clone> RandomAccessIterator<A> for Repeat<A> { pub mod order { use cmp; use cmp::{Eq, Ord, PartialOrd, PartialEq}; - use option::{Some, None}; + use option::{Option, Some, None}; use super::Iterator; /// Compare `a` and `b` for equality using `Eq` @@ -2210,6 +2212,22 @@ pub mod order { } } + /// Order `a` and `b` lexicographically using `PartialOrd` + pub fn partial_cmp<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) + -> Option<cmp::Ordering> { + loop { + match (a.next(), b.next()) { + (None, None) => return Some(cmp::Equal), + (None, _ ) => return Some(cmp::Less), + (_ , None) => return Some(cmp::Greater), + (Some(x), Some(y)) => match x.partial_cmp(&y) { + Some(cmp::Equal) => (), + non_eq => return non_eq, + }, + } + } + } + /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`) pub fn eq<A: PartialEq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool { loop { @@ -2279,868 +2297,5 @@ pub mod order { } } } - - #[test] - fn test_lt() { - use slice::ImmutableVector; - - let empty: [int, ..0] = []; - let xs = [1i,2,3]; - let ys = [1i,2,0]; - - assert!(!lt(xs.iter(), ys.iter())); - assert!(!le(xs.iter(), ys.iter())); - assert!( gt(xs.iter(), ys.iter())); - assert!( ge(xs.iter(), ys.iter())); - - assert!( lt(ys.iter(), xs.iter())); - assert!( le(ys.iter(), xs.iter())); - assert!(!gt(ys.iter(), xs.iter())); - assert!(!ge(ys.iter(), xs.iter())); - - assert!( lt(empty.iter(), xs.iter())); - assert!( le(empty.iter(), xs.iter())); - assert!(!gt(empty.iter(), xs.iter())); - assert!(!ge(empty.iter(), xs.iter())); - - // Sequence with NaN - let u = [1.0f64, 2.0]; - let v = [0.0f64/0.0, 3.0]; - - assert!(!lt(u.iter(), v.iter())); - assert!(!le(u.iter(), v.iter())); - assert!(!gt(u.iter(), v.iter())); - assert!(!ge(u.iter(), v.iter())); - - let a = [0.0f64/0.0]; - let b = [1.0f64]; - let c = [2.0f64]; - - assert!(lt(a.iter(), b.iter()) == (a[0] < b[0])); - assert!(le(a.iter(), b.iter()) == (a[0] <= b[0])); - assert!(gt(a.iter(), b.iter()) == (a[0] > b[0])); - assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0])); - - assert!(lt(c.iter(), b.iter()) == (c[0] < b[0])); - assert!(le(c.iter(), b.iter()) == (c[0] <= b[0])); - assert!(gt(c.iter(), b.iter()) == (c[0] > b[0])); - assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0])); - } - - #[test] - fn test_multi_iter() { - use slice::ImmutableVector; - use iter::DoubleEndedIterator; - let xs = [1i,2,3,4]; - let ys = [4i,3,2,1]; - assert!(eq(xs.iter(), ys.iter().rev())); - assert!(lt(xs.iter(), xs.iter().skip(2))); - } } -#[cfg(test)] -mod tests { - use prelude::*; - use iter::*; - use num; - use realstd::vec::Vec; - use realstd::slice::Vector; - use realstd::gc::GC; - - use cmp; - use realstd::owned::Box; - use uint; - - impl<T> FromIterator<T> for Vec<T> { - fn from_iter<I: Iterator<T>>(mut iterator: I) -> Vec<T> { - let mut v = Vec::new(); - for e in iterator { - v.push(e); - } - return v; - } - } - - impl<'a, T> Iterator<&'a T> for ::realcore::slice::Items<'a, T> { - fn next(&mut self) -> Option<&'a T> { - use RealSome = realcore::option::Some; - use RealNone = realcore::option::None; - fn mynext<T, I: ::realcore::iter::Iterator<T>>(i: &mut I) - -> ::realcore::option::Option<T> - { - use realcore::iter::Iterator; - i.next() - } - match mynext(self) { - RealSome(t) => Some(t), - RealNone => None, - } - } - } - - #[test] - fn test_counter_from_iter() { - let it = count(0i, 5).take(10); - let xs: Vec<int> = FromIterator::from_iter(it); - assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]); - } - - #[test] - fn test_iterator_chain() { - let xs = [0u, 1, 2, 3, 4, 5]; - let ys = [30u, 40, 50, 60]; - let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60]; - let mut it = xs.iter().chain(ys.iter()); - let mut i = 0; - for &x in it { - assert_eq!(x, expected[i]); - i += 1; - } - assert_eq!(i, expected.len()); - - let ys = count(30u, 10).take(4); - let mut it = xs.iter().map(|&x| x).chain(ys); - let mut i = 0; - for x in it { - assert_eq!(x, expected[i]); - i += 1; - } - assert_eq!(i, expected.len()); - } - - #[test] - fn test_filter_map() { - let mut it = count(0u, 1u).take(10) - .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None }); - assert!(it.collect::<Vec<uint>>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]); - } - - #[test] - fn test_iterator_enumerate() { - let xs = [0u, 1, 2, 3, 4, 5]; - let mut it = xs.iter().enumerate(); - for (i, &x) in it { - assert_eq!(i, x); - } - } - - #[test] - fn test_iterator_peekable() { - let xs = vec![0u, 1, 2, 3, 4, 5]; - let mut it = xs.iter().map(|&x|x).peekable(); - assert_eq!(it.peek().unwrap(), &0); - assert_eq!(it.next().unwrap(), 0); - assert_eq!(it.next().unwrap(), 1); - assert_eq!(it.next().unwrap(), 2); - assert_eq!(it.peek().unwrap(), &3); - assert_eq!(it.peek().unwrap(), &3); - assert_eq!(it.next().unwrap(), 3); - assert_eq!(it.next().unwrap(), 4); - assert_eq!(it.peek().unwrap(), &5); - assert_eq!(it.next().unwrap(), 5); - assert!(it.peek().is_none()); - assert!(it.next().is_none()); - } - - #[test] - fn test_iterator_take_while() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [0u, 1, 2, 3, 5, 13]; - let mut it = xs.iter().take_while(|&x| *x < 15u); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_skip_while() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [15, 16, 17, 19]; - let mut it = xs.iter().skip_while(|&x| *x < 15u); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_skip() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30]; - let ys = [13, 15, 16, 17, 19, 20, 30]; - let mut it = xs.iter().skip(5); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_take() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [0u, 1, 2, 3, 5]; - let mut it = xs.iter().take(5); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_scan() { - // test the type inference - fn add(old: &mut int, new: &uint) -> Option<f64> { - *old += *new as int; - Some(*old as f64) - } - let xs = [0u, 1, 2, 3, 4]; - let ys = [0f64, 1.0, 3.0, 6.0, 10.0]; - - let mut it = xs.iter().scan(0, add); - let mut i = 0; - for x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_flat_map() { - let xs = [0u, 3, 6]; - let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8]; - let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3)); - let mut i = 0; - for x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_inspect() { - let xs = [1u, 2, 3, 4]; - let mut n = 0; - - let ys = xs.iter() - .map(|&x| x) - .inspect(|_| n += 1) - .collect::<Vec<uint>>(); - - assert_eq!(n, xs.len()); - assert_eq!(xs.as_slice(), ys.as_slice()); - } - - #[test] - fn test_unfoldr() { - fn count(st: &mut uint) -> Option<uint> { - if *st < 10 { - let ret = Some(*st); - *st += 1; - ret - } else { - None - } - } - - let mut it = Unfold::new(0, count); - let mut i = 0; - for counted in it { - assert_eq!(counted, i); - i += 1; - } - assert_eq!(i, 10); - } - - #[test] - fn test_cycle() { - let cycle_len = 3; - let it = count(0u, 1).take(cycle_len).cycle(); - assert_eq!(it.size_hint(), (uint::MAX, None)); - for (i, x) in it.take(100).enumerate() { - assert_eq!(i % cycle_len, x); - } - - let mut it = count(0u, 1).take(0).cycle(); - assert_eq!(it.size_hint(), (0, Some(0))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_iterator_nth() { - let v = &[0i, 1, 2, 3, 4]; - for i in range(0u, v.len()) { - assert_eq!(v.iter().nth(i).unwrap(), &v[i]); - } - } - - #[test] - fn test_iterator_last() { - let v = &[0i, 1, 2, 3, 4]; - assert_eq!(v.iter().last().unwrap(), &4); - assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); - } - - #[test] - fn test_iterator_len() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().count(), 4); - assert_eq!(v.slice(0, 10).iter().count(), 10); - assert_eq!(v.slice(0, 0).iter().count(), 0); - } - - #[test] - fn test_iterator_sum() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6); - assert_eq!(v.iter().map(|&x| x).sum(), 55); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0); - } - - #[test] - fn test_iterator_product() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0); - assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1); - } - - #[test] - fn test_iterator_max() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3)); - assert_eq!(v.iter().map(|&x| x).max(), Some(10)); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None); - } - - #[test] - fn test_iterator_min() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None); - } - - #[test] - fn test_iterator_size_hint() { - let c = count(0i, 1); - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let v2 = &[10i, 11, 12]; - let vi = v.iter(); - - assert_eq!(c.size_hint(), (uint::MAX, None)); - assert_eq!(vi.size_hint(), (10, Some(10))); - - assert_eq!(c.take(5).size_hint(), (5, Some(5))); - assert_eq!(c.skip(5).size_hint().val1(), None); - assert_eq!(c.take_while(|_| false).size_hint(), (0, None)); - assert_eq!(c.skip_while(|_| false).size_hint(), (0, None)); - assert_eq!(c.enumerate().size_hint(), (uint::MAX, None)); - assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None)); - assert_eq!(c.zip(vi).size_hint(), (10, Some(10))); - assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None)); - assert_eq!(c.filter(|_| false).size_hint(), (0, None)); - assert_eq!(c.map(|_| 0).size_hint(), (uint::MAX, None)); - assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None)); - - assert_eq!(vi.take(5).size_hint(), (5, Some(5))); - assert_eq!(vi.take(12).size_hint(), (10, Some(10))); - assert_eq!(vi.skip(3).size_hint(), (7, Some(7))); - assert_eq!(vi.skip(12).size_hint(), (0, Some(0))); - assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.enumerate().size_hint(), (10, Some(10))); - assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13))); - assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3))); - assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10))); - assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10))); - assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10))); - } - - #[test] - fn test_collect() { - let a = vec![1i, 2, 3, 4, 5]; - let b: Vec<int> = a.iter().map(|&x| x).collect(); - assert!(a == b); - } - - #[test] - fn test_all() { - let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; - assert!(v.iter().all(|&x| x < 10)); - assert!(!v.iter().all(|&x| x % 2 == 0)); - assert!(!v.iter().all(|&x| x > 100)); - assert!(v.slice(0, 0).iter().all(|_| fail!())); - } - - #[test] - fn test_any() { - let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; - assert!(v.iter().any(|&x| x < 10)); - assert!(v.iter().any(|&x| x % 2 == 0)); - assert!(!v.iter().any(|&x| x > 100)); - assert!(!v.slice(0, 0).iter().any(|_| fail!())); - } - - #[test] - fn test_find() { - let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11]; - assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14); - assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3); - assert!(v.iter().find(|x| *x % 12 == 0).is_none()); - } - - #[test] - fn test_position() { - let v = &[1i, 3, 9, 27, 103, 14, 11]; - assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5); - assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1); - assert!(v.iter().position(|x| *x % 12 == 0).is_none()); - } - - #[test] - fn test_count() { - let xs = &[1i, 2, 2, 1, 5, 9, 0, 2]; - assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3); - assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1); - assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0); - } - - #[test] - fn test_max_by() { - let xs: &[int] = &[-3i, 0, 1, 5, -10]; - assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); - } - - #[test] - fn test_min_by() { - let xs: &[int] = &[-3i, 0, 1, 5, -10]; - assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); - } - - #[test] - fn test_by_ref() { - let mut xs = range(0i, 10); - // sum the first five values - let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); - assert_eq!(partial_sum, 10); - assert_eq!(xs.next(), Some(5)); - } - - #[test] - fn test_rev() { - let xs = [2i, 4, 6, 8, 10, 12, 14, 16]; - let mut it = xs.iter(); - it.next(); - it.next(); - assert!(it.rev().map(|&x| x).collect::<Vec<int>>() == - vec![16, 14, 12, 10, 8, 6]); - } - - #[test] - fn test_double_ended_map() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().map(|&x| x * -1); - assert_eq!(it.next(), Some(-1)); - assert_eq!(it.next(), Some(-2)); - assert_eq!(it.next_back(), Some(-6)); - assert_eq!(it.next_back(), Some(-5)); - assert_eq!(it.next(), Some(-3)); - assert_eq!(it.next_back(), Some(-4)); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_enumerate() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().map(|&x| x).enumerate(); - assert_eq!(it.next(), Some((0, 1))); - assert_eq!(it.next(), Some((1, 2))); - assert_eq!(it.next_back(), Some((5, 6))); - assert_eq!(it.next_back(), Some((4, 5))); - assert_eq!(it.next_back(), Some((3, 4))); - assert_eq!(it.next_back(), Some((2, 3))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_zip() { - let xs = [1i, 2, 3, 4, 5, 6]; - let ys = [1i, 2, 3, 7]; - let a = xs.iter().map(|&x| x); - let b = ys.iter().map(|&x| x); - let mut it = a.zip(b); - assert_eq!(it.next(), Some((1, 1))); - assert_eq!(it.next(), Some((2, 2))); - assert_eq!(it.next_back(), Some((4, 7))); - assert_eq!(it.next_back(), Some((3, 3))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_filter() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().filter(|&x| *x & 1 == 0); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &4); - assert_eq!(it.next().unwrap(), &2); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_double_ended_filter_map() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None }); - assert_eq!(it.next_back().unwrap(), 12); - assert_eq!(it.next_back().unwrap(), 8); - assert_eq!(it.next().unwrap(), 4); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_double_ended_chain() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - let mut it = xs.iter().chain(ys.iter()).rev(); - assert_eq!(it.next().unwrap(), &11) - assert_eq!(it.next().unwrap(), &9) - assert_eq!(it.next_back().unwrap(), &1) - assert_eq!(it.next_back().unwrap(), &2) - assert_eq!(it.next_back().unwrap(), &3) - assert_eq!(it.next_back().unwrap(), &4) - assert_eq!(it.next_back().unwrap(), &5) - assert_eq!(it.next_back().unwrap(), &7) - assert_eq!(it.next_back(), None) - } - - #[test] - fn test_rposition() { - fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } - fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } - let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; - - assert_eq!(v.iter().rposition(f), Some(3u)); - assert!(v.iter().rposition(g).is_none()); - } - - #[test] - #[should_fail] - fn test_rposition_fail() { - let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i), - (box 0i, box(GC) 0i), (box 0i, box(GC) 0i)]; - let mut i = 0i; - v.iter().rposition(|_elt| { - if i == 2 { - fail!() - } - i += 1; - false - }); - } - - - #[cfg(test)] - fn check_randacc_iter<A: PartialEq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint) - { - let mut b = a.clone(); - assert_eq!(len, b.indexable()); - let mut n = 0u; - for (i, elt) in a.enumerate() { - assert!(Some(elt) == b.idx(i)); - n += 1; - } - assert_eq!(n, len); - assert!(None == b.idx(n)); - // call recursively to check after picking off an element - if len > 0 { - b.next(); - check_randacc_iter(b, len-1); - } - } - - - #[test] - fn test_double_ended_flat_map() { - let u = [0u,1]; - let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter()); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &5); - assert_eq!(it.next_back().unwrap(), &7); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &7); - assert_eq!(it.next_back(), None); - assert_eq!(it.next(), None); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_random_access_chain() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - let mut it = xs.iter().chain(ys.iter()); - assert_eq!(it.idx(0).unwrap(), &1); - assert_eq!(it.idx(5).unwrap(), &7); - assert_eq!(it.idx(7).unwrap(), &11); - assert!(it.idx(8).is_none()); - - it.next(); - it.next(); - it.next_back(); - - assert_eq!(it.idx(0).unwrap(), &3); - assert_eq!(it.idx(4).unwrap(), &9); - assert!(it.idx(6).is_none()); - - check_randacc_iter(it, xs.len() + ys.len() - 3); - } - - #[test] - fn test_random_access_enumerate() { - let xs = [1i, 2, 3, 4, 5]; - check_randacc_iter(xs.iter().enumerate(), xs.len()); - } - - #[test] - fn test_random_access_rev() { - let xs = [1i, 2, 3, 4, 5]; - check_randacc_iter(xs.iter().rev(), xs.len()); - let mut it = xs.iter().rev(); - it.next(); - it.next_back(); - it.next(); - check_randacc_iter(it, xs.len() - 3); - } - - #[test] - fn test_random_access_zip() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len())); - } - - #[test] - fn test_random_access_take() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().take(3), 3); - check_randacc_iter(xs.iter().take(20), xs.len()); - check_randacc_iter(xs.iter().take(0), 0); - check_randacc_iter(empty.iter().take(2), 0); - } - - #[test] - fn test_random_access_skip() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().skip(2), xs.len() - 2); - check_randacc_iter(empty.iter().skip(2), 0); - } - - #[test] - fn test_random_access_inspect() { - let xs = [1i, 2, 3, 4, 5]; - - // test .map and .inspect that don't implement Clone - let mut it = xs.iter().inspect(|_| {}); - assert_eq!(xs.len(), it.indexable()); - for (i, elt) in xs.iter().enumerate() { - assert_eq!(Some(elt), it.idx(i)); - } - - } - - #[test] - fn test_random_access_map() { - let xs = [1i, 2, 3, 4, 5]; - - let mut it = xs.iter().map(|x| *x); - assert_eq!(xs.len(), it.indexable()); - for (i, elt) in xs.iter().enumerate() { - assert_eq!(Some(*elt), it.idx(i)); - } - } - - #[test] - fn test_random_access_cycle() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().cycle().take(27), 27); - check_randacc_iter(empty.iter().cycle(), 0); - } - - #[test] - fn test_double_ended_range() { - assert!(range(11i, 14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]); - for _ in range(10i, 0).rev() { - fail!("unreachable"); - } - - assert!(range(11u, 14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]); - for _ in range(10u, 0).rev() { - fail!("unreachable"); - } - } - - #[test] - fn test_range() { - /// A mock type to check Range when ToPrimitive returns None - struct Foo; - - impl ToPrimitive for Foo { - fn to_i64(&self) -> Option<i64> { None } - fn to_u64(&self) -> Option<u64> { None } - } - - impl Add<Foo, Foo> for Foo { - fn add(&self, _: &Foo) -> Foo { - Foo - } - } - - impl PartialEq for Foo { - fn eq(&self, _: &Foo) -> bool { - true - } - } - - impl PartialOrd for Foo { - fn lt(&self, _: &Foo) -> bool { - false - } - } - - impl Clone for Foo { - fn clone(&self) -> Foo { - Foo - } - } - - impl Mul<Foo, Foo> for Foo { - fn mul(&self, _: &Foo) -> Foo { - Foo - } - } - - impl num::One for Foo { - fn one() -> Foo { - Foo - } - } - - assert!(range(0i, 5).collect::<Vec<int>>() == vec![0i, 1, 2, 3, 4]); - assert!(range(-10i, -1).collect::<Vec<int>>() == - vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); - assert!(range(0i, 5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]); - assert_eq!(range(200i, -5).count(), 0); - assert_eq!(range(200i, -5).rev().count(), 0); - assert_eq!(range(200i, 200).count(), 0); - assert_eq!(range(200i, 200).rev().count(), 0); - - assert_eq!(range(0i, 100).size_hint(), (100, Some(100))); - // this test is only meaningful when sizeof uint < sizeof u64 - assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1))); - assert_eq!(range(-10i, -1).size_hint(), (9, Some(9))); - assert_eq!(range(Foo, Foo).size_hint(), (0, None)); - } - - #[test] - fn test_range_inclusive() { - assert!(range_inclusive(0i, 5).collect::<Vec<int>>() == - vec![0i, 1, 2, 3, 4, 5]); - assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() == - vec![5i, 4, 3, 2, 1, 0]); - assert_eq!(range_inclusive(200i, -5).count(), 0); - assert_eq!(range_inclusive(200i, -5).rev().count(), 0); - assert!(range_inclusive(200i, 200).collect::<Vec<int>>() == vec![200]); - assert!(range_inclusive(200i, 200).rev().collect::<Vec<int>>() == vec![200]); - } - - #[test] - fn test_range_step() { - assert!(range_step(0i, 20, 5).collect::<Vec<int>>() == - vec![0, 5, 10, 15]); - assert!(range_step(20i, 0, -5).collect::<Vec<int>>() == - vec![20, 15, 10, 5]); - assert!(range_step(20i, 0, -6).collect::<Vec<int>>() == - vec![20, 14, 8, 2]); - assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() == - vec![200u8, 250]); - assert!(range_step(200i, -5, 1).collect::<Vec<int>>() == vec![]); - assert!(range_step(200i, 200, 1).collect::<Vec<int>>() == vec![]); - } - - #[test] - fn test_range_step_inclusive() { - assert!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>() == - vec![0, 5, 10, 15, 20]); - assert!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>() == - vec![20, 15, 10, 5, 0]); - assert!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>() == - vec![20, 14, 8, 2]); - assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() == - vec![200u8, 250]); - assert!(range_step_inclusive(200i, -5, 1).collect::<Vec<int>>() == - vec![]); - assert!(range_step_inclusive(200i, 200, 1).collect::<Vec<int>>() == - vec![200]); - } - - #[test] - fn test_reverse() { - let mut ys = [1i, 2, 3, 4, 5]; - ys.mut_iter().reverse_(); - assert!(ys == [5, 4, 3, 2, 1]); - } - - #[test] - fn test_peekable_is_empty() { - let a = [1i]; - let mut it = a.iter().peekable(); - assert!( !it.is_empty() ); - it.next(); - assert!( it.is_empty() ); - } - - #[test] - fn test_min_max() { - let v: [int, ..0] = []; - assert_eq!(v.iter().min_max(), NoElements); - - let v = [1i]; - assert!(v.iter().min_max() == OneElement(&1)); - - let v = [1i, 2, 3, 4, 5]; - assert!(v.iter().min_max() == MinMax(&1, &5)); - - let v = [1i, 2, 3, 4, 5, 6]; - assert!(v.iter().min_max() == MinMax(&1, &6)); - - let v = [1i, 1, 1, 1]; - assert!(v.iter().min_max() == MinMax(&1, &1)); - } - - #[test] - fn test_min_max_result() { - let r: MinMaxResult<int> = NoElements; - assert_eq!(r.into_option(), None) - - let r = OneElement(1i); - assert_eq!(r.into_option(), Some((1,1))); - - let r = MinMax(1i,2); - assert_eq!(r.into_option(), Some((1,2))); - } -} diff --git a/src/libcore/kinds.rs b/src/libcore/kinds.rs index 40b716181e6..9a6cdb1c769 100644 --- a/src/libcore/kinds.rs +++ b/src/libcore/kinds.rs @@ -155,7 +155,7 @@ pub mod marker { /// ``` /// use std::mem; /// - /// struct S<T> { x: *() } + /// struct S<T> { x: *const () } /// fn get<T>(s: &S<T>, v: T) { /// unsafe { /// let x: fn(T) = mem::transmute(s.x); diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 7d6d0d19037..08153355e9e 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -43,7 +43,9 @@ //! the failure message, the file at which failure was invoked, and the line. //! It is up to consumers of this core library to define this failure //! function; it is only required to never return. -//! + +// Since libcore defines many fundamental lang items, all tests live in a +// separate crate, libcoretest, to avoid bizarre issues. #![crate_id = "core#0.11.0"] #![experimental] @@ -58,17 +60,6 @@ #![feature(globs, intrinsics, lang_items, macro_rules, managed_boxes, phase)] #![feature(simd, unsafe_destructor)] #![deny(missing_doc)] -#![allow(unknown_features)] // NOTE: remove after stage0 snapshot - -#[cfg(test)] extern crate realcore = "core"; -#[cfg(test)] extern crate libc; -#[cfg(test)] extern crate native; -#[cfg(test)] extern crate realstd = "std"; - -#[cfg(test)] pub use cmp = realcore::cmp; -#[cfg(test)] pub use kinds = realcore::kinds; -#[cfg(test)] pub use ops = realcore::ops; -#[cfg(test)] pub use ty = realcore::ty; mod macros; @@ -105,10 +96,10 @@ pub mod ptr; /* Core language traits */ -#[cfg(not(test))] pub mod kinds; -#[cfg(not(test))] pub mod ops; -#[cfg(not(test))] pub mod ty; -#[cfg(not(test))] pub mod cmp; +pub mod kinds; +pub mod ops; +pub mod ty; +pub mod cmp; pub mod clone; pub mod default; pub mod collections; @@ -145,11 +136,4 @@ mod std { pub use kinds; pub use option; pub use fmt; - - #[cfg(test)] pub use realstd::rt; // needed for fail!() - // #[cfg(test)] pub use realstd::option; // needed for fail!() - // #[cfg(test)] pub use realstd::fmt; // needed for fail!() - #[cfg(test)] pub use realstd::os; // needed for tests - #[cfg(test)] pub use realstd::slice; // needed for tests - #[cfg(test)] pub use realstd::vec; // needed for vec![] } diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index a62bc10d8ab..93c838198c5 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -112,16 +112,6 @@ macro_rules! writeln( ) ) -#[cfg(test)] -macro_rules! vec( ($($e:expr),*) => ({ - let mut _v = ::std::vec::Vec::new(); - $(_v.push($e);)* - _v -}) ) - -#[cfg(test)] -macro_rules! format( ($($arg:tt)*) => (format_args!(::fmt::format, $($arg)*)) ) - /// Write some formatted data into a stream. /// /// Identical to the macro in `std::macros` diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index a2a3e09a93c..06e28816c1c 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -363,7 +363,7 @@ pub unsafe fn forget<T>(thing: T) { intrinsics::forget(thing) } #[inline] #[stable] pub unsafe fn transmute_copy<T, U>(src: &T) -> U { - ptr::read(src as *T as *U) + ptr::read(src as *const T as *const U) } /// Transforms lifetime of the second pointer to match the first. @@ -382,182 +382,3 @@ pub unsafe fn copy_mut_lifetime<'a, S, T>(_ptr: &'a mut S, ptr: &mut T) -> &'a mut T { transmute(ptr) } - -#[cfg(test)] -mod tests { - use mem::*; - use option::{Some,None}; - use realstd::str::StrAllocating; - use realstd::owned::Box; - use realstd::vec::Vec; - use raw; - - #[test] - fn size_of_basic() { - assert_eq!(size_of::<u8>(), 1u); - assert_eq!(size_of::<u16>(), 2u); - assert_eq!(size_of::<u32>(), 4u); - assert_eq!(size_of::<u64>(), 8u); - } - - #[test] - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - #[cfg(target_arch = "mipsel")] - fn size_of_32() { - assert_eq!(size_of::<uint>(), 4u); - assert_eq!(size_of::<*uint>(), 4u); - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn size_of_64() { - assert_eq!(size_of::<uint>(), 8u); - assert_eq!(size_of::<*uint>(), 8u); - } - - #[test] - fn size_of_val_basic() { - assert_eq!(size_of_val(&1u8), 1); - assert_eq!(size_of_val(&1u16), 2); - assert_eq!(size_of_val(&1u32), 4); - assert_eq!(size_of_val(&1u64), 8); - } - - #[test] - fn align_of_basic() { - assert_eq!(align_of::<u8>(), 1u); - assert_eq!(align_of::<u16>(), 2u); - assert_eq!(align_of::<u32>(), 4u); - } - - #[test] - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - #[cfg(target_arch = "mipsel")] - fn align_of_32() { - assert_eq!(align_of::<uint>(), 4u); - assert_eq!(align_of::<*uint>(), 4u); - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn align_of_64() { - assert_eq!(align_of::<uint>(), 8u); - assert_eq!(align_of::<*uint>(), 8u); - } - - #[test] - fn align_of_val_basic() { - assert_eq!(align_of_val(&1u8), 1u); - assert_eq!(align_of_val(&1u16), 2u); - assert_eq!(align_of_val(&1u32), 4u); - } - - #[test] - fn test_swap() { - let mut x = 31337i; - let mut y = 42i; - swap(&mut x, &mut y); - assert_eq!(x, 42); - assert_eq!(y, 31337); - } - - #[test] - fn test_replace() { - let mut x = Some("test".to_string()); - let y = replace(&mut x, None); - assert!(x.is_none()); - assert!(y.is_some()); - } - - #[test] - fn test_transmute_copy() { - assert_eq!(1u, unsafe { ::mem::transmute_copy(&1) }); - } - - #[test] - fn test_transmute() { - trait Foo {} - impl Foo for int {} - - let a = box 100i as Box<Foo>; - unsafe { - let x: raw::TraitObject = transmute(a); - assert!(*(x.data as *int) == 100); - let _x: Box<Foo> = transmute(x); - } - - unsafe { - assert!(Vec::from_slice([76u8]) == transmute("L".to_string())); - } - } -} - -// FIXME #13642 (these benchmarks should be in another place) -/// Completely miscellaneous language-construct benchmarks. -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use option::{Some,None}; - - // Static/dynamic method dispatch - - struct Struct { - field: int - } - - trait Trait { - fn method(&self) -> int; - } - - impl Trait for Struct { - fn method(&self) -> int { - self.field - } - } - - #[bench] - fn trait_vtable_method_call(b: &mut Bencher) { - let s = Struct { field: 10 }; - let t = &s as &Trait; - b.iter(|| { - t.method() - }); - } - - #[bench] - fn trait_static_method_call(b: &mut Bencher) { - let s = Struct { field: 10 }; - b.iter(|| { - s.method() - }); - } - - // Overhead of various match forms - - #[bench] - fn match_option_some(b: &mut Bencher) { - let x = Some(10); - b.iter(|| { - match x { - Some(y) => y, - None => 11 - } - }); - } - - #[bench] - fn match_vec_pattern(b: &mut Bencher) { - let x = [1,2,3,4,5,6]; - b.iter(|| { - match x { - [1,2,3,..] => 10, - _ => 11 - } - }); - } -} diff --git a/src/libcore/num/int_macros.rs b/src/libcore/num/int_macros.rs index ef10c9abe11..ff0494725f8 100644 --- a/src/libcore/num/int_macros.rs +++ b/src/libcore/num/int_macros.rs @@ -32,152 +32,4 @@ pub static MIN: $T = (-1 as $T) << (BITS - 1); #[unstable] pub static MAX: $T = !MIN; -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - - use int; - use num; - use num::CheckedDiv; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert!(MIN + MAX + 1 == 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - pub fn test_abs() { - assert!((1 as $T).abs() == 1 as $T); - assert!((0 as $T).abs() == 0 as $T); - assert!((-1 as $T).abs() == 1 as $T); - } - - #[test] - fn test_abs_sub() { - assert!((-1 as $T).abs_sub(&(1 as $T)) == 0 as $T); - assert!((1 as $T).abs_sub(&(1 as $T)) == 0 as $T); - assert!((1 as $T).abs_sub(&(0 as $T)) == 1 as $T); - assert!((1 as $T).abs_sub(&(-1 as $T)) == 2 as $T); - } - - #[test] - fn test_signum() { - assert!((1 as $T).signum() == 1 as $T); - assert!((0 as $T).signum() == 0 as $T); - assert!((-0 as $T).signum() == 0 as $T); - assert!((-1 as $T).signum() == -1 as $T); - } - - #[test] - fn test_is_positive() { - assert!((1 as $T).is_positive()); - assert!(!(0 as $T).is_positive()); - assert!(!(-0 as $T).is_positive()); - assert!(!(-1 as $T).is_positive()); - } - - #[test] - fn test_is_negative() { - assert!(!(1 as $T).is_negative()); - assert!(!(0 as $T).is_negative()); - assert!(!(-0 as $T).is_negative()); - assert!((-1 as $T).is_negative()); - } - - #[test] - fn test_bitwise_operators() { - assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); - assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); - assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); - assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); - assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); - assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not()); - } - - static A: $T = 0b0101100; - static B: $T = 0b0100001; - static C: $T = 0b1111001; - - static _0: $T = 0; - static _1: $T = !0; - - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); - } - - #[test] - fn test_count_zeros() { - assert!(A.count_zeros() == BITS as $T - 3); - assert!(B.count_zeros() == BITS as $T - 2); - assert!(C.count_zeros() == BITS as $T - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_le() { - assert_eq!(Int::from_le(A.to_le()), A); - assert_eq!(Int::from_le(B.to_le()), B); - assert_eq!(Int::from_le(C.to_le()), C); - assert_eq!(Int::from_le(_0), _0); - assert_eq!(Int::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!(Int::from_be(A.to_be()), A); - assert_eq!(Int::from_be(B.to_be()), B); - assert_eq!(Int::from_be(C.to_be()), C); - assert_eq!(Int::from_be(_0), _0); - assert_eq!(Int::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_signed_checked_div() { - assert!(10i.checked_div(&2) == Some(5)); - assert!(5i.checked_div(&0) == None); - assert!(int::MIN.checked_div(&-1) == None); - } -} - )) diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 512c107b930..b32e4167da1 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -1375,22 +1375,6 @@ macro_rules! checkeddiv_uint_impl( checkeddiv_uint_impl!(uint u8 u16 u32 u64) -/// Helper function for testing numeric operations -#[cfg(test)] -pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) { - assert_eq!(ten.add(&two), cast(12i).unwrap()); - assert_eq!(ten.sub(&two), cast(8i).unwrap()); - assert_eq!(ten.mul(&two), cast(20i).unwrap()); - assert_eq!(ten.div(&two), cast(5i).unwrap()); - assert_eq!(ten.rem(&two), cast(0i).unwrap()); - - assert_eq!(ten.add(&two), ten + two); - assert_eq!(ten.sub(&two), ten - two); - assert_eq!(ten.mul(&two), ten * two); - assert_eq!(ten.div(&two), ten / two); - assert_eq!(ten.rem(&two), ten % two); -} - /// Used for representing the classification of floating point numbers #[deriving(PartialEq, Show)] pub enum FPCategory { diff --git a/src/libcore/num/uint_macros.rs b/src/libcore/num/uint_macros.rs index 5828697ddad..b0c570af04a 100644 --- a/src/libcore/num/uint_macros.rs +++ b/src/libcore/num/uint_macros.rs @@ -23,111 +23,4 @@ pub static MIN: $T = 0 as $T; #[unstable] pub static MAX: $T = 0 as $T - 1 as $T; -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - - use num; - use num::CheckedDiv; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert!(MIN + MAX + 1 == 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - fn test_bitwise_operators() { - assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); - assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); - assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); - assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); - assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); - assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); - } - - static A: $T = 0b0101100; - static B: $T = 0b0100001; - static C: $T = 0b1111001; - - static _0: $T = 0; - static _1: $T = !0; - - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); - } - - #[test] - fn test_count_zeros() { - assert!(A.count_zeros() == BITS as $T - 3); - assert!(B.count_zeros() == BITS as $T - 2); - assert!(C.count_zeros() == BITS as $T - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_le() { - assert_eq!(Int::from_le(A.to_le()), A); - assert_eq!(Int::from_le(B.to_le()), B); - assert_eq!(Int::from_le(C.to_le()), C); - assert_eq!(Int::from_le(_0), _0); - assert_eq!(Int::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!(Int::from_be(A.to_be()), A); - assert_eq!(Int::from_be(B.to_be()), B); - assert_eq!(Int::from_be(C.to_be()), C); - assert_eq!(Int::from_be(_0), _0); - assert_eq!(Int::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_unsigned_checked_div() { - assert!(10u.checked_div(&2) == Some(5)); - assert!(5u.checked_div(&0) == None); - } -} - )) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 14edd7c70a8..d42c09b8163 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -117,7 +117,6 @@ pub trait Add<RHS,Result> { macro_rules! add_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Add<$t, $t> for $t { #[inline] fn add(&self, other: &$t) -> $t { (*self) + (*other) } @@ -159,7 +158,6 @@ pub trait Sub<RHS,Result> { macro_rules! sub_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Sub<$t, $t> for $t { #[inline] fn sub(&self, other: &$t) -> $t { (*self) - (*other) } @@ -201,7 +199,6 @@ pub trait Mul<RHS,Result> { macro_rules! mul_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Mul<$t, $t> for $t { #[inline] fn mul(&self, other: &$t) -> $t { (*self) * (*other) } @@ -243,7 +240,6 @@ pub trait Div<RHS,Result> { macro_rules! div_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Div<$t, $t> for $t { #[inline] fn div(&self, other: &$t) -> $t { (*self) / (*other) } @@ -285,7 +281,6 @@ pub trait Rem<RHS,Result> { macro_rules! rem_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Rem<$t, $t> for $t { #[inline] fn rem(&self, other: &$t) -> $t { (*self) % (*other) } @@ -295,7 +290,6 @@ macro_rules! rem_impl( macro_rules! rem_float_impl( ($t:ty, $fmod:ident) => { - #[cfg(not(test))] impl Rem<$t, $t> for $t { #[inline] fn rem(&self, other: &$t) -> $t { @@ -342,7 +336,6 @@ pub trait Neg<Result> { macro_rules! neg_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Neg<$t> for $t { #[inline] fn neg(&self) -> $t { -*self } @@ -352,7 +345,6 @@ macro_rules! neg_impl( macro_rules! neg_uint_impl( ($t:ty, $t_signed:ty) => { - #[cfg(not(test))] impl Neg<$t> for $t { #[inline] fn neg(&self) -> $t { -(*self as $t_signed) as $t } @@ -402,7 +394,6 @@ pub trait Not<Result> { macro_rules! not_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Not<$t> for $t { #[inline] fn not(&self) -> $t { !*self } @@ -444,7 +435,6 @@ pub trait BitAnd<RHS,Result> { macro_rules! bitand_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitAnd<$t, $t> for $t { #[inline] fn bitand(&self, rhs: &$t) -> $t { (*self) & (*rhs) } @@ -486,7 +476,6 @@ pub trait BitOr<RHS,Result> { macro_rules! bitor_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitOr<$t,$t> for $t { #[inline] fn bitor(&self, rhs: &$t) -> $t { (*self) | (*rhs) } @@ -528,7 +517,6 @@ pub trait BitXor<RHS,Result> { macro_rules! bitxor_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitXor<$t, $t> for $t { #[inline] fn bitxor(&self, other: &$t) -> $t { (*self) ^ (*other) } @@ -570,12 +558,6 @@ pub trait Shl<RHS,Result> { macro_rules! shl_impl( ($($t:ty)*) => ($( - #[cfg(stage0)] - impl Shl<$t, $t> for $t { - #[inline] - fn shl(&self, other: &$t) -> $t { (*self) << (*other) } - } - #[cfg(not(stage0), not(test))] impl Shl<$t, $t> for $t { #[inline] fn shl(&self, other: &$t) -> $t { @@ -619,12 +601,6 @@ pub trait Shr<RHS,Result> { macro_rules! shr_impl( ($($t:ty)*) => ($( - #[cfg(stage0, not(test))] - impl Shr<$t, $t> for $t { - #[inline] - fn shr(&self, other: &$t) -> $t { (*self) >> (*other) } - } - #[cfg(not(stage0), not(test))] impl Shr<$t, $t> for $t { #[inline] fn shr(&self, other: &$t) -> $t { (*self) >> (*other as uint) } @@ -758,28 +734,3 @@ pub trait FnOnce<Args,Result> { /// This is called when the call operator is used. fn call_once(self, args: Args) -> Result; } - -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use ops::Drop; - - // Overhead of dtors - - struct HasDtor { - x: int - } - - impl Drop for HasDtor { - fn drop(&mut self) { - } - } - - #[bench] - fn alloc_obj_with_dtor(b: &mut Bencher) { - b.iter(|| { - HasDtor { x : 10 }; - }) - } -} diff --git a/src/libcore/option.rs b/src/libcore/option.rs index e9fb7c3dae3..b8612ed93e0 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -587,310 +587,34 @@ impl<A> ExactSize<A> for Item<A> {} /// ``` #[inline] pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) -> Option<V> { - // FIXME(#11084): This should be twice as fast once this bug is closed. - let mut iter = iter.scan(false, |state, x| { - match x { - Some(x) => Some(x), - None => { - *state = true; - None + // FIXME(#11084): This could be replaced with Iterator::scan when this + // performance bug is closed. + + struct Adapter<Iter> { + iter: Iter, + found_none: bool, + } + + impl<T, Iter: Iterator<Option<T>>> Iterator<T> for Adapter<Iter> { + #[inline] + fn next(&mut self) -> Option<T> { + match self.iter.next() { + Some(Some(value)) => Some(value), + Some(None) => { + self.found_none = true; + None + } + None => None, } } - }); + } - let v: V = FromIterator::from_iter(iter.by_ref()); + let mut adapter = Adapter { iter: iter, found_none: false }; + let v: V = FromIterator::from_iter(adapter.by_ref()); - if iter.state { + if adapter.found_none { None } else { Some(v) } } - -///////////////////////////////////////////////////////////////////////////// -// Tests -///////////////////////////////////////////////////////////////////////////// - -#[cfg(test)] -mod tests { - use realstd::vec::Vec; - use realstd::string::String; - use option::collect; - use prelude::*; - use realstd::str::{Str, StrAllocating}; - use iter::range; - - use str::StrSlice; - use kinds::marker; - use slice::ImmutableVector; - - #[test] - fn test_get_ptr() { - unsafe { - let x = box 0; - let addr_x: *int = ::mem::transmute(&*x); - let opt = Some(x); - let y = opt.unwrap(); - let addr_y: *int = ::mem::transmute(&*y); - assert_eq!(addr_x, addr_y); - } - } - - #[test] - fn test_get_str() { - let x = "test".to_string(); - let addr_x = x.as_slice().as_ptr(); - let opt = Some(x); - let y = opt.unwrap(); - let addr_y = y.as_slice().as_ptr(); - assert_eq!(addr_x, addr_y); - } - - #[test] - fn test_get_resource() { - use realstd::rc::Rc; - use cell::RefCell; - - struct R { - i: Rc<RefCell<int>>, - } - - #[unsafe_destructor] - impl ::ops::Drop for R { - fn drop(&mut self) { - let ii = &*self.i; - let i = *ii.borrow(); - *ii.borrow_mut() = i + 1; - } - } - - fn r(i: Rc<RefCell<int>>) -> R { - R { - i: i - } - } - - fn realclone<T: ::realstd::clone::Clone>(t: &T) -> T { - use realstd::clone::Clone; - t.clone() - } - - let i = Rc::new(RefCell::new(0i)); - { - let x = r(realclone(&i)); - let opt = Some(x); - let _y = opt.unwrap(); - } - assert_eq!(*i.borrow(), 1); - } - - #[test] - fn test_option_dance() { - let x = Some(()); - let mut y = Some(5i); - let mut y2 = 0; - for _x in x.iter() { - y2 = y.take_unwrap(); - } - assert_eq!(y2, 5); - assert!(y.is_none()); - } - - #[test] #[should_fail] - fn test_option_too_much_dance() { - let mut y = Some(marker::NoCopy); - let _y2 = y.take_unwrap(); - let _y3 = y.take_unwrap(); - } - - #[test] - fn test_and() { - let x: Option<int> = Some(1i); - assert_eq!(x.and(Some(2i)), Some(2)); - assert_eq!(x.and(None::<int>), None); - - let x: Option<int> = None; - assert_eq!(x.and(Some(2i)), None); - assert_eq!(x.and(None::<int>), None); - } - - #[test] - fn test_and_then() { - let x: Option<int> = Some(1); - assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); - assert_eq!(x.and_then(|_| None::<int>), None); - - let x: Option<int> = None; - assert_eq!(x.and_then(|x| Some(x + 1)), None); - assert_eq!(x.and_then(|_| None::<int>), None); - } - - #[test] - fn test_or() { - let x: Option<int> = Some(1); - assert_eq!(x.or(Some(2)), Some(1)); - assert_eq!(x.or(None), Some(1)); - - let x: Option<int> = None; - assert_eq!(x.or(Some(2)), Some(2)); - assert_eq!(x.or(None), None); - } - - #[test] - fn test_or_else() { - let x: Option<int> = Some(1); - assert_eq!(x.or_else(|| Some(2)), Some(1)); - assert_eq!(x.or_else(|| None), Some(1)); - - let x: Option<int> = None; - assert_eq!(x.or_else(|| Some(2)), Some(2)); - assert_eq!(x.or_else(|| None), None); - } - - #[test] - fn test_option_while_some() { - let mut i = 0i; - Some(10).while_some(|j| { - i += 1; - if j > 0 { - Some(j-1) - } else { - None - } - }); - assert_eq!(i, 11); - } - - #[test] - fn test_unwrap() { - assert_eq!(Some(1i).unwrap(), 1); - let s = Some("hello".to_string()).unwrap(); - assert_eq!(s.as_slice(), "hello"); - } - - #[test] - #[should_fail] - fn test_unwrap_fail1() { - let x: Option<int> = None; - x.unwrap(); - } - - #[test] - #[should_fail] - fn test_unwrap_fail2() { - let x: Option<String> = None; - x.unwrap(); - } - - #[test] - fn test_unwrap_or() { - let x: Option<int> = Some(1); - assert_eq!(x.unwrap_or(2), 1); - - let x: Option<int> = None; - assert_eq!(x.unwrap_or(2), 2); - } - - #[test] - fn test_unwrap_or_else() { - let x: Option<int> = Some(1); - assert_eq!(x.unwrap_or_else(|| 2), 1); - - let x: Option<int> = None; - assert_eq!(x.unwrap_or_else(|| 2), 2); - } - - #[test] - fn test_filtered() { - let some_stuff = Some(42i); - let modified_stuff = some_stuff.filtered(|&x| {x < 10}); - assert_eq!(some_stuff.unwrap(), 42); - assert!(modified_stuff.is_none()); - } - - #[test] - fn test_iter() { - let val = 5i; - - let x = Some(val); - let mut it = x.iter(); - - assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next(), Some(&val)); - assert_eq!(it.size_hint(), (0, Some(0))); - assert!(it.next().is_none()); - } - - #[test] - fn test_mut_iter() { - let val = 5i; - let new_val = 11i; - - let mut x = Some(val); - { - let mut it = x.mut_iter(); - - assert_eq!(it.size_hint(), (1, Some(1))); - - match it.next() { - Some(interior) => { - assert_eq!(*interior, val); - *interior = new_val; - } - None => assert!(false), - } - - assert_eq!(it.size_hint(), (0, Some(0))); - assert!(it.next().is_none()); - } - assert_eq!(x, Some(new_val)); - } - - #[test] - fn test_ord() { - let small = Some(1.0f64); - let big = Some(5.0f64); - let nan = Some(0.0f64/0.0); - assert!(!(nan < big)); - assert!(!(nan > big)); - assert!(small < big); - assert!(None < big); - assert!(big > None); - } - - #[test] - fn test_mutate() { - let mut x = Some(3i); - assert!(x.mutate(|i| i+1)); - assert_eq!(x, Some(4i)); - assert!(x.mutate_or_set(0, |i| i+1)); - assert_eq!(x, Some(5i)); - x = None; - assert!(!x.mutate(|i| i+1)); - assert_eq!(x, None); - assert!(!x.mutate_or_set(0i, |i| i+1)); - assert_eq!(x, Some(0i)); - } - - #[test] - fn test_collect() { - let v: Option<Vec<int>> = collect(range(0i, 0) - .map(|_| Some(0i))); - assert!(v == Some(vec![])); - - let v: Option<Vec<int>> = collect(range(0i, 3) - .map(|x| Some(x))); - assert!(v == Some(vec![0, 1, 2])); - - let v: Option<Vec<int>> = collect(range(0i, 3) - .map(|x| if x > 1 { None } else { Some(x) })); - assert!(v == None); - - // test that it does not take more elements than it needs - let mut functions = [|| Some(()), || None, || fail!()]; - - let v: Option<Vec<()>> = collect(functions.mut_iter().map(|f| (*f)())); - - assert!(v == None); - } -} diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 59d7bbfe52d..093591cd796 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -10,7 +10,7 @@ // FIXME: talk about offset, copy_memory, copy_nonoverlapping_memory -//! Operations on unsafe pointers, `*T`, and `*mut T`. +//! Operations on unsafe pointers, `*const T`, and `*mut T`. //! //! Working with unsafe pointers in Rust is uncommon, //! typically limited to a few patterns. @@ -29,7 +29,7 @@ //! //! ``` //! let my_num: int = 10; -//! let my_num_ptr: *int = &my_num; +//! let my_num_ptr: *const int = &my_num; //! let mut my_speed: int = 88; //! let my_speed_ptr: *mut int = &mut my_speed; //! ``` @@ -42,7 +42,7 @@ //! //! The `transmute` function takes, by value, whatever it's given //! and returns it as whatever type is requested, as long as the -//! types are the same size. Because `Box<T>` and `*T` have the same +//! types are the same size. Because `Box<T>` and `*mut T` have the same //! representation they can be trivially, //! though unsafely, transformed from one type to the other. //! @@ -51,7 +51,7 @@ //! //! unsafe { //! let my_num: Box<int> = box 10; -//! let my_num: *int = mem::transmute(my_num); +//! let my_num: *const int = mem::transmute(my_num); //! let my_speed: Box<int> = box 88; //! let my_speed: *mut int = mem::transmute(my_speed); //! @@ -93,7 +93,7 @@ use intrinsics; use iter::{range, Iterator}; use option::{Some, None, Option}; -#[cfg(not(test))] use cmp::{PartialEq, Eq, PartialOrd, Equiv}; +use cmp::{PartialEq, Eq, PartialOrd, Equiv, Ordering, Less, Equal, Greater}; /// Create a null pointer. /// @@ -102,12 +102,12 @@ use option::{Some, None, Option}; /// ``` /// use std::ptr; /// -/// let p: *int = ptr::null(); +/// let p: *const int = ptr::null(); /// assert!(p.is_null()); /// ``` #[inline] #[unstable = "may need a different name after pending changes to pointer types"] -pub fn null<T>() -> *T { 0 as *T } +pub fn null<T>() -> *const T { 0 as *const T } /// Create an unsafe mutable null pointer. /// @@ -137,7 +137,7 @@ pub fn mut_null<T>() -> *mut T { 0 as *mut T } /// ``` /// use std::ptr; /// -/// unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> Vec<T> { +/// unsafe fn from_buf_raw<T>(ptr: *const T, elts: uint) -> Vec<T> { /// let mut dst = Vec::with_capacity(elts); /// dst.set_len(elts); /// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts); @@ -147,7 +147,7 @@ pub fn mut_null<T>() -> *mut T { 0 as *mut T } /// #[inline] #[unstable] -pub unsafe fn copy_memory<T>(dst: *mut T, src: *T, count: uint) { +pub unsafe fn copy_memory<T>(dst: *mut T, src: *const T, count: uint) { intrinsics::copy_memory(dst, src, count) } @@ -190,7 +190,7 @@ pub unsafe fn copy_memory<T>(dst: *mut T, src: *T, count: uint) { #[inline] #[unstable] pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T, - src: *T, + src: *const T, count: uint) { intrinsics::copy_nonoverlapping_memory(dst, src, count) } @@ -242,7 +242,7 @@ pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T { /// Reads the value from `*src` and returns it. #[inline(always)] #[unstable] -pub unsafe fn read<T>(src: *T) -> T { +pub unsafe fn read<T>(src: *const T) -> T { let mut tmp: T = mem::uninitialized(); copy_nonoverlapping_memory(&mut tmp, src, 1); tmp @@ -275,11 +275,12 @@ pub unsafe fn write<T>(dst: *mut T, src: T) { intrinsics::move_val_init(&mut *dst, src) } -/// Given a **T (pointer to an array of pointers), -/// iterate through each *T, up to the provided `len`, +/// Given a *const *const T (pointer to an array of pointers), +/// iterate through each *const T, up to the provided `len`, /// passing to the provided callback function #[deprecated = "old-style iteration. use a loop and RawPtr::offset"] -pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) { +pub unsafe fn array_each_with_len<T>(arr: *const *const T, len: uint, + cb: |*const T|) { if arr.is_null() { fail!("ptr::array_each_with_len failure: arr input is null pointer"); } @@ -290,8 +291,8 @@ pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) { } } -/// Given a null-pointer-terminated **T (pointer to -/// an array of pointers), iterate through each *T, +/// Given a null-pointer-terminated *const *const T (pointer to +/// an array of pointers), iterate through each *const T, /// passing to the provided callback function /// /// # Safety Note @@ -300,7 +301,7 @@ pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: |*T|) { /// pointer array. #[deprecated = "old-style iteration. use a loop and RawPtr::offset"] #[allow(deprecated)] -pub unsafe fn array_each<T>(arr: **T, cb: |*T|) { +pub unsafe fn array_each<T>(arr: *const *const T, cb: |*const T|) { if arr.is_null() { fail!("ptr::array_each_with_len failure: arr input is null pointer"); } @@ -312,14 +313,14 @@ pub unsafe fn array_each<T>(arr: **T, cb: |*T|) { #[inline] #[deprecated = "use a loop and RawPtr::offset"] #[allow(deprecated)] -pub unsafe fn buf_len<T>(buf: **T) -> uint { +pub unsafe fn buf_len<T>(buf: *const *const T) -> uint { position(buf, |i| *i == null()) } /// Return the first offset `i` such that `f(buf[i]) == true`. #[inline] #[deprecated = "old-style iteration. use a loop and RawPtr::offset"] -pub unsafe fn position<T>(buf: *T, f: |&T| -> bool) -> uint { +pub unsafe fn position<T>(buf: *const T, f: |&T| -> bool) -> uint { let mut i = 0; loop { if f(&(*buf.offset(i as int))) { return i; } @@ -352,9 +353,9 @@ pub trait RawPtr<T> { unsafe fn offset(self, count: int) -> Self; } -impl<T> RawPtr<T> for *T { +impl<T> RawPtr<T> for *const T { #[inline] - fn null() -> *T { null() } + fn null() -> *const T { null() } #[inline] fn is_null(&self) -> bool { *self == RawPtr::null() } @@ -363,7 +364,9 @@ impl<T> RawPtr<T> for *T { fn to_uint(&self) -> uint { *self as uint } #[inline] - unsafe fn offset(self, count: int) -> *T { intrinsics::offset(self, count) } + unsafe fn offset(self, count: int) -> *const T { + intrinsics::offset(self, count) + } #[inline] unsafe fn to_option(&self) -> Option<&T> { @@ -387,7 +390,7 @@ impl<T> RawPtr<T> for *mut T { #[inline] unsafe fn offset(self, count: int) -> *mut T { - intrinsics::offset(self as *T, count) as *mut T + intrinsics::offset(self as *const T, count) as *mut T } #[inline] @@ -401,20 +404,17 @@ impl<T> RawPtr<T> for *mut T { } // Equality for pointers -#[cfg(not(test))] -impl<T> PartialEq for *T { +impl<T> PartialEq for *const T { #[inline] - fn eq(&self, other: &*T) -> bool { + fn eq(&self, other: &*const T) -> bool { *self == *other } #[inline] - fn ne(&self, other: &*T) -> bool { !self.eq(other) } + fn ne(&self, other: &*const T) -> bool { !self.eq(other) } } -#[cfg(not(test))] -impl<T> Eq for *T {} +impl<T> Eq for *const T {} -#[cfg(not(test))] impl<T> PartialEq for *mut T { #[inline] fn eq(&self, other: &*mut T) -> bool { @@ -424,27 +424,24 @@ impl<T> PartialEq for *mut T { fn ne(&self, other: &*mut T) -> bool { !self.eq(other) } } -#[cfg(not(test))] impl<T> Eq for *mut T {} // Equivalence for pointers -#[cfg(not(test))] -impl<T> Equiv<*mut T> for *T { +impl<T> Equiv<*mut T> for *const T { fn equiv(&self, other: &*mut T) -> bool { self.to_uint() == other.to_uint() } } -#[cfg(not(test))] -impl<T> Equiv<*T> for *mut T { - fn equiv(&self, other: &*T) -> bool { +impl<T> Equiv<*const T> for *mut T { + fn equiv(&self, other: &*const T) -> bool { self.to_uint() == other.to_uint() } } -impl<T> Clone for *T { +impl<T> Clone for *const T { #[inline] - fn clone(&self) -> *T { + fn clone(&self) -> *const T { *self } } @@ -457,7 +454,6 @@ impl<T> Clone for *mut T { } // Equality for extern "C" fn pointers -#[cfg(not(test))] mod externfnpointers { use mem; use cmp::PartialEq; @@ -465,8 +461,8 @@ mod externfnpointers { impl<_R> PartialEq for extern "C" fn() -> _R { #[inline] fn eq(&self, other: &extern "C" fn() -> _R) -> bool { - let self_: *() = unsafe { mem::transmute(*self) }; - let other_: *() = unsafe { mem::transmute(*other) }; + let self_: *const () = unsafe { mem::transmute(*self) }; + let other_: *const () = unsafe { mem::transmute(*other) }; self_ == other_ } } @@ -475,8 +471,9 @@ mod externfnpointers { impl<_R,$($p),*> PartialEq for extern "C" fn($($p),*) -> _R { #[inline] fn eq(&self, other: &extern "C" fn($($p),*) -> _R) -> bool { - let self_: *() = unsafe { mem::transmute(*self) }; - let other_: *() = unsafe { mem::transmute(*other) }; + let self_: *const () = unsafe { mem::transmute(*self) }; + + let other_: *const () = unsafe { mem::transmute(*other) }; self_ == other_ } } @@ -490,274 +487,52 @@ mod externfnpointers { } // Comparison for pointers -#[cfg(not(test))] -impl<T> PartialOrd for *T { - #[inline] - fn lt(&self, other: &*T) -> bool { *self < *other } -} - -#[cfg(not(test))] -impl<T> PartialOrd for *mut T { +impl<T> PartialOrd for *const T { #[inline] - fn lt(&self, other: &*mut T) -> bool { *self < *other } -} - -#[cfg(test)] -#[allow(deprecated, experimental)] -pub mod test { - use super::*; - use prelude::*; - - use realstd::c_str::ToCStr; - use mem; - use libc; - use realstd::str; - use realstd::str::Str; - use realstd::vec::Vec; - use realstd::collections::Collection; - use slice::{ImmutableVector, MutableVector}; - - #[test] - fn test() { - unsafe { - struct Pair { - fst: int, - snd: int - }; - let mut p = Pair {fst: 10, snd: 20}; - let pptr: *mut Pair = &mut p; - let iptr: *mut int = mem::transmute(pptr); - assert_eq!(*iptr, 10); - *iptr = 30; - assert_eq!(*iptr, 30); - assert_eq!(p.fst, 30); - - *pptr = Pair {fst: 50, snd: 60}; - assert_eq!(*iptr, 50); - assert_eq!(p.fst, 50); - assert_eq!(p.snd, 60); - - let v0 = vec![32000u16, 32001u16, 32002u16]; - let mut v1 = vec![0u16, 0u16, 0u16]; - - copy_memory(v1.as_mut_ptr().offset(1), - v0.as_ptr().offset(1), 1); - assert!((*v1.get(0) == 0u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 0u16)); - copy_memory(v1.as_mut_ptr(), - v0.as_ptr().offset(2), 1); - assert!((*v1.get(0) == 32002u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 0u16)); - copy_memory(v1.as_mut_ptr().offset(2), - v0.as_ptr(), 1u); - assert!((*v1.get(0) == 32002u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 32000u16)); - } - } - - #[test] - fn test_position() { - use libc::c_char; - - "hello".with_c_str(|p| { - unsafe { - assert!(2u == position(p, |c| *c == 'l' as c_char)); - assert!(4u == position(p, |c| *c == 'o' as c_char)); - assert!(5u == position(p, |c| *c == 0 as c_char)); - } - }) - } - - #[test] - fn test_buf_len() { - "hello".with_c_str(|p0| { - "there".with_c_str(|p1| { - "thing".with_c_str(|p2| { - let v = vec![p0, p1, p2, null()]; - unsafe { - assert_eq!(buf_len(v.as_ptr()), 3u); - } - }) - }) - }) - } - - #[test] - fn test_is_null() { - let p: *int = null(); - assert!(p.is_null()); - assert!(!p.is_not_null()); - - let q = unsafe { p.offset(1) }; - assert!(!q.is_null()); - assert!(q.is_not_null()); - - let mp: *mut int = mut_null(); - assert!(mp.is_null()); - assert!(!mp.is_not_null()); - - let mq = unsafe { mp.offset(1) }; - assert!(!mq.is_null()); - assert!(mq.is_not_null()); - } - - #[test] - fn test_to_option() { - unsafe { - let p: *int = null(); - assert_eq!(p.to_option(), None); - - let q: *int = &2; - assert_eq!(q.to_option().unwrap(), &2); - - let p: *mut int = mut_null(); - assert_eq!(p.to_option(), None); - - let q: *mut int = &mut 2; - assert_eq!(q.to_option().unwrap(), &2); - } - } - - #[test] - fn test_ptr_addition() { - unsafe { - let xs = Vec::from_elem(16, 5i); - let mut ptr = xs.as_ptr(); - let end = ptr.offset(16); - - while ptr < end { - assert_eq!(*ptr, 5); - ptr = ptr.offset(1); - } - - let mut xs_mut = xs; - let mut m_ptr = xs_mut.as_mut_ptr(); - let m_end = m_ptr.offset(16); - - while m_ptr < m_end { - *m_ptr += 5; - m_ptr = m_ptr.offset(1); - } - - assert!(xs_mut == Vec::from_elem(16, 10i)); + fn partial_cmp(&self, other: &*const T) -> Option<Ordering> { + if self < other { + Some(Less) + } else if self == other { + Some(Equal) + } else { + Some(Greater) } } - #[test] - fn test_ptr_subtraction() { - unsafe { - let xs = vec![0,1,2,3,4,5,6,7,8,9]; - let mut idx = 9i8; - let ptr = xs.as_ptr(); + #[inline] + fn lt(&self, other: &*const T) -> bool { *self < *other } - while idx >= 0i8 { - assert_eq!(*(ptr.offset(idx as int)), idx as int); - idx = idx - 1i8; - } + #[inline] + fn le(&self, other: &*const T) -> bool { *self <= *other } - let mut xs_mut = xs; - let m_start = xs_mut.as_mut_ptr(); - let mut m_ptr = m_start.offset(9); + #[inline] + fn gt(&self, other: &*const T) -> bool { *self > *other } - while m_ptr >= m_start { - *m_ptr += *m_ptr; - m_ptr = m_ptr.offset(-1); - } + #[inline] + fn ge(&self, other: &*const T) -> bool { *self >= *other } +} - assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]); +impl<T> PartialOrd for *mut T { + #[inline] + fn partial_cmp(&self, other: &*mut T) -> Option<Ordering> { + if self < other { + Some(Less) + } else if self == other { + Some(Equal) + } else { + Some(Greater) } } - #[test] - fn test_ptr_array_each_with_len() { - unsafe { - let one = "oneOne".to_c_str(); - let two = "twoTwo".to_c_str(); - let three = "threeThree".to_c_str(); - let arr = vec![ - one.with_ref(|buf| buf), - two.with_ref(|buf| buf), - three.with_ref(|buf| buf) - ]; - let expected_arr = [ - one, two, three - ]; - - let mut ctr = 0; - let mut iteration_count = 0; - array_each_with_len(arr.as_ptr(), arr.len(), |e| { - let actual = str::raw::from_c_str(e); - let expected = expected_arr[ctr].with_ref(|buf| { - str::raw::from_c_str(buf) - }); - assert_eq!(actual.as_slice(), expected.as_slice()); - ctr += 1; - iteration_count += 1; - }); - assert_eq!(iteration_count, 3u); - } - } + #[inline] + fn lt(&self, other: &*mut T) -> bool { *self < *other } - #[test] - fn test_ptr_array_each() { - unsafe { - let one = "oneOne".to_c_str(); - let two = "twoTwo".to_c_str(); - let three = "threeThree".to_c_str(); - let arr = vec![ - one.with_ref(|buf| buf), - two.with_ref(|buf| buf), - three.with_ref(|buf| buf), - // fake a null terminator - null() - ]; - let expected_arr = [ - one, two, three - ]; - - let arr_ptr = arr.as_ptr(); - let mut ctr = 0u; - let mut iteration_count = 0u; - array_each(arr_ptr, |e| { - let actual = str::raw::from_c_str(e); - let expected = expected_arr[ctr].with_ref(|buf| { - str::raw::from_c_str(buf) - }); - assert_eq!(actual.as_slice(), expected.as_slice()); - ctr += 1; - iteration_count += 1; - }); - assert_eq!(iteration_count, 3); - } - } + #[inline] + fn le(&self, other: &*mut T) -> bool { *self <= *other } - #[test] - #[should_fail] - fn test_ptr_array_each_with_len_null_ptr() { - unsafe { - array_each_with_len(0 as **libc::c_char, 1, |e| { - str::raw::from_c_str(e); - }); - } - } - #[test] - #[should_fail] - fn test_ptr_array_each_null_ptr() { - unsafe { - array_each(0 as **libc::c_char, |e| { - str::raw::from_c_str(e); - }); - } - } + #[inline] + fn gt(&self, other: &*mut T) -> bool { *self > *other } - #[test] - fn test_set_memory() { - let mut xs = [0u8, ..20]; - let ptr = xs.as_mut_ptr(); - unsafe { set_memory(ptr, 5u8, xs.len()); } - assert!(xs == [5u8, ..20]); - } + #[inline] + fn ge(&self, other: &*mut T) -> bool { *self >= *other } } diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index 0a2a756c6b1..da9fab0fc6f 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -31,20 +31,20 @@ pub struct Box<T> { /// The representation of a Rust slice pub struct Slice<T> { - pub data: *T, + pub data: *const T, pub len: uint, } /// The representation of a Rust closure pub struct Closure { - pub code: *(), - pub env: *(), + pub code: *mut (), + pub env: *mut (), } /// The representation of a Rust procedure (`proc()`) pub struct Procedure { - pub code: *(), - pub env: *(), + pub code: *mut (), + pub env: *mut (), } /// The representation of a Rust trait object. @@ -52,8 +52,8 @@ pub struct Procedure { /// This struct does not have a `Repr` implementation /// because there is no way to refer to all trait objects generically. pub struct TraitObject { - pub vtable: *(), - pub data: *(), + pub vtable: *mut (), + pub data: *mut (), } /// This trait is meant to map equivalences between raw structs and their @@ -70,32 +70,3 @@ pub trait Repr<T> { impl<'a, T> Repr<Slice<T>> for &'a [T] {} impl<'a> Repr<Slice<u8>> for &'a str {} -#[cfg(test)] -mod tests { - use super::*; - - use mem; - - #[test] - fn synthesize_closure() { - unsafe { - let x = 10; - let f: |int| -> int = |y| x + y; - - assert_eq!(f(20), 30); - - let original_closure: Closure = mem::transmute(f); - - let actual_function_pointer = original_closure.code; - let environment = original_closure.env; - - let new_closure = Closure { - code: actual_function_pointer, - env: environment - }; - - let new_f: |int| -> int = mem::transmute(new_closure); - assert_eq!(new_f(20), 30); - } - } -} diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 6c163b79199..5cbbf30cd36 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -585,20 +585,32 @@ impl<T: Show, E> Result<T, E> { /// ``` #[inline] pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> { - // FIXME(#11084): This should be twice as fast once this bug is closed. - let mut iter = iter.scan(None, |state, x| { - match x { - Ok(x) => Some(x), - Err(err) => { - *state = Some(err); - None + // FIXME(#11084): This could be replaced with Iterator::scan when this + // performance bug is closed. + + struct Adapter<Iter, E> { + iter: Iter, + err: Option<E>, + } + + impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> { + #[inline] + fn next(&mut self) -> Option<T> { + match self.iter.next() { + Some(Ok(value)) => Some(value), + Some(Err(err)) => { + self.err = Some(err); + None + } + None => None, } } - }); + } - let v: V = FromIterator::from_iter(iter.by_ref()); + let mut adapter = Adapter { iter: iter, err: None }; + let v: V = FromIterator::from_iter(adapter.by_ref()); - match iter.state { + match adapter.err { Some(err) => Err(err), None => Ok(v), } @@ -635,166 +647,3 @@ pub fn fold<T, pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> { fold(iterator, (), |_, _| ()) } - -///////////////////////////////////////////////////////////////////////////// -// Tests -///////////////////////////////////////////////////////////////////////////// - -#[cfg(test)] -mod tests { - use realstd::vec::Vec; - - use result::{collect, fold, fold_}; - use prelude::*; - use realstd::str::Str; - use iter::range; - - pub fn op1() -> Result<int, &'static str> { Ok(666) } - pub fn op2() -> Result<int, &'static str> { Err("sadface") } - - #[test] - pub fn test_and() { - assert_eq!(op1().and(Ok(667i)).unwrap(), 667); - assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), - "bad"); - - assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); - assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_and_then() { - assert_eq!(op1().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap(), 667); - assert_eq!(op1().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(), - "bad"); - - assert_eq!(op2().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap_err(), - "sadface"); - assert_eq!(op2().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_or() { - assert_eq!(op1().or(Ok(667)).unwrap(), 666); - assert_eq!(op1().or(Err("bad")).unwrap(), 666); - - assert_eq!(op2().or(Ok(667)).unwrap(), 667); - assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad"); - } - - #[test] - pub fn test_or_else() { - assert_eq!(op1().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 666); - assert_eq!(op1().or_else(|e| Err::<int, &'static str>(e)).unwrap(), 666); - - assert_eq!(op2().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 667); - assert_eq!(op2().or_else(|e| Err::<int, &'static str>(e)).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_impl_map() { - assert!(Ok::<int, int>(1).map(|x| x + 1) == Ok(2)); - assert!(Err::<int, int>(1).map(|x| x + 1) == Err(1)); - } - - #[test] - pub fn test_impl_map_err() { - assert!(Ok::<int, int>(1).map_err(|x| x + 1) == Ok(1)); - assert!(Err::<int, int>(1).map_err(|x| x + 1) == Err(2)); - } - - #[test] - fn test_collect() { - let v: Result<Vec<int>, ()> = collect(range(0i, 0).map(|_| Ok::<int, ()>(0))); - assert!(v == Ok(vec![])); - - let v: Result<Vec<int>, ()> = collect(range(0i, 3).map(|x| Ok::<int, ()>(x))); - assert!(v == Ok(vec![0, 1, 2])); - - let v: Result<Vec<int>, int> = collect(range(0i, 3) - .map(|x| if x > 1 { Err(x) } else { Ok(x) })); - assert!(v == Err(2)); - - // test that it does not take more elements than it needs - let mut functions = [|| Ok(()), || Err(1i), || fail!()]; - - let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)())); - assert!(v == Err(1)); - } - - #[test] - fn test_fold() { - assert_eq!(fold_(range(0i, 0) - .map(|_| Ok::<(), ()>(()))), - Ok(())); - assert_eq!(fold(range(0i, 3) - .map(|x| Ok::<int, ()>(x)), - 0, |a, b| a + b), - Ok(3)); - assert_eq!(fold_(range(0i, 3) - .map(|x| if x > 1 { Err(x) } else { Ok(()) })), - Err(2)); - - // test that it does not take more elements than it needs - let mut functions = [|| Ok(()), || Err(1i), || fail!()]; - - assert_eq!(fold_(functions.mut_iter() - .map(|f| (*f)())), - Err(1)); - } - - #[test] - pub fn test_fmt_default() { - let ok: Result<int, &'static str> = Ok(100); - let err: Result<int, &'static str> = Err("Err"); - - let s = format!("{}", ok); - assert_eq!(s.as_slice(), "Ok(100)"); - let s = format!("{}", err); - assert_eq!(s.as_slice(), "Err(Err)"); - } - - #[test] - pub fn test_unwrap_or() { - let ok: Result<int, &'static str> = Ok(100i); - let ok_err: Result<int, &'static str> = Err("Err"); - - assert_eq!(ok.unwrap_or(50), 100); - assert_eq!(ok_err.unwrap_or(50), 50); - } - - #[test] - pub fn test_unwrap_or_else() { - fn handler(msg: &'static str) -> int { - if msg == "I got this." { - 50i - } else { - fail!("BadBad") - } - } - - let ok: Result<int, &'static str> = Ok(100); - let ok_err: Result<int, &'static str> = Err("I got this."); - - assert_eq!(ok.unwrap_or_else(handler), 100); - assert_eq!(ok_err.unwrap_or_else(handler), 50); - } - - #[test] - #[should_fail] - pub fn test_unwrap_or_else_failure() { - fn handler(msg: &'static str) -> int { - if msg == "I got this." { - 50i - } else { - fail!("BadBad") - } - } - - let bad_err: Result<int, &'static str> = Err("Unrecoverable mess."); - let _ : int = bad_err.unwrap_or_else(handler); - } -} diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 14b5f7a6d60..0178c0318b8 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -14,10 +14,29 @@ #![doc(primitive = "slice")] +// How this module is organized. +// +// The library infrastructure for slices is fairly messy. There's +// a lot of stuff defined here. Let's keep it clean. +// +// Since slices don't support inherent methods; all operations +// on them are defined on traits, which are then reexported from +// the prelude for convenience. So there are a lot of traits here. +// +// The layout of this file is thus: +// +// * Slice-specific 'extension' traits and their implementations. This +// is where most of the slice API resides. +// * Implementations of a few common traits with important slice ops. +// * Definitions of a bunch of iterators. +// * Free functions. +// * The `raw` and `bytes` submodules. +// * Boilerplate trait implementations. + use mem::transmute; use clone::Clone; use collections::Collection; -use cmp::{PartialEq, Ord, Ordering, Less, Equal, Greater}; +use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Less, Equal, Greater, Equiv}; use cmp; use default::Default; use iter::*; @@ -30,295 +49,9 @@ use mem::size_of; use kinds::marker; use raw::{Repr, Slice}; -/** - * Converts a pointer to A into a slice of length 1 (without copying). - */ -pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] { - unsafe { - transmute(Slice { data: s, len: 1 }) - } -} - -/** - * Converts a pointer to A into a slice of length 1 (without copying). - */ -pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] { - unsafe { - let ptr: *A = transmute(s); - transmute(Slice { data: ptr, len: 1 }) - } -} - -/// An iterator over the slices of a vector separated by elements that -/// match a predicate function. -pub struct Splits<'a, T> { - v: &'a [T], - pred: |t: &T|: 'a -> bool, - finished: bool -} - -impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a [T]> { - if self.finished { return None; } - - match self.v.iter().position(|x| (self.pred)(x)) { - None => { - self.finished = true; - Some(self.v) - } - Some(idx) => { - let ret = Some(self.v.slice(0, idx)); - self.v = self.v.slice(idx + 1, self.v.len()); - ret - } - } - } - - #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - if self.finished { - (0, Some(0)) - } else { - (1, Some(self.v.len() + 1)) - } - } -} - -impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> { - #[inline] - fn next_back(&mut self) -> Option<&'a [T]> { - if self.finished { return None; } - - match self.v.iter().rposition(|x| (self.pred)(x)) { - None => { - self.finished = true; - Some(self.v) - } - Some(idx) => { - let ret = Some(self.v.slice(idx + 1, self.v.len())); - self.v = self.v.slice(0, idx); - ret - } - } - } -} - -/// An iterator over the slices of a vector separated by elements that -/// match a predicate function, splitting at most a fixed number of times. -pub struct SplitsN<'a, T> { - iter: Splits<'a, T>, - count: uint, - invert: bool -} - -impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a [T]> { - if self.count == 0 { - if self.iter.finished { - None - } else { - self.iter.finished = true; - Some(self.iter.v) - } - } else { - self.count -= 1; - if self.invert { self.iter.next_back() } else { self.iter.next() } - } - } - - #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - if self.iter.finished { - (0, Some(0)) - } else { - (1, Some(cmp::min(self.count, self.iter.v.len()) + 1)) - } - } -} - -// Functional utilities - -/// An iterator over the (overlapping) slices of length `size` within -/// a vector. -#[deriving(Clone)] -pub struct Windows<'a, T> { - v: &'a [T], - size: uint -} - -impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a [T]> { - if self.size > self.v.len() { - None - } else { - let ret = Some(self.v.slice(0, self.size)); - self.v = self.v.slice(1, self.v.len()); - ret - } - } - - #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - if self.size > self.v.len() { - (0, Some(0)) - } else { - let x = self.v.len() - self.size; - (x.saturating_add(1), x.checked_add(&1u)) - } - } -} - -/// An iterator over a vector in (non-overlapping) chunks (`size` -/// elements at a time). -/// -/// When the vector len is not evenly divided by the chunk size, -/// the last slice of the iteration will be the remainder. -#[deriving(Clone)] -pub struct Chunks<'a, T> { - v: &'a [T], - size: uint -} - -impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> { - #[inline] - fn next(&mut self) -> Option<&'a [T]> { - if self.v.len() == 0 { - None - } else { - let chunksz = cmp::min(self.v.len(), self.size); - let (fst, snd) = (self.v.slice_to(chunksz), - self.v.slice_from(chunksz)); - self.v = snd; - Some(fst) - } - } - - #[inline] - fn size_hint(&self) -> (uint, Option<uint>) { - if self.v.len() == 0 { - (0, Some(0)) - } else { - let (n, rem) = div_rem(self.v.len(), self.size); - let n = if rem > 0 { n+1 } else { n }; - (n, Some(n)) - } - } -} - -impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> { - #[inline] - fn next_back(&mut self) -> Option<&'a [T]> { - if self.v.len() == 0 { - None - } else { - let remainder = self.v.len() % self.size; - let chunksz = if remainder != 0 { remainder } else { self.size }; - let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz), - self.v.slice_from(self.v.len() - chunksz)); - self.v = fst; - Some(snd) - } - } -} - -impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> { - #[inline] - fn indexable(&self) -> uint { - self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 } - } - - #[inline] - fn idx(&mut self, index: uint) -> Option<&'a [T]> { - if index < self.indexable() { - let lo = index * self.size; - let mut hi = lo + self.size; - if hi < lo || hi > self.v.len() { hi = self.v.len(); } - - Some(self.v.slice(lo, hi)) - } else { - None - } - } -} - -// Equality - -#[cfg(not(test))] -#[allow(missing_doc)] -pub mod traits { - use super::*; - - use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Equiv}; - use iter::order; - use collections::Collection; - - impl<'a,T:PartialEq> PartialEq for &'a [T] { - fn eq(&self, other: & &'a [T]) -> bool { - self.len() == other.len() && - order::eq(self.iter(), other.iter()) - } - fn ne(&self, other: & &'a [T]) -> bool { - self.len() != other.len() || - order::ne(self.iter(), other.iter()) - } - } - - impl<'a,T:Eq> Eq for &'a [T] {} - - impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] { - #[inline] - fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } - } - - impl<'a,T:Ord> Ord for &'a [T] { - fn cmp(&self, other: & &'a [T]) -> Ordering { - order::cmp(self.iter(), other.iter()) - } - } - - impl<'a, T: PartialOrd> PartialOrd for &'a [T] { - fn lt(&self, other: & &'a [T]) -> bool { - order::lt(self.iter(), other.iter()) - } - #[inline] - fn le(&self, other: & &'a [T]) -> bool { - order::le(self.iter(), other.iter()) - } - #[inline] - fn ge(&self, other: & &'a [T]) -> bool { - order::ge(self.iter(), other.iter()) - } - #[inline] - fn gt(&self, other: & &'a [T]) -> bool { - order::gt(self.iter(), other.iter()) - } - } -} - -#[cfg(test)] -pub mod traits {} - -/// Any vector that can be represented as a slice. -pub trait Vector<T> { - /// Work with `self` as a slice. - fn as_slice<'a>(&'a self) -> &'a [T]; -} - -impl<'a,T> Vector<T> for &'a [T] { - #[inline(always)] - fn as_slice<'a>(&'a self) -> &'a [T] { *self } -} - -impl<'a, T> Collection for &'a [T] { - /// Returns the length of a vector - #[inline] - fn len(&self) -> uint { - self.repr().len - } -} +// +// Extension traits +// /// Extension methods for vectors pub trait ImmutableVector<'a, T> { @@ -439,7 +172,7 @@ pub trait ImmutableVector<'a, T> { * Modifying the vector may cause its buffer to be reallocated, which * would also make any pointers to it invalid. */ - fn as_ptr(&self) -> *T; + fn as_ptr(&self) -> *const T; /** * Binary search a sorted vector with a comparator function. @@ -520,7 +253,7 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] { let p = self.as_ptr(); if mem::size_of::<T>() == 0 { Items{ptr: p, - end: (p as uint + self.len()) as *T, + end: (p as uint + self.len()) as *const T, marker: marker::ContravariantLifetime::<'a>} } else { Items{ptr: p, @@ -606,7 +339,7 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] { } #[inline] - fn as_ptr(&self) -> *T { + fn as_ptr(&self) -> *const T { self.repr().data } @@ -651,69 +384,6 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] { } } -/// Extension methods for vectors contain `PartialEq` elements. -pub trait ImmutableEqVector<T:PartialEq> { - /// Find the first index containing a matching value - fn position_elem(&self, t: &T) -> Option<uint>; - - /// Find the last index containing a matching value - fn rposition_elem(&self, t: &T) -> Option<uint>; - - /// Return true if a vector contains an element with the given value - fn contains(&self, x: &T) -> bool; - - /// Returns true if `needle` is a prefix of the vector. - fn starts_with(&self, needle: &[T]) -> bool; - - /// Returns true if `needle` is a suffix of the vector. - fn ends_with(&self, needle: &[T]) -> bool; -} - -impl<'a,T:PartialEq> ImmutableEqVector<T> for &'a [T] { - #[inline] - fn position_elem(&self, x: &T) -> Option<uint> { - self.iter().position(|y| *x == *y) - } - - #[inline] - fn rposition_elem(&self, t: &T) -> Option<uint> { - self.iter().rposition(|x| *x == *t) - } - - #[inline] - fn contains(&self, x: &T) -> bool { - self.iter().any(|elt| *x == *elt) - } - - #[inline] - fn starts_with(&self, needle: &[T]) -> bool { - let n = needle.len(); - self.len() >= n && needle == self.slice_to(n) - } - - #[inline] - fn ends_with(&self, needle: &[T]) -> bool { - let (m, n) = (self.len(), needle.len()); - m >= n && needle == self.slice_from(m - n) - } -} - -/// Extension methods for vectors containing `Ord` elements. -pub trait ImmutableOrdVector<T: Ord> { - /** - * Binary search a sorted vector for a given element. - * - * Returns the index of the element or None if not found. - */ - fn bsearch_elem(&self, x: &T) -> Option<uint>; -} - -impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] { - fn bsearch_elem(&self, x: &T) -> Option<uint> { - self.bsearch(|p| p.cmp(x)) - } -} - /// Extension methods for vectors such that their elements are /// mutable. pub trait MutableVector<'a, T> { @@ -936,7 +606,7 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] { assert!(end <= self.len()); unsafe { transmute(Slice { - data: self.as_mut_ptr().offset(start as int) as *T, + data: self.as_mut_ptr().offset(start as int) as *const T, len: (end - start) }) } @@ -1069,6 +739,69 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] { } } +/// Extension methods for vectors contain `PartialEq` elements. +pub trait ImmutableEqVector<T:PartialEq> { + /// Find the first index containing a matching value + fn position_elem(&self, t: &T) -> Option<uint>; + + /// Find the last index containing a matching value + fn rposition_elem(&self, t: &T) -> Option<uint>; + + /// Return true if a vector contains an element with the given value + fn contains(&self, x: &T) -> bool; + + /// Returns true if `needle` is a prefix of the vector. + fn starts_with(&self, needle: &[T]) -> bool; + + /// Returns true if `needle` is a suffix of the vector. + fn ends_with(&self, needle: &[T]) -> bool; +} + +impl<'a,T:PartialEq> ImmutableEqVector<T> for &'a [T] { + #[inline] + fn position_elem(&self, x: &T) -> Option<uint> { + self.iter().position(|y| *x == *y) + } + + #[inline] + fn rposition_elem(&self, t: &T) -> Option<uint> { + self.iter().rposition(|x| *x == *t) + } + + #[inline] + fn contains(&self, x: &T) -> bool { + self.iter().any(|elt| *x == *elt) + } + + #[inline] + fn starts_with(&self, needle: &[T]) -> bool { + let n = needle.len(); + self.len() >= n && needle == self.slice_to(n) + } + + #[inline] + fn ends_with(&self, needle: &[T]) -> bool { + let (m, n) = (self.len(), needle.len()); + m >= n && needle == self.slice_from(m - n) + } +} + +/// Extension methods for vectors containing `Ord` elements. +pub trait ImmutableOrdVector<T: Ord> { + /** + * Binary search a sorted vector for a given element. + * + * Returns the index of the element or None if not found. + */ + fn bsearch_elem(&self, x: &T) -> Option<uint>; +} + +impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] { + fn bsearch_elem(&self, x: &T) -> Option<uint> { + self.bsearch(|p| p.cmp(x)) + } +} + /// Trait for &[T] where T is Cloneable pub trait MutableCloneableVector<T> { /// Copies as many elements from `src` as it can into `self` (the @@ -1103,117 +836,44 @@ impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] { } } -/// Unsafe operations -pub mod raw { - use mem::transmute; - use ptr::RawPtr; - use raw::Slice; - use option::{None, Option, Some}; - /** - * Form a slice from a pointer and length (as a number of units, - * not bytes). - */ - #[inline] - pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U) - -> U { - f(transmute(Slice { - data: p, - len: len - })) - } - /** - * Form a slice from a pointer and length (as a number of units, - * not bytes). - */ - #[inline] - pub unsafe fn mut_buf_as_slice<T, - U>( - p: *mut T, - len: uint, - f: |v: &mut [T]| -> U) - -> U { - f(transmute(Slice { - data: p as *T, - len: len - })) - } - /** - * Returns a pointer to first element in slice and adjusts - * slice so it no longer contains that element. Returns None - * if the slice is empty. O(1). - */ - #[inline] - pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*T> { - if slice.len == 0 { return None; } - let head: *T = slice.data; - slice.data = slice.data.offset(1); - slice.len -= 1; - Some(head) - } +// +// Common traits +// - /** - * Returns a pointer to last element in slice and adjusts - * slice so it no longer contains that element. Returns None - * if the slice is empty. O(1). - */ - #[inline] - pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*T> { - if slice.len == 0 { return None; } - let tail: *T = slice.data.offset((slice.len - 1) as int); - slice.len -= 1; - Some(tail) - } +/// Any vector that can be represented as a slice. +pub trait Vector<T> { + /// Work with `self` as a slice. + fn as_slice<'a>(&'a self) -> &'a [T]; } -/// Operations on `[u8]`. -pub mod bytes { - use collections::Collection; - use ptr; - use slice::MutableVector; - - /// A trait for operations on mutable `[u8]`s. - pub trait MutableByteVector { - /// Sets all bytes of the receiver to the given value. - fn set_memory(self, value: u8); - } - - impl<'a> MutableByteVector for &'a mut [u8] { - #[inline] - #[allow(experimental)] - fn set_memory(self, value: u8) { - unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) }; - } - } +impl<'a,T> Vector<T> for &'a [T] { + #[inline(always)] + fn as_slice<'a>(&'a self) -> &'a [T] { *self } +} - /// Copies data from `src` to `dst` - /// - /// `src` and `dst` must not overlap. Fails if the length of `dst` - /// is less than the length of `src`. +impl<'a, T> Collection for &'a [T] { + /// Returns the length of a vector #[inline] - pub fn copy_memory(dst: &mut [u8], src: &[u8]) { - // Bound checks are done at .copy_memory. - unsafe { dst.copy_memory(src) } + fn len(&self) -> uint { + self.repr().len } } -/// Immutable slice iterator -pub struct Items<'a, T> { - ptr: *T, - end: *T, - marker: marker::ContravariantLifetime<'a> +impl<'a, T> Default for &'a [T] { + fn default() -> &'a [T] { &[] } } -/// Mutable slice iterator -pub struct MutItems<'a, T> { - ptr: *mut T, - end: *mut T, - marker: marker::ContravariantLifetime<'a>, - marker2: marker::NoCopy -} + + +// +// Iterators +// + +// The shared definition of the `Item` and `MutItems` iterators macro_rules! iterator { (struct $name:ident -> $ptr:ty, $elem:ty) => { impl<'a, T> Iterator<$elem> for $name<'a, T> { @@ -1270,6 +930,21 @@ macro_rules! iterator { } } +/// Immutable slice iterator +pub struct Items<'a, T> { + ptr: *const T, + end: *const T, + marker: marker::ContravariantLifetime<'a> +} + +iterator!{struct Items -> *const T, &'a T} + +impl<'a, T> ExactSize<&'a T> for Items<'a, T> {} + +impl<'a, T> Clone for Items<'a, T> { + fn clone(&self) -> Items<'a, T> { *self } +} + impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> { #[inline] fn indexable(&self) -> uint { @@ -1289,16 +964,72 @@ impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> { } } -iterator!{struct Items -> *T, &'a T} +/// Mutable slice iterator +pub struct MutItems<'a, T> { + ptr: *mut T, + end: *mut T, + marker: marker::ContravariantLifetime<'a>, + marker2: marker::NoCopy +} + +iterator!{struct MutItems -> *mut T, &'a mut T} -impl<'a, T> ExactSize<&'a T> for Items<'a, T> {} impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {} -impl<'a, T> Clone for Items<'a, T> { - fn clone(&self) -> Items<'a, T> { *self } +/// An iterator over the slices of a vector separated by elements that +/// match a predicate function. +pub struct Splits<'a, T> { + v: &'a [T], + pred: |t: &T|: 'a -> bool, + finished: bool } -iterator!{struct MutItems -> *mut T, &'a mut T} +impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a [T]> { + if self.finished { return None; } + + match self.v.iter().position(|x| (self.pred)(x)) { + None => { + self.finished = true; + Some(self.v) + } + Some(idx) => { + let ret = Some(self.v.slice(0, idx)); + self.v = self.v.slice(idx + 1, self.v.len()); + ret + } + } + } + + #[inline] + fn size_hint(&self) -> (uint, Option<uint>) { + if self.finished { + (0, Some(0)) + } else { + (1, Some(self.v.len() + 1)) + } + } +} + +impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> { + #[inline] + fn next_back(&mut self) -> Option<&'a [T]> { + if self.finished { return None; } + + match self.v.iter().rposition(|x| (self.pred)(x)) { + None => { + self.finished = true; + Some(self.v) + } + Some(idx) => { + let ret = Some(self.v.slice(idx + 1, self.v.len())); + self.v = self.v.slice(0, idx); + ret + } + } + } +} /// An iterator over the subslices of the vector which are separated /// by elements that match `pred`. @@ -1366,6 +1097,144 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> { } } +/// An iterator over the slices of a vector separated by elements that +/// match a predicate function, splitting at most a fixed number of times. +pub struct SplitsN<'a, T> { + iter: Splits<'a, T>, + count: uint, + invert: bool +} + +impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a [T]> { + if self.count == 0 { + if self.iter.finished { + None + } else { + self.iter.finished = true; + Some(self.iter.v) + } + } else { + self.count -= 1; + if self.invert { self.iter.next_back() } else { self.iter.next() } + } + } + + #[inline] + fn size_hint(&self) -> (uint, Option<uint>) { + if self.iter.finished { + (0, Some(0)) + } else { + (1, Some(cmp::min(self.count, self.iter.v.len()) + 1)) + } + } +} + +/// An iterator over the (overlapping) slices of length `size` within +/// a vector. +#[deriving(Clone)] +pub struct Windows<'a, T> { + v: &'a [T], + size: uint +} + +impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a [T]> { + if self.size > self.v.len() { + None + } else { + let ret = Some(self.v.slice(0, self.size)); + self.v = self.v.slice(1, self.v.len()); + ret + } + } + + #[inline] + fn size_hint(&self) -> (uint, Option<uint>) { + if self.size > self.v.len() { + (0, Some(0)) + } else { + let x = self.v.len() - self.size; + (x.saturating_add(1), x.checked_add(&1u)) + } + } +} + +/// An iterator over a vector in (non-overlapping) chunks (`size` +/// elements at a time). +/// +/// When the vector len is not evenly divided by the chunk size, +/// the last slice of the iteration will be the remainder. +#[deriving(Clone)] +pub struct Chunks<'a, T> { + v: &'a [T], + size: uint +} + +impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> { + #[inline] + fn next(&mut self) -> Option<&'a [T]> { + if self.v.len() == 0 { + None + } else { + let chunksz = cmp::min(self.v.len(), self.size); + let (fst, snd) = (self.v.slice_to(chunksz), + self.v.slice_from(chunksz)); + self.v = snd; + Some(fst) + } + } + + #[inline] + fn size_hint(&self) -> (uint, Option<uint>) { + if self.v.len() == 0 { + (0, Some(0)) + } else { + let (n, rem) = div_rem(self.v.len(), self.size); + let n = if rem > 0 { n+1 } else { n }; + (n, Some(n)) + } + } +} + +impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> { + #[inline] + fn next_back(&mut self) -> Option<&'a [T]> { + if self.v.len() == 0 { + None + } else { + let remainder = self.v.len() % self.size; + let chunksz = if remainder != 0 { remainder } else { self.size }; + let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz), + self.v.slice_from(self.v.len() - chunksz)); + self.v = fst; + Some(snd) + } + } +} + +impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> { + #[inline] + fn indexable(&self) -> uint { + self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 } + } + + #[inline] + fn idx(&mut self, index: uint) -> Option<&'a [T]> { + if index < self.indexable() { + let lo = index * self.size; + let mut hi = lo + self.size; + if hi < lo || hi > self.v.len() { hi = self.v.len(); } + + Some(self.v.slice(lo, hi)) + } else { + None + } + } +} + /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be /// the remainder. @@ -1417,6 +1286,185 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> { } } -impl<'a, T> Default for &'a [T] { - fn default() -> &'a [T] { &[] } + + + +// +// Free functions +// + +/** + * Converts a pointer to A into a slice of length 1 (without copying). + */ +pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] { + unsafe { + transmute(Slice { data: s, len: 1 }) + } +} + +/** + * Converts a pointer to A into a slice of length 1 (without copying). + */ +pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] { + unsafe { + let ptr: *const A = transmute(s); + transmute(Slice { data: ptr, len: 1 }) + } +} + + + + +// +// Submodules +// + +/// Unsafe operations +pub mod raw { + use mem::transmute; + use ptr::RawPtr; + use raw::Slice; + use option::{None, Option, Some}; + + /** + * Form a slice from a pointer and length (as a number of units, + * not bytes). + */ + #[inline] + pub unsafe fn buf_as_slice<T,U>(p: *const T, len: uint, f: |v: &[T]| -> U) + -> U { + f(transmute(Slice { + data: p, + len: len + })) + } + + /** + * Form a slice from a pointer and length (as a number of units, + * not bytes). + */ + #[inline] + pub unsafe fn mut_buf_as_slice<T, + U>( + p: *mut T, + len: uint, + f: |v: &mut [T]| -> U) + -> U { + f(transmute(Slice { + data: p as *const T, + len: len + })) + } + + /** + * Returns a pointer to first element in slice and adjusts + * slice so it no longer contains that element. Returns None + * if the slice is empty. O(1). + */ + #[inline] + pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> { + if slice.len == 0 { return None; } + let head: *const T = slice.data; + slice.data = slice.data.offset(1); + slice.len -= 1; + Some(head) + } + + /** + * Returns a pointer to last element in slice and adjusts + * slice so it no longer contains that element. Returns None + * if the slice is empty. O(1). + */ + #[inline] + pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> { + if slice.len == 0 { return None; } + let tail: *const T = slice.data.offset((slice.len - 1) as int); + slice.len -= 1; + Some(tail) + } +} + +/// Operations on `[u8]`. +pub mod bytes { + use collections::Collection; + use ptr; + use slice::MutableVector; + + /// A trait for operations on mutable `[u8]`s. + pub trait MutableByteVector { + /// Sets all bytes of the receiver to the given value. + fn set_memory(self, value: u8); + } + + impl<'a> MutableByteVector for &'a mut [u8] { + #[inline] + #[allow(experimental)] + fn set_memory(self, value: u8) { + unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) }; + } + } + + /// Copies data from `src` to `dst` + /// + /// `src` and `dst` must not overlap. Fails if the length of `dst` + /// is less than the length of `src`. + #[inline] + pub fn copy_memory(dst: &mut [u8], src: &[u8]) { + // Bound checks are done at .copy_memory. + unsafe { dst.copy_memory(src) } + } +} + + + + +// +// Boilerplate traits +// + +impl<'a,T:PartialEq> PartialEq for &'a [T] { + fn eq(&self, other: & &'a [T]) -> bool { + self.len() == other.len() && + order::eq(self.iter(), other.iter()) + } + fn ne(&self, other: & &'a [T]) -> bool { + self.len() != other.len() || + order::ne(self.iter(), other.iter()) + } +} + +impl<'a,T:Eq> Eq for &'a [T] {} + +impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] { + #[inline] + fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } +} + +impl<'a,T:Ord> Ord for &'a [T] { + fn cmp(&self, other: & &'a [T]) -> Ordering { + order::cmp(self.iter(), other.iter()) + } +} + +impl<'a, T: PartialOrd> PartialOrd for &'a [T] { + #[inline] + fn partial_cmp(&self, other: &&'a [T]) -> Option<Ordering> { + order::partial_cmp(self.iter(), other.iter()) + } + #[inline] + fn lt(&self, other: & &'a [T]) -> bool { + order::lt(self.iter(), other.iter()) + } + #[inline] + fn le(&self, other: & &'a [T]) -> bool { + order::le(self.iter(), other.iter()) + } + #[inline] + fn ge(&self, other: & &'a [T]) -> bool { + order::ge(self.iter(), other.iter()) + } + #[inline] + fn gt(&self, other: & &'a [T]) -> bool { + order::gt(self.iter(), other.iter()) + } } diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 13efeab57d4..94df7a5a6c2 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -16,6 +16,7 @@ use mem; use char; +use char::Char; use clone::Clone; use cmp; use cmp::{PartialEq, Eq}; @@ -24,7 +25,7 @@ use default::Default; use iter::{Filter, Map, Iterator}; use iter::{DoubleEndedIterator, ExactSize}; use iter::range; -use num::Saturating; +use num::{CheckedMul, Saturating}; use option::{None, Option, Some}; use raw::Repr; use slice::ImmutableVector; @@ -557,6 +558,41 @@ impl<'a> Iterator<&'a str> for StrSplits<'a> { } } +/// External iterator for a string's UTF16 codeunits. +/// Use with the `std::iter` module. +#[deriving(Clone)] +pub struct Utf16CodeUnits<'a> { + chars: Chars<'a>, + extra: u16 +} + +impl<'a> Iterator<u16> for Utf16CodeUnits<'a> { + #[inline] + fn next(&mut self) -> Option<u16> { + if self.extra != 0 { + let tmp = self.extra; + self.extra = 0; + return Some(tmp); + } + + let mut buf = [0u16, ..2]; + self.chars.next().map(|ch| { + let n = ch.encode_utf16(buf /* as mut slice! */); + if n == 2 { self.extra = buf[1]; } + buf[0] + }) + } + + #[inline] + fn size_hint(&self) -> (uint, Option<uint>) { + let (low, high) = self.chars.size_hint(); + // every char gets either one u16 or two u16, + // so this iterator is between 1 or 2 times as + // long as the underlying iterator. + (low, high.and_then(|n| n.checked_mul(&2))) + } +} + /* Section: Comparing strings */ @@ -568,10 +604,10 @@ Section: Comparing strings #[inline] fn eq_slice_(a: &str, b: &str) -> bool { #[allow(ctypes)] - extern { fn memcmp(s1: *i8, s2: *i8, n: uint) -> i32; } + extern { fn memcmp(s1: *const i8, s2: *const i8, n: uint) -> i32; } a.len() == b.len() && unsafe { - memcmp(a.as_ptr() as *i8, - b.as_ptr() as *i8, + memcmp(a.as_ptr() as *const i8, + b.as_ptr() as *const i8, a.len()) == 0 } } @@ -579,20 +615,12 @@ fn eq_slice_(a: &str, b: &str) -> bool { /// Bytewise slice equality /// NOTE: This function is (ab)used in rustc::middle::trans::_match /// to compare &[u8] byte slices that are not necessarily valid UTF-8. -#[cfg(not(test))] #[lang="str_eq"] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { eq_slice_(a, b) } -/// Bytewise slice equality -#[cfg(test)] -#[inline] -pub fn eq_slice(a: &str, b: &str) -> bool { - eq_slice_(a, b) -} - /* Section: Misc */ @@ -888,8 +916,8 @@ pub mod raw { /// Form a slice from a C string. Unsafe because the caller must ensure the /// C string has the static lifetime, or else the return value may be /// invalidated later. - pub unsafe fn c_str_to_static_slice(s: *i8) -> &'static str { - let s = s as *u8; + pub unsafe fn c_str_to_static_slice(s: *const i8) -> &'static str { + let s = s as *const u8; let mut curr = s; let mut len = 0u; while *curr != 0u8 { @@ -934,13 +962,12 @@ pub mod raw { Section: Trait implementations */ -#[cfg(not(test))] #[allow(missing_doc)] pub mod traits { use cmp::{Ord, Ordering, Less, Equal, Greater, PartialEq, PartialOrd, Equiv, Eq}; use collections::Collection; use iter::Iterator; - use option::{Some, None}; + use option::{Option, Some, None}; use str::{Str, StrSlice, eq_slice}; impl<'a> Ord for &'a str { @@ -971,7 +998,9 @@ pub mod traits { impl<'a> PartialOrd for &'a str { #[inline] - fn lt(&self, other: & &'a str) -> bool { self.cmp(other) == Less } + fn partial_cmp(&self, other: &&'a str) -> Option<Ordering> { + Some(self.cmp(other)) + } } impl<'a, S: Str> Equiv<S> for &'a str { @@ -980,9 +1009,6 @@ pub mod traits { } } -#[cfg(test)] -pub mod traits {} - /// Any string that can be represented as a slice pub trait Str { /// Work with `self` as a slice. @@ -1618,7 +1644,10 @@ pub trait StrSlice<'a> { /// The caller must ensure that the string outlives this pointer, /// and that it is not reallocated (e.g. by pushing to the /// string). - fn as_ptr(&self) -> *u8; + fn as_ptr(&self) -> *const u8; + + /// Return an iterator of `u16` over the string encoded as UTF-16. + fn utf16_units(&self) -> Utf16CodeUnits<'a>; } impl<'a> StrSlice<'a> for &'a str { @@ -1714,7 +1743,7 @@ impl<'a> StrSlice<'a> for &'a str { fn lines_any(&self) -> AnyLines<'a> { self.lines().map(|line| { let l = line.len(); - if l > 0 && line[l - 1] == '\r' as u8 { line.slice(0, l - 1) } + if l > 0 && line.as_bytes()[l - 1] == '\r' as u8 { line.slice(0, l - 1) } else { line } }) } @@ -1838,26 +1867,26 @@ impl<'a> StrSlice<'a> for &'a str { fn is_char_boundary(&self, index: uint) -> bool { if index == self.len() { return true; } if index > self.len() { return false; } - let b = self[index]; + let b = self.as_bytes()[index]; return b < 128u8 || b >= 192u8; } #[inline] fn char_range_at(&self, i: uint) -> CharRange { - if self[i] < 128u8 { - return CharRange {ch: self[i] as char, next: i + 1 }; + if self.as_bytes()[i] < 128u8 { + return CharRange {ch: self.as_bytes()[i] as char, next: i + 1 }; } // Multibyte case is a fn to allow char_range_at to inline cleanly fn multibyte_char_range_at(s: &str, i: uint) -> CharRange { - let mut val = s[i] as u32; + let mut val = s.as_bytes()[i] as u32; let w = UTF8_CHAR_WIDTH[val as uint] as uint; assert!((w != 0)); val = utf8_first_byte!(val, w); - val = utf8_acc_cont_byte!(val, s[i + 1]); - if w > 2 { val = utf8_acc_cont_byte!(val, s[i + 2]); } - if w > 3 { val = utf8_acc_cont_byte!(val, s[i + 3]); } + val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]); + if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); } + if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); } return CharRange {ch: unsafe { mem::transmute(val) }, next: i + w}; } @@ -1870,23 +1899,25 @@ impl<'a> StrSlice<'a> for &'a str { let mut prev = start; prev = prev.saturating_sub(1); - if self[prev] < 128 { return CharRange{ch: self[prev] as char, next: prev} } + if self.as_bytes()[prev] < 128 { + return CharRange{ch: self.as_bytes()[prev] as char, next: prev} + } // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly fn multibyte_char_range_at_reverse(s: &str, mut i: uint) -> CharRange { // while there is a previous byte == 10...... - while i > 0 && s[i] & 192u8 == TAG_CONT_U8 { + while i > 0 && s.as_bytes()[i] & 192u8 == TAG_CONT_U8 { i -= 1u; } - let mut val = s[i] as u32; + let mut val = s.as_bytes()[i] as u32; let w = UTF8_CHAR_WIDTH[val as uint] as uint; assert!((w != 0)); val = utf8_first_byte!(val, w); - val = utf8_acc_cont_byte!(val, s[i + 1]); - if w > 2 { val = utf8_acc_cont_byte!(val, s[i + 2]); } - if w > 3 { val = utf8_acc_cont_byte!(val, s[i + 3]); } + val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 1]); + if w > 2 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 2]); } + if w > 3 { val = utf8_acc_cont_byte!(val, s.as_bytes()[i + 3]); } return CharRange {ch: unsafe { mem::transmute(val) }, next: i}; } @@ -1964,9 +1995,14 @@ impl<'a> StrSlice<'a> for &'a str { } #[inline] - fn as_ptr(&self) -> *u8 { + fn as_ptr(&self) -> *const u8 { self.repr().data } + + #[inline] + fn utf16_units(&self) -> Utf16CodeUnits<'a> { + Utf16CodeUnits{ chars: self.chars(), extra: 0} + } } impl<'a> Default for &'a str { diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 3508da5d516..0e3722894bc 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -62,8 +62,9 @@ #![doc(primitive = "tuple")] use clone::Clone; -#[cfg(not(test))] use cmp::*; -#[cfg(not(test))] use default::Default; +use cmp::*; +use default::Default; +use option::{Option, Some}; // macro for implementing n-ary tuple functions and operations macro_rules! tuple_impls { @@ -111,7 +112,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:PartialEq),+> PartialEq for ($($T,)+) { #[inline] fn eq(&self, other: &($($T,)+)) -> bool { @@ -123,12 +123,14 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Eq),+> Eq for ($($T,)+) {} - #[cfg(not(test))] impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+) { #[inline] + fn partial_cmp(&self, other: &($($T,)+)) -> Option<Ordering> { + lexical_partial_cmp!($(self.$refN(), other.$refN()),+) + } + #[inline] fn lt(&self, other: &($($T,)+)) -> bool { lexical_ord!(lt, $(self.$refN(), other.$refN()),+) } @@ -146,7 +148,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Ord),+> Ord for ($($T,)+) { #[inline] fn cmp(&self, other: &($($T,)+)) -> Ordering { @@ -154,7 +155,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Default),+> Default for ($($T,)+) { #[inline] fn default() -> ($($T,)+) { @@ -177,6 +177,16 @@ macro_rules! lexical_ord { ($rel: ident, $a:expr, $b:expr) => { (*$a) . $rel ($b) }; } +macro_rules! lexical_partial_cmp { + ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => { + match ($a).partial_cmp($b) { + Some(Equal) => lexical_partial_cmp!($($rest_a, $rest_b),+), + ordering => ordering + } + }; + ($a:expr, $b:expr) => { ($a).partial_cmp($b) }; +} + macro_rules! lexical_cmp { ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => { match ($a).cmp($b) { @@ -292,93 +302,3 @@ tuple_impls! { } } -#[cfg(test)] -mod tests { - use super::*; - use clone::Clone; - use cmp::*; - use realstd::str::Str; - - #[test] - fn test_clone() { - let a = (1i, "2"); - let b = a.clone(); - assert_eq!(a, b); - } - - #[test] - fn test_getters() { - macro_rules! test_getter( - ($x:expr, $valN:ident, $refN:ident, $mutN:ident, - $init:expr, $incr:expr, $result:expr) => ({ - assert_eq!($x.$valN(), $init); - assert_eq!(*$x.$refN(), $init); - *$x.$mutN() += $incr; - assert_eq!(*$x.$refN(), $result); - }) - ) - let mut x = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - test_getter!(x, val0, ref0, mut0, 0, 1, 1); - test_getter!(x, val1, ref1, mut1, 1, 1, 2); - test_getter!(x, val2, ref2, mut2, 2, 1, 3); - test_getter!(x, val3, ref3, mut3, 3, 1, 4); - test_getter!(x, val4, ref4, mut4, 4, 1, 5); - test_getter!(x, val5, ref5, mut5, 5, 1, 6); - test_getter!(x, val6, ref6, mut6, 6, 1, 7); - test_getter!(x, val7, ref7, mut7, 7, 1, 8); - test_getter!(x, val8, ref8, mut8, 8, 1, 9); - test_getter!(x, val9, ref9, mut9, 9, 1, 10); - test_getter!(x, val10, ref10, mut10, 10.0, 1.0, 11.0); - test_getter!(x, val11, ref11, mut11, 11.0, 1.0, 12.0); - } - - #[test] - fn test_tuple_cmp() { - let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u)); - - let nan = 0.0f64/0.0; - - // PartialEq - assert_eq!(small, small); - assert_eq!(big, big); - assert!(small != big); - assert!(big != small); - - // PartialOrd - assert!(small < big); - assert!(!(small < small)); - assert!(!(big < small)); - assert!(!(big < big)); - - assert!(small <= small); - assert!(big <= big); - - assert!(big > small); - assert!(small >= small); - assert!(big >= small); - assert!(big >= big); - - assert!(!((1.0f64, 2.0f64) < (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) <= (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) > (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) >= (nan, 3.0))); - assert!(((1.0f64, 2.0f64) < (2.0, nan))); - assert!(!((2.0f64, 2.0f64) < (2.0, nan))); - - // Ord - assert!(small.cmp(&small) == Equal); - assert!(big.cmp(&big) == Equal); - assert!(small.cmp(&big) == Less); - assert!(big.cmp(&small) == Greater); - } - - #[test] - fn test_show() { - let s = format!("{}", (1i,)); - assert_eq!(s.as_slice(), "(1,)"); - let s = format!("{}", (1i, true)); - assert_eq!(s.as_slice(), "(1, true)"); - let s = format!("{}", (1i, "hi", true)); - assert_eq!(s.as_slice(), "(1, hi, true)"); - } -} diff --git a/src/libcore/ty.rs b/src/libcore/ty.rs index 47a2005fef1..5bdab6a78ca 100644 --- a/src/libcore/ty.rs +++ b/src/libcore/ty.rs @@ -62,7 +62,7 @@ impl<T> Unsafe<T> { /// Gets a mutable pointer to the wrapped value #[inline] - pub unsafe fn get(&self) -> *mut T { &self.value as *T as *mut T } + pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value #[inline] diff --git a/src/libcoretest/any.rs b/src/libcoretest/any.rs new file mode 100644 index 00000000000..fae4a26cd38 --- /dev/null +++ b/src/libcoretest/any.rs @@ -0,0 +1,131 @@ +// 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. +use core::any::*; +use test::Bencher; +use test; + +#[deriving(PartialEq, Show)] +struct Test; + +static TEST: &'static str = "Test"; + +#[test] +fn any_referenced() { + let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any); + + assert!(a.is::<uint>()); + assert!(!b.is::<uint>()); + assert!(!c.is::<uint>()); + + assert!(!a.is::<&'static str>()); + assert!(b.is::<&'static str>()); + assert!(!c.is::<&'static str>()); + + assert!(!a.is::<Test>()); + assert!(!b.is::<Test>()); + assert!(c.is::<Test>()); +} + +#[test] +fn any_owning() { + let (a, b, c) = (box 5u as Box<Any>, box TEST as Box<Any>, box Test as Box<Any>); + + assert!(a.is::<uint>()); + assert!(!b.is::<uint>()); + assert!(!c.is::<uint>()); + + assert!(!a.is::<&'static str>()); + assert!(b.is::<&'static str>()); + assert!(!c.is::<&'static str>()); + + assert!(!a.is::<Test>()); + assert!(!b.is::<Test>()); + assert!(c.is::<Test>()); +} + +#[test] +fn any_as_ref() { + let a = &5u as &Any; + + match a.as_ref::<uint>() { + Some(&5) => {} + x => fail!("Unexpected value {}", x) + } + + match a.as_ref::<Test>() { + None => {} + x => fail!("Unexpected value {}", x) + } +} + +#[test] +fn any_as_mut() { + let mut a = 5u; + let mut b = box 7u; + + let a_r = &mut a as &mut Any; + let tmp: &mut uint = &mut *b; + let b_r = tmp as &mut Any; + + match a_r.as_mut::<uint>() { + Some(x) => { + assert_eq!(*x, 5u); + *x = 612; + } + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::<uint>() { + Some(x) => { + assert_eq!(*x, 7u); + *x = 413; + } + x => fail!("Unexpected value {}", x) + } + + match a_r.as_mut::<Test>() { + None => (), + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::<Test>() { + None => (), + x => fail!("Unexpected value {}", x) + } + + match a_r.as_mut::<uint>() { + Some(&612) => {} + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::<uint>() { + Some(&413) => {} + x => fail!("Unexpected value {}", x) + } +} + +#[test] +fn any_fixed_vec() { + let test = [0u, ..8]; + let test = &test as &Any; + assert!(test.is::<[uint, ..8]>()); + assert!(!test.is::<[uint, ..10]>()); +} + + +#[bench] +fn bench_as_ref(b: &mut Bencher) { + b.iter(|| { + let mut x = 0i; + let mut y = &mut x as &mut Any; + test::black_box(&mut y); + test::black_box(y.as_ref::<int>() == Some(&0)); + }); +} diff --git a/src/libcoretest/atomics.rs b/src/libcoretest/atomics.rs new file mode 100644 index 00000000000..3f960ae1f26 --- /dev/null +++ b/src/libcoretest/atomics.rs @@ -0,0 +1,83 @@ +// 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. + +use core::atomics::*; + +#[test] +fn bool_() { + let a = AtomicBool::new(false); + assert_eq!(a.compare_and_swap(false, true, SeqCst), false); + assert_eq!(a.compare_and_swap(false, true, SeqCst), true); + + a.store(false, SeqCst); + assert_eq!(a.compare_and_swap(false, true, SeqCst), false); +} + +#[test] +fn bool_and() { + let a = AtomicBool::new(true); + assert_eq!(a.fetch_and(false, SeqCst),true); + assert_eq!(a.load(SeqCst),false); +} + +#[test] +fn uint_and() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); +} + +#[test] +fn uint_or() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); +} + +#[test] +fn uint_xor() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); +} + +#[test] +fn int_and() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); +} + +#[test] +fn int_or() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); +} + +#[test] +fn int_xor() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); +} + +static mut S_BOOL : AtomicBool = INIT_ATOMIC_BOOL; +static mut S_INT : AtomicInt = INIT_ATOMIC_INT; +static mut S_UINT : AtomicUint = INIT_ATOMIC_UINT; + +#[test] +fn static_init() { + unsafe { + assert!(!S_BOOL.load(SeqCst)); + assert!(S_INT.load(SeqCst) == 0); + assert!(S_UINT.load(SeqCst) == 0); + } +} diff --git a/src/libcoretest/cell.rs b/src/libcoretest/cell.rs new file mode 100644 index 00000000000..b3ae110363c --- /dev/null +++ b/src/libcoretest/cell.rs @@ -0,0 +1,129 @@ +// 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. + +use core::cell::*; +use std::mem::drop; + +#[test] +fn smoketest_cell() { + let x = Cell::new(10i); + assert!(x == Cell::new(10)); + assert!(x.get() == 10); + x.set(20); + assert!(x == Cell::new(20)); + assert!(x.get() == 20); + + let y = Cell::new((30i, 40i)); + assert!(y == Cell::new((30, 40))); + assert!(y.get() == (30, 40)); +} + +#[test] +fn cell_has_sensible_show() { + let x = Cell::new("foo bar"); + assert!(format!("{}", x).as_slice().contains(x.get())); + + x.set("baz qux"); + assert!(format!("{}", x).as_slice().contains(x.get())); +} + +#[test] +fn ref_and_refmut_have_sensible_show() { + let refcell = RefCell::new("foo"); + + let refcell_refmut = refcell.borrow_mut(); + assert!(format!("{}", refcell_refmut).as_slice().contains("foo")); + drop(refcell_refmut); + + let refcell_ref = refcell.borrow(); + assert!(format!("{}", refcell_ref).as_slice().contains("foo")); + drop(refcell_ref); +} + +#[test] +fn double_imm_borrow() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + x.borrow(); +} + +#[test] +fn no_mut_then_imm_borrow() { + let x = RefCell::new(0i); + let _b1 = x.borrow_mut(); + assert!(x.try_borrow().is_none()); +} + +#[test] +fn no_imm_then_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +fn no_double_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow_mut(); + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +fn imm_release_borrow_mut() { + let x = RefCell::new(0i); + { + let _b1 = x.borrow(); + } + x.borrow_mut(); +} + +#[test] +fn mut_release_borrow_mut() { + let x = RefCell::new(0i); + { + let _b1 = x.borrow_mut(); + } + x.borrow(); +} + +#[test] +fn double_borrow_single_release_no_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + { + let _b2 = x.borrow(); + } + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +#[should_fail] +fn discard_doesnt_unborrow() { + let x = RefCell::new(0i); + let _b = x.borrow(); + let _ = _b; + let _b = x.borrow_mut(); +} + +#[test] +#[allow(experimental)] +fn clone_ref_updates_flag() { + let x = RefCell::new(0i); + { + let b1 = x.borrow(); + assert!(x.try_borrow_mut().is_none()); + { + let _b2 = clone_ref(&b1); + assert!(x.try_borrow_mut().is_none()); + } + assert!(x.try_borrow_mut().is_none()); + } + assert!(x.try_borrow_mut().is_some()); +} diff --git a/src/libcoretest/char.rs b/src/libcoretest/char.rs new file mode 100644 index 00000000000..852edd90b0f --- /dev/null +++ b/src/libcoretest/char.rs @@ -0,0 +1,202 @@ +// 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. + +use core::char::{escape_unicode, escape_default}; + +#[test] +fn test_is_lowercase() { + assert!('a'.is_lowercase()); + assert!('ö'.is_lowercase()); + assert!('ß'.is_lowercase()); + assert!(!'Ü'.is_lowercase()); + assert!(!'P'.is_lowercase()); +} + +#[test] +fn test_is_uppercase() { + assert!(!'h'.is_uppercase()); + assert!(!'ä'.is_uppercase()); + assert!(!'ß'.is_uppercase()); + assert!('Ö'.is_uppercase()); + assert!('T'.is_uppercase()); +} + +#[test] +fn test_is_whitespace() { + assert!(' '.is_whitespace()); + assert!('\u2007'.is_whitespace()); + assert!('\t'.is_whitespace()); + assert!('\n'.is_whitespace()); + assert!(!'a'.is_whitespace()); + assert!(!'_'.is_whitespace()); + assert!(!'\u0000'.is_whitespace()); +} + +#[test] +fn test_to_digit() { + assert_eq!('0'.to_digit(10u), Some(0u)); + assert_eq!('1'.to_digit(2u), Some(1u)); + assert_eq!('2'.to_digit(3u), Some(2u)); + assert_eq!('9'.to_digit(10u), Some(9u)); + assert_eq!('a'.to_digit(16u), Some(10u)); + assert_eq!('A'.to_digit(16u), Some(10u)); + assert_eq!('b'.to_digit(16u), Some(11u)); + assert_eq!('B'.to_digit(16u), Some(11u)); + assert_eq!('z'.to_digit(36u), Some(35u)); + assert_eq!('Z'.to_digit(36u), Some(35u)); + assert_eq!(' '.to_digit(10u), None); + assert_eq!('$'.to_digit(36u), None); +} + +#[test] +fn test_to_lowercase() { + assert_eq!('A'.to_lowercase(), 'a'); + assert_eq!('Ö'.to_lowercase(), 'ö'); + assert_eq!('ß'.to_lowercase(), 'ß'); + assert_eq!('Ü'.to_lowercase(), 'ü'); + assert_eq!('💩'.to_lowercase(), '💩'); + assert_eq!('Σ'.to_lowercase(), 'σ'); + assert_eq!('Τ'.to_lowercase(), 'τ'); + assert_eq!('Ι'.to_lowercase(), 'ι'); + assert_eq!('Γ'.to_lowercase(), 'γ'); + assert_eq!('Μ'.to_lowercase(), 'μ'); + assert_eq!('Α'.to_lowercase(), 'α'); + assert_eq!('Σ'.to_lowercase(), 'σ'); +} + +#[test] +fn test_to_uppercase() { + assert_eq!('a'.to_uppercase(), 'A'); + assert_eq!('ö'.to_uppercase(), 'Ö'); + assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s + assert_eq!('ü'.to_uppercase(), 'Ü'); + assert_eq!('💩'.to_uppercase(), '💩'); + + assert_eq!('σ'.to_uppercase(), 'Σ'); + assert_eq!('τ'.to_uppercase(), 'Τ'); + assert_eq!('ι'.to_uppercase(), 'Ι'); + assert_eq!('γ'.to_uppercase(), 'Γ'); + assert_eq!('μ'.to_uppercase(), 'Μ'); + assert_eq!('α'.to_uppercase(), 'Α'); + assert_eq!('ς'.to_uppercase(), 'Σ'); +} + +#[test] +fn test_is_control() { + assert!('\u0000'.is_control()); + assert!('\u0003'.is_control()); + assert!('\u0006'.is_control()); + assert!('\u0009'.is_control()); + assert!('\u007f'.is_control()); + assert!('\u0092'.is_control()); + assert!(!'\u0020'.is_control()); + assert!(!'\u0055'.is_control()); + assert!(!'\u0068'.is_control()); +} + +#[test] +fn test_is_digit() { + assert!('2'.is_digit()); + assert!('7'.is_digit()); + assert!(!'c'.is_digit()); + assert!(!'i'.is_digit()); + assert!(!'z'.is_digit()); + assert!(!'Q'.is_digit()); +} + +#[test] +fn test_escape_default() { + fn string(c: char) -> String { + let mut result = String::new(); + escape_default(c, |c| { result.push_char(c); }); + return result; + } + let s = string('\n'); + assert_eq!(s.as_slice(), "\\n"); + let s = string('\r'); + assert_eq!(s.as_slice(), "\\r"); + let s = string('\''); + assert_eq!(s.as_slice(), "\\'"); + let s = string('"'); + assert_eq!(s.as_slice(), "\\\""); + let s = string(' '); + assert_eq!(s.as_slice(), " "); + let s = string('a'); + assert_eq!(s.as_slice(), "a"); + let s = string('~'); + assert_eq!(s.as_slice(), "~"); + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\x1f'); + assert_eq!(s.as_slice(), "\\x1f"); + let s = string('\x7f'); + assert_eq!(s.as_slice(), "\\x7f"); + let s = string('\xff'); + assert_eq!(s.as_slice(), "\\xff"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); +} + +#[test] +fn test_escape_unicode() { + fn string(c: char) -> String { + let mut result = String::new(); + escape_unicode(c, |c| { result.push_char(c); }); + return result; + } + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\n'); + assert_eq!(s.as_slice(), "\\x0a"); + let s = string(' '); + assert_eq!(s.as_slice(), "\\x20"); + let s = string('a'); + assert_eq!(s.as_slice(), "\\x61"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); +} + +#[test] +fn test_to_str() { + 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]; + let n = input.encode_utf8(buf /* as mut slice! */); + assert_eq!(buf.slice_to(n), expect); + } + + check('x', [0x78]); + check('\u00e9', [0xc3, 0xa9]); + check('\ua66e', [0xea, 0x99, 0xae]); + check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]); +} + +#[test] +fn test_encode_utf16() { + fn check(input: char, expect: &[u16]) { + let mut buf = [0u16, ..2]; + let n = input.encode_utf16(buf /* as mut slice! */); + assert_eq!(buf.slice_to(n), expect); + } + + check('x', [0x0078]); + check('\u00e9', [0x00e9]); + check('\ua66e', [0xa66e]); + check('\U0001f4a9', [0xd83d, 0xdca9]); +} diff --git a/src/libcoretest/clone.rs b/src/libcoretest/clone.rs new file mode 100644 index 00000000000..67c30d945d4 --- /dev/null +++ b/src/libcoretest/clone.rs @@ -0,0 +1,39 @@ +// 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. + +#[test] +fn test_borrowed_clone() { + let x = 5i; + let y: &int = &x; + let z: &int = (&y).clone(); + assert_eq!(*z, 5); +} + +#[test] +fn test_clone_from() { + let a = box 5i; + let mut b = box 10i; + b.clone_from(&a); + assert_eq!(*b, 5); +} + +#[test] +fn test_extern_fn_clone() { + trait Empty {} + impl Empty for int {} + + fn test_fn_a() -> f64 { 1.0 } + fn test_fn_b<T: Empty>(x: T) -> T { x } + fn test_fn_c(_: int, _: f64, _: int, _: int, _: int) {} + + let _ = test_fn_a.clone(); + let _ = test_fn_b::<int>.clone(); + let _ = test_fn_c.clone(); +} diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs new file mode 100644 index 00000000000..88e944be3e8 --- /dev/null +++ b/src/libcoretest/cmp.rs @@ -0,0 +1,69 @@ +// 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. + +use core::cmp::lexical_ordering; + +#[test] +fn test_int_totalord() { + assert_eq!(5i.cmp(&10), Less); + assert_eq!(10i.cmp(&5), Greater); + assert_eq!(5i.cmp(&5), Equal); + assert_eq!((-5i).cmp(&12), Less); + assert_eq!(12i.cmp(&-5), Greater); +} + +#[test] +fn test_mut_int_totalord() { + assert_eq!((&mut 5i).cmp(&&mut 10), Less); + assert_eq!((&mut 10i).cmp(&&mut 5), Greater); + assert_eq!((&mut 5i).cmp(&&mut 5), Equal); + assert_eq!((&mut -5i).cmp(&&mut 12), Less); + assert_eq!((&mut 12i).cmp(&&mut -5), Greater); +} + +#[test] +fn test_ordering_order() { + assert!(Less < Equal); + assert_eq!(Greater.cmp(&Less), Greater); +} + +#[test] +fn test_lexical_ordering() { + fn t(o1: Ordering, o2: Ordering, e: Ordering) { + assert_eq!(lexical_ordering(o1, o2), e); + } + + let xs = [Less, Equal, Greater]; + for &o in xs.iter() { + t(Less, o, Less); + t(Equal, o, o); + t(Greater, o, Greater); + } +} + +#[test] +fn test_user_defined_eq() { + // Our type. + struct SketchyNum { + num : int + } + + // Our implementation of `PartialEq` to support `==` and `!=`. + impl PartialEq for SketchyNum { + // Our custom eq allows numbers which are near each other to be equal! :D + fn eq(&self, other: &SketchyNum) -> bool { + (self.num - other.num).abs() < 5 + } + } + + // Now these binary operators will work when applied! + assert!(SketchyNum {num: 37} == SketchyNum {num: 34}); + assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); +} diff --git a/src/libcoretest/finally.rs b/src/libcoretest/finally.rs new file mode 100644 index 00000000000..5da004086d2 --- /dev/null +++ b/src/libcoretest/finally.rs @@ -0,0 +1,59 @@ +// 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. + +use core::finally::{try_finally, Finally}; +use std::task::failing; + +#[test] +fn test_success() { + let mut i = 0i; + try_finally( + &mut i, (), + |i, ()| { + *i = 10; + }, + |i| { + assert!(!failing()); + assert_eq!(*i, 10); + *i = 20; + }); + assert_eq!(i, 20); +} + +#[test] +#[should_fail] +fn test_fail() { + let mut i = 0i; + try_finally( + &mut i, (), + |i, ()| { + *i = 10; + fail!(); + }, + |i| { + assert!(failing()); + assert_eq!(*i, 10); + }) +} + +#[test] +fn test_retval() { + let mut closure: || -> int = || 10; + let i = closure.finally(|| { }); + assert_eq!(i, 10); +} + +#[test] +fn test_compact() { + fn do_some_fallible_work() {} + fn but_always_run_this_function() { } + let mut f = do_some_fallible_work; + f.finally(but_always_run_this_function); +} diff --git a/src/libcoretest/fmt/mod.rs b/src/libcoretest/fmt/mod.rs new file mode 100644 index 00000000000..9fc09b3124e --- /dev/null +++ b/src/libcoretest/fmt/mod.rs @@ -0,0 +1,11 @@ +// 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. + +mod num; diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs new file mode 100644 index 00000000000..baef7e3a11e --- /dev/null +++ b/src/libcoretest/fmt/num.rs @@ -0,0 +1,234 @@ +// 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. +#![allow(unsigned_negate)] + +use core::fmt::radix; + +#[test] +fn test_format_int() { + // Formatting integers should select the right implementation based off + // the type of the argument. Also, hex/octal/binary should be defined + // for integers, but they shouldn't emit the negative sign. + assert!(format!("{}", 1i).as_slice() == "1"); + assert!(format!("{}", 1i8).as_slice() == "1"); + assert!(format!("{}", 1i16).as_slice() == "1"); + assert!(format!("{}", 1i32).as_slice() == "1"); + assert!(format!("{}", 1i64).as_slice() == "1"); + assert!(format!("{:d}", -1i).as_slice() == "-1"); + assert!(format!("{:d}", -1i8).as_slice() == "-1"); + assert!(format!("{:d}", -1i16).as_slice() == "-1"); + assert!(format!("{:d}", -1i32).as_slice() == "-1"); + assert!(format!("{:d}", -1i64).as_slice() == "-1"); + assert!(format!("{:t}", 1i).as_slice() == "1"); + assert!(format!("{:t}", 1i8).as_slice() == "1"); + assert!(format!("{:t}", 1i16).as_slice() == "1"); + assert!(format!("{:t}", 1i32).as_slice() == "1"); + assert!(format!("{:t}", 1i64).as_slice() == "1"); + assert!(format!("{:x}", 1i).as_slice() == "1"); + assert!(format!("{:x}", 1i8).as_slice() == "1"); + assert!(format!("{:x}", 1i16).as_slice() == "1"); + assert!(format!("{:x}", 1i32).as_slice() == "1"); + assert!(format!("{:x}", 1i64).as_slice() == "1"); + assert!(format!("{:X}", 1i).as_slice() == "1"); + assert!(format!("{:X}", 1i8).as_slice() == "1"); + assert!(format!("{:X}", 1i16).as_slice() == "1"); + assert!(format!("{:X}", 1i32).as_slice() == "1"); + assert!(format!("{:X}", 1i64).as_slice() == "1"); + assert!(format!("{:o}", 1i).as_slice() == "1"); + assert!(format!("{:o}", 1i8).as_slice() == "1"); + assert!(format!("{:o}", 1i16).as_slice() == "1"); + assert!(format!("{:o}", 1i32).as_slice() == "1"); + assert!(format!("{:o}", 1i64).as_slice() == "1"); + + assert!(format!("{}", 1u).as_slice() == "1"); + assert!(format!("{}", 1u8).as_slice() == "1"); + assert!(format!("{}", 1u16).as_slice() == "1"); + assert!(format!("{}", 1u32).as_slice() == "1"); + assert!(format!("{}", 1u64).as_slice() == "1"); + assert!(format!("{:u}", 1u).as_slice() == "1"); + assert!(format!("{:u}", 1u8).as_slice() == "1"); + assert!(format!("{:u}", 1u16).as_slice() == "1"); + assert!(format!("{:u}", 1u32).as_slice() == "1"); + assert!(format!("{:u}", 1u64).as_slice() == "1"); + assert!(format!("{:t}", 1u).as_slice() == "1"); + assert!(format!("{:t}", 1u8).as_slice() == "1"); + assert!(format!("{:t}", 1u16).as_slice() == "1"); + assert!(format!("{:t}", 1u32).as_slice() == "1"); + assert!(format!("{:t}", 1u64).as_slice() == "1"); + assert!(format!("{:x}", 1u).as_slice() == "1"); + assert!(format!("{:x}", 1u8).as_slice() == "1"); + assert!(format!("{:x}", 1u16).as_slice() == "1"); + assert!(format!("{:x}", 1u32).as_slice() == "1"); + assert!(format!("{:x}", 1u64).as_slice() == "1"); + assert!(format!("{:X}", 1u).as_slice() == "1"); + assert!(format!("{:X}", 1u8).as_slice() == "1"); + assert!(format!("{:X}", 1u16).as_slice() == "1"); + assert!(format!("{:X}", 1u32).as_slice() == "1"); + assert!(format!("{:X}", 1u64).as_slice() == "1"); + assert!(format!("{:o}", 1u).as_slice() == "1"); + assert!(format!("{:o}", 1u8).as_slice() == "1"); + assert!(format!("{:o}", 1u16).as_slice() == "1"); + assert!(format!("{:o}", 1u32).as_slice() == "1"); + assert!(format!("{:o}", 1u64).as_slice() == "1"); + + // Test a larger number + assert!(format!("{:t}", 55i).as_slice() == "110111"); + assert!(format!("{:o}", 55i).as_slice() == "67"); + assert!(format!("{:d}", 55i).as_slice() == "55"); + assert!(format!("{:x}", 55i).as_slice() == "37"); + assert!(format!("{:X}", 55i).as_slice() == "37"); +} + +#[test] +fn test_format_int_zero() { + assert!(format!("{}", 0i).as_slice() == "0"); + assert!(format!("{:d}", 0i).as_slice() == "0"); + assert!(format!("{:t}", 0i).as_slice() == "0"); + assert!(format!("{:o}", 0i).as_slice() == "0"); + assert!(format!("{:x}", 0i).as_slice() == "0"); + assert!(format!("{:X}", 0i).as_slice() == "0"); + + assert!(format!("{}", 0u).as_slice() == "0"); + assert!(format!("{:u}", 0u).as_slice() == "0"); + assert!(format!("{:t}", 0u).as_slice() == "0"); + assert!(format!("{:o}", 0u).as_slice() == "0"); + assert!(format!("{:x}", 0u).as_slice() == "0"); + assert!(format!("{:X}", 0u).as_slice() == "0"); +} + +#[test] +fn test_format_int_flags() { + assert!(format!("{:3d}", 1i).as_slice() == " 1"); + assert!(format!("{:>3d}", 1i).as_slice() == " 1"); + assert!(format!("{:>+3d}", 1i).as_slice() == " +1"); + assert!(format!("{:<3d}", 1i).as_slice() == "1 "); + assert!(format!("{:#d}", 1i).as_slice() == "1"); + assert!(format!("{:#x}", 10i).as_slice() == "0xa"); + assert!(format!("{:#X}", 10i).as_slice() == "0xA"); + assert!(format!("{:#5x}", 10i).as_slice() == " 0xa"); + assert!(format!("{:#o}", 10i).as_slice() == "0o12"); + assert!(format!("{:08x}", 10i).as_slice() == "0000000a"); + assert!(format!("{:8x}", 10i).as_slice() == " a"); + assert!(format!("{:<8x}", 10i).as_slice() == "a "); + assert!(format!("{:>8x}", 10i).as_slice() == " a"); + assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a"); + assert!(format!("{:08d}", -10i).as_slice() == "-0000010"); + assert!(format!("{:x}", -1u8).as_slice() == "ff"); + assert!(format!("{:X}", -1u8).as_slice() == "FF"); + assert!(format!("{:t}", -1u8).as_slice() == "11111111"); + assert!(format!("{:o}", -1u8).as_slice() == "377"); + assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); + assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); + assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); + assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); +} + +#[test] +fn test_format_int_sign_padding() { + assert!(format!("{:+5d}", 1i).as_slice() == " +1"); + assert!(format!("{:+5d}", -1i).as_slice() == " -1"); + assert!(format!("{:05d}", 1i).as_slice() == "00001"); + assert!(format!("{:05d}", -1i).as_slice() == "-0001"); + assert!(format!("{:+05d}", 1i).as_slice() == "+0001"); + assert!(format!("{:+05d}", -1i).as_slice() == "-0001"); +} + +#[test] +fn test_format_int_twos_complement() { + use core::{i8, i16, i32, i64}; + assert!(format!("{}", i8::MIN).as_slice() == "-128"); + assert!(format!("{}", i16::MIN).as_slice() == "-32768"); + assert!(format!("{}", i32::MIN).as_slice() == "-2147483648"); + assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808"); +} + +#[test] +fn test_format_radix() { + assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011"); + assert!(format!("{}", radix(55i, 36)).as_slice() == "1j"); +} + +#[test] +#[should_fail] +fn test_radix_base_too_large() { + let _ = radix(55i, 37); +} + +mod uint { + use test::Bencher; + use core::fmt::radix; + use std::rand::{weak_rng, Rng}; + + #[bench] + fn format_bin(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:t}", rng.gen::<uint>()); }) + } + + #[bench] + fn format_oct(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:o}", rng.gen::<uint>()); }) + } + + #[bench] + fn format_dec(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:u}", rng.gen::<uint>()); }) + } + + #[bench] + fn format_hex(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:x}", rng.gen::<uint>()); }) + } + + #[bench] + fn format_base_36(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{}", radix(rng.gen::<uint>(), 36)); }) + } +} + +mod int { + use test::Bencher; + use core::fmt::radix; + use std::rand::{weak_rng, Rng}; + + #[bench] + fn format_bin(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:t}", rng.gen::<int>()); }) + } + + #[bench] + fn format_oct(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:o}", rng.gen::<int>()); }) + } + + #[bench] + fn format_dec(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:d}", rng.gen::<int>()); }) + } + + #[bench] + fn format_hex(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:x}", rng.gen::<int>()); }) + } + + #[bench] + fn format_base_36(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{}", radix(rng.gen::<int>(), 36)); }) + } +} diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs new file mode 100644 index 00000000000..86b5ffece41 --- /dev/null +++ b/src/libcoretest/iter.rs @@ -0,0 +1,835 @@ +// 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. + +use core::iter::*; +use core::iter::order::*; +use core::uint; +use core::cmp; +use core::num; + +#[test] +fn test_lt() { + let empty: [int, ..0] = []; + let xs = [1i,2,3]; + let ys = [1i,2,0]; + + assert!(!lt(xs.iter(), ys.iter())); + assert!(!le(xs.iter(), ys.iter())); + assert!( gt(xs.iter(), ys.iter())); + assert!( ge(xs.iter(), ys.iter())); + + assert!( lt(ys.iter(), xs.iter())); + assert!( le(ys.iter(), xs.iter())); + assert!(!gt(ys.iter(), xs.iter())); + assert!(!ge(ys.iter(), xs.iter())); + + assert!( lt(empty.iter(), xs.iter())); + assert!( le(empty.iter(), xs.iter())); + assert!(!gt(empty.iter(), xs.iter())); + assert!(!ge(empty.iter(), xs.iter())); + + // Sequence with NaN + let u = [1.0f64, 2.0]; + let v = [0.0f64/0.0, 3.0]; + + assert!(!lt(u.iter(), v.iter())); + assert!(!le(u.iter(), v.iter())); + assert!(!gt(u.iter(), v.iter())); + assert!(!ge(u.iter(), v.iter())); + + let a = [0.0f64/0.0]; + let b = [1.0f64]; + let c = [2.0f64]; + + assert!(lt(a.iter(), b.iter()) == (a[0] < b[0])); + assert!(le(a.iter(), b.iter()) == (a[0] <= b[0])); + assert!(gt(a.iter(), b.iter()) == (a[0] > b[0])); + assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0])); + + assert!(lt(c.iter(), b.iter()) == (c[0] < b[0])); + assert!(le(c.iter(), b.iter()) == (c[0] <= b[0])); + assert!(gt(c.iter(), b.iter()) == (c[0] > b[0])); + assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0])); +} + +#[test] +fn test_multi_iter() { + let xs = [1i,2,3,4]; + let ys = [4i,3,2,1]; + assert!(eq(xs.iter(), ys.iter().rev())); + assert!(lt(xs.iter(), xs.iter().skip(2))); +} + +#[test] +fn test_counter_from_iter() { + let it = count(0i, 5).take(10); + let xs: Vec<int> = FromIterator::from_iter(it); + assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]); +} + +#[test] +fn test_iterator_chain() { + let xs = [0u, 1, 2, 3, 4, 5]; + let ys = [30u, 40, 50, 60]; + let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60]; + let mut it = xs.iter().chain(ys.iter()); + let mut i = 0; + for &x in it { + assert_eq!(x, expected[i]); + i += 1; + } + assert_eq!(i, expected.len()); + + let ys = count(30u, 10).take(4); + let mut it = xs.iter().map(|&x| x).chain(ys); + let mut i = 0; + for x in it { + assert_eq!(x, expected[i]); + i += 1; + } + assert_eq!(i, expected.len()); +} + +#[test] +fn test_filter_map() { + let mut it = count(0u, 1u).take(10) + .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None }); + assert!(it.collect::<Vec<uint>>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]); +} + +#[test] +fn test_iterator_enumerate() { + let xs = [0u, 1, 2, 3, 4, 5]; + let mut it = xs.iter().enumerate(); + for (i, &x) in it { + assert_eq!(i, x); + } +} + +#[test] +fn test_iterator_peekable() { + let xs = vec![0u, 1, 2, 3, 4, 5]; + let mut it = xs.iter().map(|&x|x).peekable(); + assert_eq!(it.peek().unwrap(), &0); + assert_eq!(it.next().unwrap(), 0); + assert_eq!(it.next().unwrap(), 1); + assert_eq!(it.next().unwrap(), 2); + assert_eq!(it.peek().unwrap(), &3); + assert_eq!(it.peek().unwrap(), &3); + assert_eq!(it.next().unwrap(), 3); + assert_eq!(it.next().unwrap(), 4); + assert_eq!(it.peek().unwrap(), &5); + assert_eq!(it.next().unwrap(), 5); + assert!(it.peek().is_none()); + assert!(it.next().is_none()); +} + +#[test] +fn test_iterator_take_while() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [0u, 1, 2, 3, 5, 13]; + let mut it = xs.iter().take_while(|&x| *x < 15u); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_skip_while() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [15, 16, 17, 19]; + let mut it = xs.iter().skip_while(|&x| *x < 15u); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_skip() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30]; + let ys = [13, 15, 16, 17, 19, 20, 30]; + let mut it = xs.iter().skip(5); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_take() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [0u, 1, 2, 3, 5]; + let mut it = xs.iter().take(5); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_scan() { + // test the type inference + fn add(old: &mut int, new: &uint) -> Option<f64> { + *old += *new as int; + Some(*old as f64) + } + let xs = [0u, 1, 2, 3, 4]; + let ys = [0f64, 1.0, 3.0, 6.0, 10.0]; + + let mut it = xs.iter().scan(0, add); + let mut i = 0; + for x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_flat_map() { + let xs = [0u, 3, 6]; + let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8]; + let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3)); + let mut i = 0; + for x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_inspect() { + let xs = [1u, 2, 3, 4]; + let mut n = 0; + + let ys = xs.iter() + .map(|&x| x) + .inspect(|_| n += 1) + .collect::<Vec<uint>>(); + + assert_eq!(n, xs.len()); + assert_eq!(xs.as_slice(), ys.as_slice()); +} + +#[test] +fn test_unfoldr() { + fn count(st: &mut uint) -> Option<uint> { + if *st < 10 { + let ret = Some(*st); + *st += 1; + ret + } else { + None + } + } + + let mut it = Unfold::new(0, count); + let mut i = 0; + for counted in it { + assert_eq!(counted, i); + i += 1; + } + assert_eq!(i, 10); +} + +#[test] +fn test_cycle() { + let cycle_len = 3; + let it = count(0u, 1).take(cycle_len).cycle(); + assert_eq!(it.size_hint(), (uint::MAX, None)); + for (i, x) in it.take(100).enumerate() { + assert_eq!(i % cycle_len, x); + } + + let mut it = count(0u, 1).take(0).cycle(); + assert_eq!(it.size_hint(), (0, Some(0))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_iterator_nth() { + let v = &[0i, 1, 2, 3, 4]; + for i in range(0u, v.len()) { + assert_eq!(v.iter().nth(i).unwrap(), &v[i]); + } +} + +#[test] +fn test_iterator_last() { + let v = &[0i, 1, 2, 3, 4]; + assert_eq!(v.iter().last().unwrap(), &4); + assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); +} + +#[test] +fn test_iterator_len() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().count(), 4); + assert_eq!(v.slice(0, 10).iter().count(), 10); + assert_eq!(v.slice(0, 0).iter().count(), 0); +} + +#[test] +fn test_iterator_sum() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6); + assert_eq!(v.iter().map(|&x| x).sum(), 55); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0); +} + +#[test] +fn test_iterator_product() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0); + assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1); +} + +#[test] +fn test_iterator_max() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3)); + assert_eq!(v.iter().map(|&x| x).max(), Some(10)); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None); +} + +#[test] +fn test_iterator_min() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0)); + assert_eq!(v.iter().map(|&x| x).min(), Some(0)); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None); +} + +#[test] +fn test_iterator_size_hint() { + let c = count(0i, 1); + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let v2 = &[10i, 11, 12]; + let vi = v.iter(); + + assert_eq!(c.size_hint(), (uint::MAX, None)); + assert_eq!(vi.size_hint(), (10, Some(10))); + + assert_eq!(c.take(5).size_hint(), (5, Some(5))); + assert_eq!(c.skip(5).size_hint().val1(), None); + assert_eq!(c.take_while(|_| false).size_hint(), (0, None)); + assert_eq!(c.skip_while(|_| false).size_hint(), (0, None)); + assert_eq!(c.enumerate().size_hint(), (uint::MAX, None)); + assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None)); + assert_eq!(c.zip(vi).size_hint(), (10, Some(10))); + assert_eq!(c.scan(0i, |_,_| Some(0i)).size_hint(), (0, None)); + assert_eq!(c.filter(|_| false).size_hint(), (0, None)); + assert_eq!(c.map(|_| 0i).size_hint(), (uint::MAX, None)); + assert_eq!(c.filter_map(|_| Some(0i)).size_hint(), (0, None)); + + assert_eq!(vi.take(5).size_hint(), (5, Some(5))); + assert_eq!(vi.take(12).size_hint(), (10, Some(10))); + assert_eq!(vi.skip(3).size_hint(), (7, Some(7))); + assert_eq!(vi.skip(12).size_hint(), (0, Some(0))); + assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.enumerate().size_hint(), (10, Some(10))); + assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13))); + assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3))); + assert_eq!(vi.scan(0i, |_,_| Some(0i)).size_hint(), (0, Some(10))); + assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10))); + assert_eq!(vi.filter_map(|_| Some(0i)).size_hint(), (0, Some(10))); +} + +#[test] +fn test_collect() { + let a = vec![1i, 2, 3, 4, 5]; + let b: Vec<int> = a.iter().map(|&x| x).collect(); + assert!(a == b); +} + +#[test] +fn test_all() { + let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; + assert!(v.iter().all(|&x| x < 10)); + assert!(!v.iter().all(|&x| x % 2 == 0)); + assert!(!v.iter().all(|&x| x > 100)); + assert!(v.slice(0, 0).iter().all(|_| fail!())); +} + +#[test] +fn test_any() { + let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; + assert!(v.iter().any(|&x| x < 10)); + assert!(v.iter().any(|&x| x % 2 == 0)); + assert!(!v.iter().any(|&x| x > 100)); + assert!(!v.slice(0, 0).iter().any(|_| fail!())); +} + +#[test] +fn test_find() { + let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11]; + assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14); + assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3); + assert!(v.iter().find(|x| *x % 12 == 0).is_none()); +} + +#[test] +fn test_position() { + let v = &[1i, 3, 9, 27, 103, 14, 11]; + assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5); + assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1); + assert!(v.iter().position(|x| *x % 12 == 0).is_none()); +} + +#[test] +fn test_count() { + let xs = &[1i, 2, 2, 1, 5, 9, 0, 2]; + assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3); + assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1); + assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0); +} + +#[test] +fn test_max_by() { + let xs: &[int] = &[-3i, 0, 1, 5, -10]; + assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); +} + +#[test] +fn test_min_by() { + let xs: &[int] = &[-3i, 0, 1, 5, -10]; + assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); +} + +#[test] +fn test_by_ref() { + let mut xs = range(0i, 10); + // sum the first five values + let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); + assert_eq!(partial_sum, 10); + assert_eq!(xs.next(), Some(5)); +} + +#[test] +fn test_rev() { + let xs = [2i, 4, 6, 8, 10, 12, 14, 16]; + let mut it = xs.iter(); + it.next(); + it.next(); + assert!(it.rev().map(|&x| x).collect::<Vec<int>>() == + vec![16, 14, 12, 10, 8, 6]); +} + +#[test] +fn test_double_ended_map() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().map(|&x| x * -1); + assert_eq!(it.next(), Some(-1)); + assert_eq!(it.next(), Some(-2)); + assert_eq!(it.next_back(), Some(-6)); + assert_eq!(it.next_back(), Some(-5)); + assert_eq!(it.next(), Some(-3)); + assert_eq!(it.next_back(), Some(-4)); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_enumerate() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().map(|&x| x).enumerate(); + assert_eq!(it.next(), Some((0, 1))); + assert_eq!(it.next(), Some((1, 2))); + assert_eq!(it.next_back(), Some((5, 6))); + assert_eq!(it.next_back(), Some((4, 5))); + assert_eq!(it.next_back(), Some((3, 4))); + assert_eq!(it.next_back(), Some((2, 3))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_zip() { + let xs = [1i, 2, 3, 4, 5, 6]; + let ys = [1i, 2, 3, 7]; + let a = xs.iter().map(|&x| x); + let b = ys.iter().map(|&x| x); + let mut it = a.zip(b); + assert_eq!(it.next(), Some((1, 1))); + assert_eq!(it.next(), Some((2, 2))); + assert_eq!(it.next_back(), Some((4, 7))); + assert_eq!(it.next_back(), Some((3, 3))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_filter() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().filter(|&x| *x & 1 == 0); + assert_eq!(it.next_back().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &4); + assert_eq!(it.next().unwrap(), &2); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_double_ended_filter_map() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None }); + assert_eq!(it.next_back().unwrap(), 12); + assert_eq!(it.next_back().unwrap(), 8); + assert_eq!(it.next().unwrap(), 4); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_double_ended_chain() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + let mut it = xs.iter().chain(ys.iter()).rev(); + assert_eq!(it.next().unwrap(), &11) + assert_eq!(it.next().unwrap(), &9) + assert_eq!(it.next_back().unwrap(), &1) + assert_eq!(it.next_back().unwrap(), &2) + assert_eq!(it.next_back().unwrap(), &3) + assert_eq!(it.next_back().unwrap(), &4) + assert_eq!(it.next_back().unwrap(), &5) + assert_eq!(it.next_back().unwrap(), &7) + assert_eq!(it.next_back(), None) +} + +#[test] +fn test_rposition() { + fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } + fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } + let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; + + assert_eq!(v.iter().rposition(f), Some(3u)); + assert!(v.iter().rposition(g).is_none()); +} + +#[test] +#[should_fail] +fn test_rposition_fail() { + use std::gc::GC; + let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i), + (box 0i, box(GC) 0i), (box 0i, box(GC) 0i)]; + let mut i = 0i; + v.iter().rposition(|_elt| { + if i == 2 { + fail!() + } + i += 1; + false + }); +} + + +#[cfg(test)] +fn check_randacc_iter<A: PartialEq, T: Clone + RandomAccessIterator<A>>(a: T, len: uint) +{ + let mut b = a.clone(); + assert_eq!(len, b.indexable()); + let mut n = 0u; + for (i, elt) in a.enumerate() { + assert!(Some(elt) == b.idx(i)); + n += 1; + } + assert_eq!(n, len); + assert!(None == b.idx(n)); + // call recursively to check after picking off an element + if len > 0 { + b.next(); + check_randacc_iter(b, len-1); + } +} + + +#[test] +fn test_double_ended_flat_map() { + let u = [0u,1]; + let v = [5u,6,7,8]; + let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter()); + assert_eq!(it.next_back().unwrap(), &8); + assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next_back().unwrap(), &7); + assert_eq!(it.next_back().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &8); + assert_eq!(it.next().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &7); + assert_eq!(it.next_back(), None); + assert_eq!(it.next(), None); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_random_access_chain() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + let mut it = xs.iter().chain(ys.iter()); + assert_eq!(it.idx(0).unwrap(), &1); + assert_eq!(it.idx(5).unwrap(), &7); + assert_eq!(it.idx(7).unwrap(), &11); + assert!(it.idx(8).is_none()); + + it.next(); + it.next(); + it.next_back(); + + assert_eq!(it.idx(0).unwrap(), &3); + assert_eq!(it.idx(4).unwrap(), &9); + assert!(it.idx(6).is_none()); + + check_randacc_iter(it, xs.len() + ys.len() - 3); +} + +#[test] +fn test_random_access_enumerate() { + let xs = [1i, 2, 3, 4, 5]; + check_randacc_iter(xs.iter().enumerate(), xs.len()); +} + +#[test] +fn test_random_access_rev() { + let xs = [1i, 2, 3, 4, 5]; + check_randacc_iter(xs.iter().rev(), xs.len()); + let mut it = xs.iter().rev(); + it.next(); + it.next_back(); + it.next(); + check_randacc_iter(it, xs.len() - 3); +} + +#[test] +fn test_random_access_zip() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len())); +} + +#[test] +fn test_random_access_take() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().take(3), 3); + check_randacc_iter(xs.iter().take(20), xs.len()); + check_randacc_iter(xs.iter().take(0), 0); + check_randacc_iter(empty.iter().take(2), 0); +} + +#[test] +fn test_random_access_skip() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().skip(2), xs.len() - 2); + check_randacc_iter(empty.iter().skip(2), 0); +} + +#[test] +fn test_random_access_inspect() { + let xs = [1i, 2, 3, 4, 5]; + + // test .map and .inspect that don't implement Clone + let mut it = xs.iter().inspect(|_| {}); + assert_eq!(xs.len(), it.indexable()); + for (i, elt) in xs.iter().enumerate() { + assert_eq!(Some(elt), it.idx(i)); + } + +} + +#[test] +fn test_random_access_map() { + let xs = [1i, 2, 3, 4, 5]; + + let mut it = xs.iter().map(|x| *x); + assert_eq!(xs.len(), it.indexable()); + for (i, elt) in xs.iter().enumerate() { + assert_eq!(Some(*elt), it.idx(i)); + } +} + +#[test] +fn test_random_access_cycle() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().cycle().take(27), 27); + check_randacc_iter(empty.iter().cycle(), 0); +} + +#[test] +fn test_double_ended_range() { + assert!(range(11i, 14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]); + for _ in range(10i, 0).rev() { + fail!("unreachable"); + } + + assert!(range(11u, 14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]); + for _ in range(10u, 0).rev() { + fail!("unreachable"); + } +} + +#[test] +fn test_range() { + /// A mock type to check Range when ToPrimitive returns None + struct Foo; + + impl ToPrimitive for Foo { + fn to_i64(&self) -> Option<i64> { None } + fn to_u64(&self) -> Option<u64> { None } + } + + impl Add<Foo, Foo> for Foo { + fn add(&self, _: &Foo) -> Foo { + Foo + } + } + + impl PartialEq for Foo { + fn eq(&self, _: &Foo) -> bool { + true + } + } + + impl PartialOrd for Foo { + fn partial_cmp(&self, _: &Foo) -> Option<Ordering> { + None + } + } + + impl Clone for Foo { + fn clone(&self) -> Foo { + Foo + } + } + + impl Mul<Foo, Foo> for Foo { + fn mul(&self, _: &Foo) -> Foo { + Foo + } + } + + impl num::One for Foo { + fn one() -> Foo { + Foo + } + } + + assert!(range(0i, 5).collect::<Vec<int>>() == vec![0i, 1, 2, 3, 4]); + assert!(range(-10i, -1).collect::<Vec<int>>() == + vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); + assert!(range(0i, 5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]); + assert_eq!(range(200i, -5).count(), 0); + assert_eq!(range(200i, -5).rev().count(), 0); + assert_eq!(range(200i, 200).count(), 0); + assert_eq!(range(200i, 200).rev().count(), 0); + + assert_eq!(range(0i, 100).size_hint(), (100, Some(100))); + // this test is only meaningful when sizeof uint < sizeof u64 + assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1))); + assert_eq!(range(-10i, -1).size_hint(), (9, Some(9))); + assert_eq!(range(Foo, Foo).size_hint(), (0, None)); +} + +#[test] +fn test_range_inclusive() { + assert!(range_inclusive(0i, 5).collect::<Vec<int>>() == + vec![0i, 1, 2, 3, 4, 5]); + assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() == + vec![5i, 4, 3, 2, 1, 0]); + assert_eq!(range_inclusive(200i, -5).count(), 0); + assert_eq!(range_inclusive(200i, -5).rev().count(), 0); + assert!(range_inclusive(200i, 200).collect::<Vec<int>>() == vec![200]); + assert!(range_inclusive(200i, 200).rev().collect::<Vec<int>>() == vec![200]); +} + +#[test] +fn test_range_step() { + assert!(range_step(0i, 20, 5).collect::<Vec<int>>() == + vec![0, 5, 10, 15]); + assert!(range_step(20i, 0, -5).collect::<Vec<int>>() == + vec![20, 15, 10, 5]); + assert!(range_step(20i, 0, -6).collect::<Vec<int>>() == + vec![20, 14, 8, 2]); + assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() == + vec![200u8, 250]); + assert!(range_step(200i, -5, 1).collect::<Vec<int>>() == vec![]); + assert!(range_step(200i, 200, 1).collect::<Vec<int>>() == vec![]); +} + +#[test] +fn test_range_step_inclusive() { + assert!(range_step_inclusive(0i, 20, 5).collect::<Vec<int>>() == + vec![0, 5, 10, 15, 20]); + assert!(range_step_inclusive(20i, 0, -5).collect::<Vec<int>>() == + vec![20, 15, 10, 5, 0]); + assert!(range_step_inclusive(20i, 0, -6).collect::<Vec<int>>() == + vec![20, 14, 8, 2]); + assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() == + vec![200u8, 250]); + assert!(range_step_inclusive(200i, -5, 1).collect::<Vec<int>>() == + vec![]); + assert!(range_step_inclusive(200i, 200, 1).collect::<Vec<int>>() == + vec![200]); +} + +#[test] +fn test_reverse() { + let mut ys = [1i, 2, 3, 4, 5]; + ys.mut_iter().reverse_(); + assert!(ys == [5, 4, 3, 2, 1]); +} + +#[test] +fn test_peekable_is_empty() { + let a = [1i]; + let mut it = a.iter().peekable(); + assert!( !it.is_empty() ); + it.next(); + assert!( it.is_empty() ); +} + +#[test] +fn test_min_max() { + let v: [int, ..0] = []; + assert_eq!(v.iter().min_max(), NoElements); + + let v = [1i]; + assert!(v.iter().min_max() == OneElement(&1)); + + let v = [1i, 2, 3, 4, 5]; + assert!(v.iter().min_max() == MinMax(&1, &5)); + + let v = [1i, 2, 3, 4, 5, 6]; + assert!(v.iter().min_max() == MinMax(&1, &6)); + + let v = [1i, 1, 1, 1]; + assert!(v.iter().min_max() == MinMax(&1, &1)); +} + +#[test] +fn test_min_max_result() { + let r: MinMaxResult<int> = NoElements; + assert_eq!(r.into_option(), None) + + let r = OneElement(1i); + assert_eq!(r.into_option(), Some((1,1))); + + let r = MinMax(1i,2); + assert_eq!(r.into_option(), Some((1,2))); +} diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs new file mode 100644 index 00000000000..3a3cac542c9 --- /dev/null +++ b/src/libcoretest/lib.rs @@ -0,0 +1,31 @@ +// 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. +#![feature(globs, unsafe_destructor, macro_rules)] + +extern crate core; +extern crate test; +extern crate libc; + +mod any; +mod atomics; +mod cell; +mod char; +mod cmp; +mod finally; +mod fmt; +mod iter; +mod mem; +mod num; +mod ops; +mod option; +mod ptr; +mod raw; +mod result; +mod tuple; diff --git a/src/libcoretest/mem.rs b/src/libcoretest/mem.rs new file mode 100644 index 00000000000..fde640158f5 --- /dev/null +++ b/src/libcoretest/mem.rs @@ -0,0 +1,173 @@ +// 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. +use core::mem::*; +use test::Bencher; + +#[test] +fn size_of_basic() { + assert_eq!(size_of::<u8>(), 1u); + assert_eq!(size_of::<u16>(), 2u); + assert_eq!(size_of::<u32>(), 4u); + assert_eq!(size_of::<u64>(), 8u); +} + +#[test] +#[cfg(target_arch = "x86")] +#[cfg(target_arch = "arm")] +#[cfg(target_arch = "mips")] +#[cfg(target_arch = "mipsel")] +fn size_of_32() { + assert_eq!(size_of::<uint>(), 4u); + assert_eq!(size_of::<*const uint>(), 4u); +} + +#[test] +#[cfg(target_arch = "x86_64")] +fn size_of_64() { + assert_eq!(size_of::<uint>(), 8u); + assert_eq!(size_of::<*const uint>(), 8u); +} + +#[test] +fn size_of_val_basic() { + assert_eq!(size_of_val(&1u8), 1); + assert_eq!(size_of_val(&1u16), 2); + assert_eq!(size_of_val(&1u32), 4); + assert_eq!(size_of_val(&1u64), 8); +} + +#[test] +fn align_of_basic() { + assert_eq!(align_of::<u8>(), 1u); + assert_eq!(align_of::<u16>(), 2u); + assert_eq!(align_of::<u32>(), 4u); +} + +#[test] +#[cfg(target_arch = "x86")] +#[cfg(target_arch = "arm")] +#[cfg(target_arch = "mips")] +#[cfg(target_arch = "mipsel")] +fn align_of_32() { + assert_eq!(align_of::<uint>(), 4u); + assert_eq!(align_of::<*const uint>(), 4u); +} + +#[test] +#[cfg(target_arch = "x86_64")] +fn align_of_64() { + assert_eq!(align_of::<uint>(), 8u); + assert_eq!(align_of::<*const uint>(), 8u); +} + +#[test] +fn align_of_val_basic() { + assert_eq!(align_of_val(&1u8), 1u); + assert_eq!(align_of_val(&1u16), 2u); + assert_eq!(align_of_val(&1u32), 4u); +} + +#[test] +fn test_swap() { + let mut x = 31337i; + let mut y = 42i; + swap(&mut x, &mut y); + assert_eq!(x, 42); + assert_eq!(y, 31337); +} + +#[test] +fn test_replace() { + let mut x = Some("test".to_string()); + let y = replace(&mut x, None); + assert!(x.is_none()); + assert!(y.is_some()); +} + +#[test] +fn test_transmute_copy() { + assert_eq!(1u, unsafe { transmute_copy(&1i) }); +} + +#[test] +fn test_transmute() { + trait Foo {} + impl Foo for int {} + + let a = box 100i as Box<Foo>; + unsafe { + let x: ::core::raw::TraitObject = transmute(a); + assert!(*(x.data as *const int) == 100); + let _x: Box<Foo> = transmute(x); + } + + unsafe { + assert!(Vec::from_slice([76u8]) == transmute("L".to_string())); + } +} + +// FIXME #13642 (these benchmarks should be in another place) +/// Completely miscellaneous language-construct benchmarks. +// Static/dynamic method dispatch + +struct Struct { + field: int +} + +trait Trait { + fn method(&self) -> int; +} + +impl Trait for Struct { + fn method(&self) -> int { + self.field + } +} + +#[bench] +fn trait_vtable_method_call(b: &mut Bencher) { + let s = Struct { field: 10 }; + let t = &s as &Trait; + b.iter(|| { + t.method() + }); +} + +#[bench] +fn trait_static_method_call(b: &mut Bencher) { + let s = Struct { field: 10 }; + b.iter(|| { + s.method() + }); +} + +// Overhead of various match forms + +#[bench] +fn match_option_some(b: &mut Bencher) { + let x = Some(10i); + b.iter(|| { + match x { + Some(y) => y, + None => 11 + } + }); +} + +#[bench] +fn match_vec_pattern(b: &mut Bencher) { + let x = [1i,2,3,4,5,6]; + b.iter(|| { + match x { + [1,2,3,..] => 10i, + _ => 11i, + } + }); +} diff --git a/src/libcoretest/num/i16.rs b/src/libcoretest/num/i16.rs new file mode 100644 index 00000000000..f3c2d67cdeb --- /dev/null +++ b/src/libcoretest/num/i16.rs @@ -0,0 +1,11 @@ +// 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. + +int_module!(i16, i16) diff --git a/src/libcoretest/num/i32.rs b/src/libcoretest/num/i32.rs new file mode 100644 index 00000000000..7232fc7505d --- /dev/null +++ b/src/libcoretest/num/i32.rs @@ -0,0 +1,11 @@ +// 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. + +int_module!(i32, i32) diff --git a/src/libcoretest/num/i64.rs b/src/libcoretest/num/i64.rs new file mode 100644 index 00000000000..075b8448f35 --- /dev/null +++ b/src/libcoretest/num/i64.rs @@ -0,0 +1,11 @@ +// 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. + +int_module!(i64, i64) diff --git a/src/libcoretest/num/i8.rs b/src/libcoretest/num/i8.rs new file mode 100644 index 00000000000..9e0439f2818 --- /dev/null +++ b/src/libcoretest/num/i8.rs @@ -0,0 +1,11 @@ +// 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. + +int_module!(i8, i8) diff --git a/src/libcoretest/num/int.rs b/src/libcoretest/num/int.rs new file mode 100644 index 00000000000..f01ec3f0310 --- /dev/null +++ b/src/libcoretest/num/int.rs @@ -0,0 +1,11 @@ +// 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. + +int_module!(int, int) diff --git a/src/libcoretest/num/int_macros.rs b/src/libcoretest/num/int_macros.rs new file mode 100644 index 00000000000..940b036ca90 --- /dev/null +++ b/src/libcoretest/num/int_macros.rs @@ -0,0 +1,160 @@ +// 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. + +#![macro_escape] + +macro_rules! int_module (($T:ty, $T_i:ident) => ( +#[cfg(test)] +mod tests { + use core::$T_i::*; + use core::int; + use num; + use core::num::CheckedDiv; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert!(MIN + MAX + 1 == 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + pub fn test_abs() { + assert!((1 as $T).abs() == 1 as $T); + assert!((0 as $T).abs() == 0 as $T); + assert!((-1 as $T).abs() == 1 as $T); + } + + #[test] + fn test_abs_sub() { + assert!((-1 as $T).abs_sub(&(1 as $T)) == 0 as $T); + assert!((1 as $T).abs_sub(&(1 as $T)) == 0 as $T); + assert!((1 as $T).abs_sub(&(0 as $T)) == 1 as $T); + assert!((1 as $T).abs_sub(&(-1 as $T)) == 2 as $T); + } + + #[test] + fn test_signum() { + assert!((1 as $T).signum() == 1 as $T); + assert!((0 as $T).signum() == 0 as $T); + assert!((-0 as $T).signum() == 0 as $T); + assert!((-1 as $T).signum() == -1 as $T); + } + + #[test] + fn test_is_positive() { + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); + } + + #[test] + fn test_is_negative() { + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); + } + + #[test] + fn test_bitwise_operators() { + assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); + assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); + assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); + assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); + assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not()); + } + + static A: $T = 0b0101100; + static B: $T = 0b0100001; + static C: $T = 0b1111001; + + static _0: $T = 0; + static _1: $T = !0; + + #[test] + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + #[test] + fn test_count_zeros() { + assert!(A.count_zeros() == BITS as $T - 3); + assert!(B.count_zeros() == BITS as $T - 2); + assert!(C.count_zeros() == BITS as $T - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_le() { + assert_eq!(Int::from_le(A.to_le()), A); + assert_eq!(Int::from_le(B.to_le()), B); + assert_eq!(Int::from_le(C.to_le()), C); + assert_eq!(Int::from_le(_0), _0); + assert_eq!(Int::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!(Int::from_be(A.to_be()), A); + assert_eq!(Int::from_be(B.to_be()), B); + assert_eq!(Int::from_be(C.to_be()), C); + assert_eq!(Int::from_be(_0), _0); + assert_eq!(Int::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_signed_checked_div() { + assert!(10i.checked_div(&2) == Some(5)); + assert!(5i.checked_div(&0) == None); + assert!(int::MIN.checked_div(&-1) == None); + } +} + +)) diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs new file mode 100644 index 00000000000..8bb238c0b66 --- /dev/null +++ b/src/libcoretest/num/mod.rs @@ -0,0 +1,39 @@ +// 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. + +use core::num::cast; + +mod int_macros; +mod i8; +mod i16; +mod i32; +mod i64; +mod int; +mod uint_macros; +mod u8; +mod u16; +mod u32; +mod u64; +mod uint; + +/// Helper function for testing numeric operations +pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) { + assert_eq!(ten.add(&two), cast(12i).unwrap()); + assert_eq!(ten.sub(&two), cast(8i).unwrap()); + assert_eq!(ten.mul(&two), cast(20i).unwrap()); + assert_eq!(ten.div(&two), cast(5i).unwrap()); + assert_eq!(ten.rem(&two), cast(0i).unwrap()); + + assert_eq!(ten.add(&two), ten + two); + assert_eq!(ten.sub(&two), ten - two); + assert_eq!(ten.mul(&two), ten * two); + assert_eq!(ten.div(&two), ten / two); + assert_eq!(ten.rem(&two), ten % two); +} diff --git a/src/libcoretest/num/u16.rs b/src/libcoretest/num/u16.rs new file mode 100644 index 00000000000..d6aa6476678 --- /dev/null +++ b/src/libcoretest/num/u16.rs @@ -0,0 +1,11 @@ +// 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. + +uint_module!(u16, u16) diff --git a/src/libcoretest/num/u32.rs b/src/libcoretest/num/u32.rs new file mode 100644 index 00000000000..218e79df5ae --- /dev/null +++ b/src/libcoretest/num/u32.rs @@ -0,0 +1,11 @@ +// 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. + +uint_module!(u32, u32) diff --git a/src/libcoretest/num/u64.rs b/src/libcoretest/num/u64.rs new file mode 100644 index 00000000000..f78d4813503 --- /dev/null +++ b/src/libcoretest/num/u64.rs @@ -0,0 +1,11 @@ +// 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. + +uint_module!(u64, u64) diff --git a/src/libcoretest/num/u8.rs b/src/libcoretest/num/u8.rs new file mode 100644 index 00000000000..bb08072320b --- /dev/null +++ b/src/libcoretest/num/u8.rs @@ -0,0 +1,11 @@ +// 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. + +uint_module!(u8, u8) diff --git a/src/libcoretest/num/uint.rs b/src/libcoretest/num/uint.rs new file mode 100644 index 00000000000..0db865f4cde --- /dev/null +++ b/src/libcoretest/num/uint.rs @@ -0,0 +1,11 @@ +// 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. + +uint_module!(uint, uint) diff --git a/src/libcoretest/num/uint_macros.rs b/src/libcoretest/num/uint_macros.rs new file mode 100644 index 00000000000..2272af67daf --- /dev/null +++ b/src/libcoretest/num/uint_macros.rs @@ -0,0 +1,118 @@ +// 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. + +#![macro_escape] + +macro_rules! uint_module (($T:ty, $T_i:ident) => ( +#[cfg(test)] +mod tests { + use core::$T_i::*; + use num; + use core::num::CheckedDiv; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert!(MIN + MAX + 1 == 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_bitwise_operators() { + assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); + assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); + assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); + assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); + assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); + } + + static A: $T = 0b0101100; + static B: $T = 0b0100001; + static C: $T = 0b1111001; + + static _0: $T = 0; + static _1: $T = !0; + + #[test] + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + #[test] + fn test_count_zeros() { + assert!(A.count_zeros() == BITS as $T - 3); + assert!(B.count_zeros() == BITS as $T - 2); + assert!(C.count_zeros() == BITS as $T - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_le() { + assert_eq!(Int::from_le(A.to_le()), A); + assert_eq!(Int::from_le(B.to_le()), B); + assert_eq!(Int::from_le(C.to_le()), C); + assert_eq!(Int::from_le(_0), _0); + assert_eq!(Int::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!(Int::from_be(A.to_be()), A); + assert_eq!(Int::from_be(B.to_be()), B); + assert_eq!(Int::from_be(C.to_be()), C); + assert_eq!(Int::from_be(_0), _0); + assert_eq!(Int::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_unsigned_checked_div() { + assert!(10u.checked_div(&2) == Some(5)); + assert!(5u.checked_div(&0) == None); + } +} +)) diff --git a/src/libcoretest/ops.rs b/src/libcoretest/ops.rs new file mode 100644 index 00000000000..447fd1c699d --- /dev/null +++ b/src/libcoretest/ops.rs @@ -0,0 +1,29 @@ +// 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. + +use test::Bencher; + +// Overhead of dtors + +struct HasDtor { + _x: int +} + +impl Drop for HasDtor { + fn drop(&mut self) { + } +} + +#[bench] +fn alloc_obj_with_dtor(b: &mut Bencher) { + b.iter(|| { + HasDtor { _x : 10 }; + }) +} diff --git a/src/libcoretest/option.rs b/src/libcoretest/option.rs new file mode 100644 index 00000000000..776637f3be9 --- /dev/null +++ b/src/libcoretest/option.rs @@ -0,0 +1,278 @@ +// 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. + +use core::option::*; +use core::kinds::marker; +use core::mem; + +#[test] +fn test_get_ptr() { + unsafe { + let x = box 0i; + let addr_x: *const int = mem::transmute(&*x); + let opt = Some(x); + let y = opt.unwrap(); + let addr_y: *const int = mem::transmute(&*y); + assert_eq!(addr_x, addr_y); + } +} + +#[test] +fn test_get_str() { + let x = "test".to_string(); + let addr_x = x.as_slice().as_ptr(); + let opt = Some(x); + let y = opt.unwrap(); + let addr_y = y.as_slice().as_ptr(); + assert_eq!(addr_x, addr_y); +} + +#[test] +fn test_get_resource() { + use std::rc::Rc; + use core::cell::RefCell; + + struct R { + i: Rc<RefCell<int>>, + } + + #[unsafe_destructor] + impl Drop for R { + fn drop(&mut self) { + let ii = &*self.i; + let i = *ii.borrow(); + *ii.borrow_mut() = i + 1; + } + } + + fn r(i: Rc<RefCell<int>>) -> R { + R { + i: i + } + } + + let i = Rc::new(RefCell::new(0i)); + { + let x = r(i.clone()); + let opt = Some(x); + let _y = opt.unwrap(); + } + assert_eq!(*i.borrow(), 1); +} + +#[test] +fn test_option_dance() { + let x = Some(()); + let mut y = Some(5i); + let mut y2 = 0; + for _x in x.iter() { + y2 = y.take_unwrap(); + } + assert_eq!(y2, 5); + assert!(y.is_none()); +} + +#[test] #[should_fail] +fn test_option_too_much_dance() { + let mut y = Some(marker::NoCopy); + let _y2 = y.take_unwrap(); + let _y3 = y.take_unwrap(); +} + +#[test] +fn test_and() { + let x: Option<int> = Some(1i); + assert_eq!(x.and(Some(2i)), Some(2)); + assert_eq!(x.and(None::<int>), None); + + let x: Option<int> = None; + assert_eq!(x.and(Some(2i)), None); + assert_eq!(x.and(None::<int>), None); +} + +#[test] +fn test_and_then() { + let x: Option<int> = Some(1); + assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); + assert_eq!(x.and_then(|_| None::<int>), None); + + let x: Option<int> = None; + assert_eq!(x.and_then(|x| Some(x + 1)), None); + assert_eq!(x.and_then(|_| None::<int>), None); +} + +#[test] +fn test_or() { + let x: Option<int> = Some(1); + assert_eq!(x.or(Some(2)), Some(1)); + assert_eq!(x.or(None), Some(1)); + + let x: Option<int> = None; + assert_eq!(x.or(Some(2)), Some(2)); + assert_eq!(x.or(None), None); +} + +#[test] +fn test_or_else() { + let x: Option<int> = Some(1); + assert_eq!(x.or_else(|| Some(2)), Some(1)); + assert_eq!(x.or_else(|| None), Some(1)); + + let x: Option<int> = None; + assert_eq!(x.or_else(|| Some(2)), Some(2)); + assert_eq!(x.or_else(|| None), None); +} + +#[test] +fn test_option_while_some() { + let mut i = 0i; + Some(10i).while_some(|j| { + i += 1; + if j > 0 { + Some(j-1) + } else { + None + } + }); + assert_eq!(i, 11); +} + +#[test] +fn test_unwrap() { + assert_eq!(Some(1i).unwrap(), 1); + let s = Some("hello".to_string()).unwrap(); + assert_eq!(s.as_slice(), "hello"); +} + +#[test] +#[should_fail] +fn test_unwrap_fail1() { + let x: Option<int> = None; + x.unwrap(); +} + +#[test] +#[should_fail] +fn test_unwrap_fail2() { + let x: Option<String> = None; + x.unwrap(); +} + +#[test] +fn test_unwrap_or() { + let x: Option<int> = Some(1); + assert_eq!(x.unwrap_or(2), 1); + + let x: Option<int> = None; + assert_eq!(x.unwrap_or(2), 2); +} + +#[test] +fn test_unwrap_or_else() { + let x: Option<int> = Some(1); + assert_eq!(x.unwrap_or_else(|| 2), 1); + + let x: Option<int> = None; + assert_eq!(x.unwrap_or_else(|| 2), 2); +} + +#[test] +fn test_filtered() { + let some_stuff = Some(42i); + let modified_stuff = some_stuff.filtered(|&x| {x < 10}); + assert_eq!(some_stuff.unwrap(), 42); + assert!(modified_stuff.is_none()); +} + +#[test] +fn test_iter() { + let val = 5i; + + let x = Some(val); + let mut it = x.iter(); + + assert_eq!(it.size_hint(), (1, Some(1))); + assert_eq!(it.next(), Some(&val)); + assert_eq!(it.size_hint(), (0, Some(0))); + assert!(it.next().is_none()); +} + +#[test] +fn test_mut_iter() { + let val = 5i; + let new_val = 11i; + + let mut x = Some(val); + { + let mut it = x.mut_iter(); + + assert_eq!(it.size_hint(), (1, Some(1))); + + match it.next() { + Some(interior) => { + assert_eq!(*interior, val); + *interior = new_val; + } + None => assert!(false), + } + + assert_eq!(it.size_hint(), (0, Some(0))); + assert!(it.next().is_none()); + } + assert_eq!(x, Some(new_val)); +} + +#[test] +fn test_ord() { + let small = Some(1.0f64); + let big = Some(5.0f64); + let nan = Some(0.0f64/0.0); + assert!(!(nan < big)); + assert!(!(nan > big)); + assert!(small < big); + assert!(None < big); + assert!(big > None); +} + +#[test] +fn test_mutate() { + let mut x = Some(3i); + assert!(x.mutate(|i| i+1)); + assert_eq!(x, Some(4i)); + assert!(x.mutate_or_set(0, |i| i+1)); + assert_eq!(x, Some(5i)); + x = None; + assert!(!x.mutate(|i| i+1)); + assert_eq!(x, None); + assert!(!x.mutate_or_set(0i, |i| i+1)); + assert_eq!(x, Some(0i)); +} + +#[test] +fn test_collect() { + let v: Option<Vec<int>> = collect(range(0i, 0) + .map(|_| Some(0i))); + assert!(v == Some(vec![])); + + let v: Option<Vec<int>> = collect(range(0i, 3) + .map(|x| Some(x))); + assert!(v == Some(vec![0, 1, 2])); + + let v: Option<Vec<int>> = collect(range(0i, 3) + .map(|x| if x > 1 { None } else { Some(x) })); + assert!(v == None); + + // test that it does not take more elements than it needs + let mut functions = [|| Some(()), || None, || fail!()]; + + let v: Option<Vec<()>> = collect(functions.mut_iter().map(|f| (*f)())); + + assert!(v == None); +} diff --git a/src/libcoretest/ptr.rs b/src/libcoretest/ptr.rs new file mode 100644 index 00000000000..2a4ef5e275d --- /dev/null +++ b/src/libcoretest/ptr.rs @@ -0,0 +1,255 @@ +// 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. +#![allow(deprecated)] +use core::ptr::*; +use libc::c_char; +use core::mem; +use std::str; +use libc; + +#[test] +fn test() { + unsafe { + struct Pair { + fst: int, + snd: int + }; + let mut p = Pair {fst: 10, snd: 20}; + let pptr: *mut Pair = &mut p; + let iptr: *mut int = mem::transmute(pptr); + assert_eq!(*iptr, 10); + *iptr = 30; + assert_eq!(*iptr, 30); + assert_eq!(p.fst, 30); + + *pptr = Pair {fst: 50, snd: 60}; + assert_eq!(*iptr, 50); + assert_eq!(p.fst, 50); + assert_eq!(p.snd, 60); + + let v0 = vec![32000u16, 32001u16, 32002u16]; + let mut v1 = vec![0u16, 0u16, 0u16]; + + copy_memory(v1.as_mut_ptr().offset(1), + v0.as_ptr().offset(1), 1); + assert!((*v1.get(0) == 0u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 0u16)); + copy_memory(v1.as_mut_ptr(), + v0.as_ptr().offset(2), 1); + assert!((*v1.get(0) == 32002u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 0u16)); + copy_memory(v1.as_mut_ptr().offset(2), + v0.as_ptr(), 1u); + assert!((*v1.get(0) == 32002u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 32000u16)); + } +} + +#[test] +fn test_position() { + use libc::c_char; + + "hello".with_c_str(|p| { + unsafe { + assert!(2u == position(p, |c| *c == 'l' as c_char)); + assert!(4u == position(p, |c| *c == 'o' as c_char)); + assert!(5u == position(p, |c| *c == 0 as c_char)); + } + }) +} + +#[test] +fn test_buf_len() { + "hello".with_c_str(|p0| { + "there".with_c_str(|p1| { + "thing".with_c_str(|p2| { + let v = vec![p0, p1, p2, null()]; + unsafe { + assert_eq!(buf_len(v.as_ptr()), 3u); + } + }) + }) + }) +} + +#[test] +fn test_is_null() { + let p: *const int = null(); + assert!(p.is_null()); + assert!(!p.is_not_null()); + + let q = unsafe { p.offset(1) }; + assert!(!q.is_null()); + assert!(q.is_not_null()); + + let mp: *mut int = mut_null(); + assert!(mp.is_null()); + assert!(!mp.is_not_null()); + + let mq = unsafe { mp.offset(1) }; + assert!(!mq.is_null()); + assert!(mq.is_not_null()); +} + +#[test] +fn test_to_option() { + unsafe { + let p: *const int = null(); + assert_eq!(p.to_option(), None); + + let q: *const int = &2; + assert_eq!(q.to_option().unwrap(), &2); + + let p: *mut int = mut_null(); + assert_eq!(p.to_option(), None); + + let q: *mut int = &mut 2; + assert_eq!(q.to_option().unwrap(), &2); + } +} + +#[test] +fn test_ptr_addition() { + unsafe { + let xs = Vec::from_elem(16, 5i); + let mut ptr = xs.as_ptr(); + let end = ptr.offset(16); + + while ptr < end { + assert_eq!(*ptr, 5); + ptr = ptr.offset(1); + } + + let mut xs_mut = xs; + let mut m_ptr = xs_mut.as_mut_ptr(); + let m_end = m_ptr.offset(16); + + while m_ptr < m_end { + *m_ptr += 5; + m_ptr = m_ptr.offset(1); + } + + assert!(xs_mut == Vec::from_elem(16, 10i)); + } +} + +#[test] +fn test_ptr_subtraction() { + unsafe { + let xs = vec![0,1,2,3,4,5,6,7,8,9]; + let mut idx = 9i8; + let ptr = xs.as_ptr(); + + while idx >= 0i8 { + assert_eq!(*(ptr.offset(idx as int)), idx as int); + idx = idx - 1i8; + } + + let mut xs_mut = xs; + let m_start = xs_mut.as_mut_ptr(); + let mut m_ptr = m_start.offset(9); + + while m_ptr >= m_start { + *m_ptr += *m_ptr; + m_ptr = m_ptr.offset(-1); + } + + assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]); + } +} + +#[test] +fn test_ptr_array_each_with_len() { + unsafe { + let one = "oneOne".to_c_str(); + let two = "twoTwo".to_c_str(); + let three = "threeThree".to_c_str(); + let arr = vec![ + one.as_ptr(), + two.as_ptr(), + three.as_ptr() + ]; + let expected_arr = [ + one, two, three + ]; + + let mut ctr = 0; + let mut iteration_count = 0; + array_each_with_len(arr.as_ptr(), arr.len(), |e| { + let actual = str::raw::from_c_str(e); + let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); + assert_eq!(actual.as_slice(), expected.as_slice()); + ctr += 1; + iteration_count += 1; + }); + assert_eq!(iteration_count, 3u); + } +} + +#[test] +fn test_ptr_array_each() { + unsafe { + let one = "oneOne".to_c_str(); + let two = "twoTwo".to_c_str(); + let three = "threeThree".to_c_str(); + let arr = vec![ + one.as_ptr(), + two.as_ptr(), + three.as_ptr(), + // fake a null terminator + null() + ]; + let expected_arr = [ + one, two, three + ]; + + let arr_ptr = arr.as_ptr(); + let mut ctr = 0u; + let mut iteration_count = 0u; + array_each(arr_ptr, |e| { + let actual = str::raw::from_c_str(e); + let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); + assert_eq!(actual.as_slice(), expected.as_slice()); + ctr += 1; + iteration_count += 1; + }); + assert_eq!(iteration_count, 3); + } +} + +#[test] +#[should_fail] +fn test_ptr_array_each_with_len_null_ptr() { + unsafe { + array_each_with_len(0 as *const *const libc::c_char, 1, |e| { + str::raw::from_c_str(e); + }); + } +} +#[test] +#[should_fail] +fn test_ptr_array_each_null_ptr() { + unsafe { + array_each(0 as *const *const libc::c_char, |e| { + str::raw::from_c_str(e); + }); + } +} + +#[test] +fn test_set_memory() { + let mut xs = [0u8, ..20]; + let ptr = xs.as_mut_ptr(); + unsafe { set_memory(ptr, 5u8, xs.len()); } + assert!(xs == [5u8, ..20]); +} diff --git a/src/libcoretest/raw.rs b/src/libcoretest/raw.rs new file mode 100644 index 00000000000..f2c23c7c773 --- /dev/null +++ b/src/libcoretest/raw.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. + +use core::raw::*; +use core::mem; + +#[test] +fn synthesize_closure() { + unsafe { + let x = 10; + let f: |int| -> int = |y| x + y; + + assert_eq!(f(20), 30); + + let original_closure: Closure = mem::transmute(f); + + let actual_function_pointer = original_closure.code; + let environment = original_closure.env; + + let new_closure = Closure { + code: actual_function_pointer, + env: environment + }; + + let new_f: |int| -> int = mem::transmute(new_closure); + assert_eq!(new_f(20), 30); + } +} diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs new file mode 100644 index 00000000000..7c7e0a542cd --- /dev/null +++ b/src/libcoretest/result.rs @@ -0,0 +1,161 @@ +// 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. + +use core::result::{collect, fold, fold_}; +use core::iter::range; + +pub fn op1() -> Result<int, &'static str> { Ok(666) } +pub fn op2() -> Result<int, &'static str> { Err("sadface") } + +#[test] +pub fn test_and() { + assert_eq!(op1().and(Ok(667i)).unwrap(), 667); + assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), + "bad"); + + assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); + assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_and_then() { + assert_eq!(op1().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap(), 667); + assert_eq!(op1().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(), + "bad"); + + assert_eq!(op2().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap_err(), + "sadface"); + assert_eq!(op2().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_or() { + assert_eq!(op1().or(Ok(667)).unwrap(), 666); + assert_eq!(op1().or(Err("bad")).unwrap(), 666); + + assert_eq!(op2().or(Ok(667)).unwrap(), 667); + assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad"); +} + +#[test] +pub fn test_or_else() { + assert_eq!(op1().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 666); + assert_eq!(op1().or_else(|e| Err::<int, &'static str>(e)).unwrap(), 666); + + assert_eq!(op2().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 667); + assert_eq!(op2().or_else(|e| Err::<int, &'static str>(e)).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_impl_map() { + assert!(Ok::<int, int>(1).map(|x| x + 1) == Ok(2)); + assert!(Err::<int, int>(1).map(|x| x + 1) == Err(1)); +} + +#[test] +pub fn test_impl_map_err() { + assert!(Ok::<int, int>(1).map_err(|x| x + 1) == Ok(1)); + assert!(Err::<int, int>(1).map_err(|x| x + 1) == Err(2)); +} + +#[test] +fn test_collect() { + let v: Result<Vec<int>, ()> = collect(range(0i, 0).map(|_| Ok::<int, ()>(0))); + assert!(v == Ok(vec![])); + + let v: Result<Vec<int>, ()> = collect(range(0i, 3).map(|x| Ok::<int, ()>(x))); + assert!(v == Ok(vec![0, 1, 2])); + + let v: Result<Vec<int>, int> = collect(range(0i, 3) + .map(|x| if x > 1 { Err(x) } else { Ok(x) })); + assert!(v == Err(2)); + + // test that it does not take more elements than it needs + let mut functions = [|| Ok(()), || Err(1i), || fail!()]; + + let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)())); + assert!(v == Err(1)); +} + +#[test] +fn test_fold() { + assert_eq!(fold_(range(0i, 0) + .map(|_| Ok::<(), ()>(()))), + Ok(())); + assert_eq!(fold(range(0i, 3) + .map(|x| Ok::<int, ()>(x)), + 0, |a, b| a + b), + Ok(3)); + assert_eq!(fold_(range(0i, 3) + .map(|x| if x > 1 { Err(x) } else { Ok(()) })), + Err(2)); + + // test that it does not take more elements than it needs + let mut functions = [|| Ok(()), || Err(1i), || fail!()]; + + assert_eq!(fold_(functions.mut_iter() + .map(|f| (*f)())), + Err(1)); +} + +#[test] +pub fn test_fmt_default() { + let ok: Result<int, &'static str> = Ok(100); + let err: Result<int, &'static str> = Err("Err"); + + let s = format!("{}", ok); + assert_eq!(s.as_slice(), "Ok(100)"); + let s = format!("{}", err); + assert_eq!(s.as_slice(), "Err(Err)"); +} + +#[test] +pub fn test_unwrap_or() { + let ok: Result<int, &'static str> = Ok(100i); + let ok_err: Result<int, &'static str> = Err("Err"); + + assert_eq!(ok.unwrap_or(50), 100); + assert_eq!(ok_err.unwrap_or(50), 50); +} + +#[test] +pub fn test_unwrap_or_else() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { + 50i + } else { + fail!("BadBad") + } + } + + let ok: Result<int, &'static str> = Ok(100); + let ok_err: Result<int, &'static str> = Err("I got this."); + + assert_eq!(ok.unwrap_or_else(handler), 100); + assert_eq!(ok_err.unwrap_or_else(handler), 50); +} + +#[test] +#[should_fail] +pub fn test_unwrap_or_else_failure() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { + 50i + } else { + fail!("BadBad") + } + } + + let bad_err: Result<int, &'static str> = Err("Unrecoverable mess."); + let _ : int = bad_err.unwrap_or_else(handler); +} diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs new file mode 100644 index 00000000000..be71e42ae9a --- /dev/null +++ b/src/libcoretest/tuple.rs @@ -0,0 +1,92 @@ +// 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. + +#[test] +fn test_clone() { + let a = (1i, "2"); + let b = a.clone(); + assert_eq!(a, b); +} + +#[test] +fn test_getters() { + macro_rules! test_getter( + ($x:expr, $valN:ident, $refN:ident, $mutN:ident, + $init:expr, $incr:expr, $result:expr) => ({ + assert_eq!($x.$valN(), $init); + assert_eq!(*$x.$refN(), $init); + *$x.$mutN() += $incr; + assert_eq!(*$x.$refN(), $result); + }) + ) + let mut x = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); + test_getter!(x, val0, ref0, mut0, 0, 1, 1); + test_getter!(x, val1, ref1, mut1, 1, 1, 2); + test_getter!(x, val2, ref2, mut2, 2, 1, 3); + test_getter!(x, val3, ref3, mut3, 3, 1, 4); + test_getter!(x, val4, ref4, mut4, 4, 1, 5); + test_getter!(x, val5, ref5, mut5, 5, 1, 6); + test_getter!(x, val6, ref6, mut6, 6, 1, 7); + test_getter!(x, val7, ref7, mut7, 7, 1, 8); + test_getter!(x, val8, ref8, mut8, 8, 1, 9); + test_getter!(x, val9, ref9, mut9, 9, 1, 10); + test_getter!(x, val10, ref10, mut10, 10.0, 1.0, 11.0); + test_getter!(x, val11, ref11, mut11, 11.0, 1.0, 12.0); +} + +#[test] +fn test_tuple_cmp() { + let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u)); + + let nan = 0.0f64/0.0; + + // PartialEq + assert_eq!(small, small); + assert_eq!(big, big); + assert!(small != big); + assert!(big != small); + + // PartialOrd + assert!(small < big); + assert!(!(small < small)); + assert!(!(big < small)); + assert!(!(big < big)); + + assert!(small <= small); + assert!(big <= big); + + assert!(big > small); + assert!(small >= small); + assert!(big >= small); + assert!(big >= big); + + assert!(!((1.0f64, 2.0f64) < (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) <= (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) > (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) >= (nan, 3.0))); + assert!(((1.0f64, 2.0f64) < (2.0, nan))); + assert!(!((2.0f64, 2.0f64) < (2.0, nan))); + + // Ord + assert!(small.cmp(&small) == Equal); + assert!(big.cmp(&big) == Equal); + assert!(small.cmp(&big) == Less); + assert!(big.cmp(&small) == Greater); +} + +#[test] +fn test_show() { + let s = format!("{}", (1i,)); + assert_eq!(s.as_slice(), "(1,)"); + let s = format!("{}", (1i, true)); + assert_eq!(s.as_slice(), "(1, true)"); + let s = format!("{}", (1i, "hi", true)); + assert_eq!(s.as_slice(), "(1, hi, true)"); +} diff --git a/src/libdebug/reflect.rs b/src/libdebug/reflect.rs index 280e8753b34..0cbae6ee2d3 100644 --- a/src/libdebug/reflect.rs +++ b/src/libdebug/reflect.rs @@ -28,7 +28,7 @@ use std::gc::Gc; * as `TyVisitor`; then build a MovePtrAdaptor wrapped around your struct. */ pub trait MovePtr { - fn move_ptr(&mut self, adjustment: |*u8| -> *u8); + fn move_ptr(&mut self, adjustment: |*const u8| -> *const u8); fn push_ptr(&mut self); fn pop_ptr(&mut self); } @@ -51,12 +51,12 @@ impl<V:TyVisitor + MovePtr> MovePtrAdaptor<V> { #[inline] pub fn bump(&mut self, sz: uint) { - self.inner.move_ptr(|p| ((p as uint) + sz) as *u8) + self.inner.move_ptr(|p| ((p as uint) + sz) as *const u8) } #[inline] pub fn align(&mut self, a: uint) { - self.inner.move_ptr(|p| align(p as uint, a) as *u8) + self.inner.move_ptr(|p| align(p as uint, a) as *const u8) } #[inline] @@ -202,35 +202,35 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { true } - fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_box(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { self.align_to::<Gc<u8>>(); if ! self.inner.visit_box(mtbl, inner) { return false; } self.bump_past::<Gc<u8>>(); true } - fn visit_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_uniq(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { self.align_to::<Box<u8>>(); if ! self.inner.visit_uniq(mtbl, inner) { return false; } self.bump_past::<Box<u8>>(); true } - fn visit_ptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool { - self.align_to::<*u8>(); + fn visit_ptr(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { + self.align_to::<*const u8>(); if ! self.inner.visit_ptr(mtbl, inner) { return false; } - self.bump_past::<*u8>(); + self.bump_past::<*const u8>(); true } - fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_rptr(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { self.align_to::<&'static u8>(); if ! self.inner.visit_rptr(mtbl, inner) { return false; } self.bump_past::<&'static u8>(); true } - fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_evec_slice(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { self.align_to::<&'static [u8]>(); if ! self.inner.visit_evec_slice(mtbl, inner) { return false; } self.bump_past::<&'static [u8]>(); @@ -238,7 +238,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { } fn visit_evec_fixed(&mut self, n: uint, sz: uint, align: uint, - mtbl: uint, inner: *TyDesc) -> bool { + mtbl: uint, inner: *const TyDesc) -> bool { self.align(align); if ! self.inner.visit_evec_fixed(n, sz, align, mtbl, inner) { return false; @@ -254,7 +254,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { } fn visit_rec_field(&mut self, i: uint, name: &str, - mtbl: uint, inner: *TyDesc) -> bool { + mtbl: uint, inner: *const TyDesc) -> bool { unsafe { self.align((*inner).align); } if ! self.inner.visit_rec_field(i, name, mtbl, inner) { return false; @@ -278,7 +278,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { } fn visit_class_field(&mut self, i: uint, name: &str, named: bool, mtbl: uint, - inner: *TyDesc) -> bool { + inner: *const TyDesc) -> bool { unsafe { self.align((*inner).align); } if ! self.inner.visit_class_field(i, name, named, mtbl, inner) { return false; @@ -301,7 +301,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { true } - fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool { + fn visit_tup_field(&mut self, i: uint, inner: *const TyDesc) -> bool { unsafe { self.align((*inner).align); } if ! self.inner.visit_tup_field(i, inner) { return false; } unsafe { self.bump((*inner).size); } @@ -321,12 +321,14 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { true } - fn visit_fn_input(&mut self, i: uint, mode: uint, inner: *TyDesc) -> bool { + fn visit_fn_input(&mut self, i: uint, mode: uint, + inner: *const TyDesc) -> bool { if ! self.inner.visit_fn_input(i, mode, inner) { return false; } true } - fn visit_fn_output(&mut self, retstyle: uint, variadic: bool, inner: *TyDesc) -> bool { + fn visit_fn_output(&mut self, retstyle: uint, variadic: bool, + inner: *const TyDesc) -> bool { if ! self.inner.visit_fn_output(retstyle, variadic, inner) { return false; } true } @@ -340,7 +342,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { } fn visit_enter_enum(&mut self, n_variants: uint, - get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, sz: uint, align: uint) -> bool { self.align(align); @@ -361,7 +363,8 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { true } - fn visit_enum_variant_field(&mut self, i: uint, offset: uint, inner: *TyDesc) -> bool { + fn visit_enum_variant_field(&mut self, i: uint, offset: uint, + inner: *const TyDesc) -> bool { self.inner.push_ptr(); self.bump(offset); if ! self.inner.visit_enum_variant_field(i, offset, inner) { return false; } @@ -381,7 +384,7 @@ impl<V:TyVisitor + MovePtr> TyVisitor for MovePtrAdaptor<V> { } fn visit_leave_enum(&mut self, n_variants: uint, - get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, sz: uint, align: uint) -> bool { if ! self.inner.visit_leave_enum(n_variants, get_disr, sz, align) { return false; diff --git a/src/libdebug/repr.rs b/src/libdebug/repr.rs index 6562e2fb6e3..133353ec3d7 100644 --- a/src/libdebug/repr.rs +++ b/src/libdebug/repr.rs @@ -92,8 +92,8 @@ enum VariantState { } pub struct ReprVisitor<'a> { - ptr: *u8, - ptr_stk: Vec<*u8>, + ptr: *const u8, + ptr_stk: Vec<*const u8>, var_stk: Vec<VariantState>, writer: &'a mut io::Writer, last_err: Option<io::IoError>, @@ -101,7 +101,7 @@ pub struct ReprVisitor<'a> { impl<'a> MovePtr for ReprVisitor<'a> { #[inline] - fn move_ptr(&mut self, adjustment: |*u8| -> *u8) { + fn move_ptr(&mut self, adjustment: |*const u8| -> *const u8) { self.ptr = adjustment(self.ptr); } fn push_ptr(&mut self) { @@ -114,7 +114,7 @@ impl<'a> MovePtr for ReprVisitor<'a> { impl<'a> ReprVisitor<'a> { // Various helpers for the TyVisitor impl - pub fn new(ptr: *u8, writer: &'a mut io::Writer) -> ReprVisitor<'a> { + pub fn new(ptr: *const u8, writer: &'a mut io::Writer) -> ReprVisitor<'a> { ReprVisitor { ptr: ptr, ptr_stk: vec!(), @@ -128,18 +128,19 @@ impl<'a> ReprVisitor<'a> { pub fn get<T>(&mut self, f: |&mut ReprVisitor, &T| -> bool) -> bool { unsafe { let ptr = self.ptr; - f(self, mem::transmute::<*u8,&T>(ptr)) + f(self, mem::transmute::<*const u8,&T>(ptr)) } } #[inline] - pub fn visit_inner(&mut self, inner: *TyDesc) -> bool { + pub fn visit_inner(&mut self, inner: *const TyDesc) -> bool { let ptr = self.ptr; self.visit_ptr_inner(ptr, inner) } #[inline] - pub fn visit_ptr_inner(&mut self, ptr: *u8, inner: *TyDesc) -> bool { + pub fn visit_ptr_inner(&mut self, ptr: *const u8, + inner: *const TyDesc) -> bool { unsafe { let u = ReprVisitor::new(ptr, mem::transmute_copy(&self.writer)); let mut v = reflect::MovePtrAdaptor::new(u); @@ -183,8 +184,9 @@ impl<'a> ReprVisitor<'a> { true } - pub fn write_vec_range(&mut self, ptr: *(), len: uint, inner: *TyDesc) -> bool { - let mut p = ptr as *u8; + pub fn write_vec_range(&mut self, ptr: *const (), len: uint, + inner: *const TyDesc) -> bool { + let mut p = ptr as *const u8; let (sz, al) = unsafe { ((*inner).size, (*inner).align) }; try!(self, self.writer.write(['[' as u8])); let mut first = true; @@ -197,8 +199,8 @@ impl<'a> ReprVisitor<'a> { } else { try!(self, self.writer.write(", ".as_bytes())); } - self.visit_ptr_inner(p as *u8, inner); - p = align(unsafe { p.offset(sz as int) as uint }, al) as *u8; + self.visit_ptr_inner(p as *const u8, inner); + p = align(unsafe { p.offset(sz as int) as uint }, al) as *const u8; left -= dec; } try!(self, self.writer.write([']' as u8])); @@ -276,40 +278,46 @@ impl<'a> TyVisitor for ReprVisitor<'a> { fn visit_estr_fixed(&mut self, _n: uint, _sz: uint, _align: uint) -> bool { fail!(); } - fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_box(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { try!(self, self.writer.write("box(GC) ".as_bytes())); self.write_mut_qualifier(mtbl); self.get::<&raw::Box<()>>(|this, b| { - let p = &b.data as *() as *u8; + let p = &b.data as *const () as *const u8; this.visit_ptr_inner(p, inner) }) } - fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool { + fn visit_uniq(&mut self, _mtbl: uint, inner: *const TyDesc) -> bool { try!(self, self.writer.write("box ".as_bytes())); - self.get::<*u8>(|this, b| { + self.get::<*const u8>(|this, b| { this.visit_ptr_inner(*b, inner) }) } - fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool { - self.get::<*u8>(|this, p| { + fn visit_ptr(&mut self, mtbl: uint, _inner: *const TyDesc) -> bool { + self.get::<*const u8>(|this, p| { try!(this, write!(this.writer, "({} as *", *p)); - this.write_mut_qualifier(mtbl); + if mtbl == 0 { + try!(this, this.writer.write("mut ".as_bytes())); + } else if mtbl == 1 { + try!(this, this.writer.write("const ".as_bytes())); + } else { + fail!("invalid mutability value"); + } try!(this, this.writer.write("())".as_bytes())); true }) } - fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_rptr(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { try!(self, self.writer.write(['&' as u8])); self.write_mut_qualifier(mtbl); - self.get::<*u8>(|this, p| { + self.get::<*const u8>(|this, p| { this.visit_ptr_inner(*p, inner) }) } - fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool { + fn visit_evec_slice(&mut self, mtbl: uint, inner: *const TyDesc) -> bool { self.get::<raw::Slice<()>>(|this, s| { try!(this, this.writer.write(['&' as u8])); this.write_mut_qualifier(mtbl); @@ -321,7 +329,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { } fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint, - _: uint, inner: *TyDesc) -> bool { + _: uint, inner: *const TyDesc) -> bool { let assumed_size = if sz == 0 { n } else { sz }; self.get::<()>(|this, b| { this.write_vec_range(b, assumed_size, inner) @@ -335,7 +343,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { } fn visit_rec_field(&mut self, i: uint, name: &str, - mtbl: uint, inner: *TyDesc) -> bool { + mtbl: uint, inner: *const TyDesc) -> bool { if i != 0 { try!(self, self.writer.write(", ".as_bytes())); } @@ -366,7 +374,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { } fn visit_class_field(&mut self, i: uint, name: &str, named: bool, - _mtbl: uint, inner: *TyDesc) -> bool { + _mtbl: uint, inner: *const TyDesc) -> bool { if i != 0 { try!(self, self.writer.write(", ".as_bytes())); } @@ -396,7 +404,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { true } - fn visit_tup_field(&mut self, i: uint, inner: *TyDesc) -> bool { + fn visit_tup_field(&mut self, i: uint, inner: *const TyDesc) -> bool { if i != 0 { try!(self, self.writer.write(", ".as_bytes())); } @@ -415,7 +423,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { fn visit_enter_enum(&mut self, _n_variants: uint, - get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, _sz: uint, _align: uint) -> bool { let disr = unsafe { @@ -456,7 +464,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { fn visit_enum_variant_field(&mut self, i: uint, _offset: uint, - inner: *TyDesc) + inner: *const TyDesc) -> bool { match *self.var_stk.get(self.var_stk.len() - 1) { Matched => { @@ -489,7 +497,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { fn visit_leave_enum(&mut self, _n_variants: uint, - _get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + _get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, _sz: uint, _align: uint) -> bool { @@ -505,7 +513,8 @@ impl<'a> TyVisitor for ReprVisitor<'a> { true } - fn visit_fn_input(&mut self, i: uint, _mode: uint, inner: *TyDesc) -> bool { + fn visit_fn_input(&mut self, i: uint, _mode: uint, + inner: *const TyDesc) -> bool { if i != 0 { try!(self, self.writer.write(", ".as_bytes())); } @@ -515,7 +524,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { } fn visit_fn_output(&mut self, _retstyle: uint, variadic: bool, - inner: *TyDesc) -> bool { + inner: *const TyDesc) -> bool { if variadic { try!(self, self.writer.write(", ...".as_bytes())); } @@ -543,7 +552,7 @@ impl<'a> TyVisitor for ReprVisitor<'a> { pub fn write_repr<T>(writer: &mut io::Writer, object: &T) -> io::IoResult<()> { unsafe { - let ptr = object as *T as *u8; + let ptr = object as *const T as *const u8; let tydesc = get_tydesc::<T>(); let u = ReprVisitor::new(ptr, writer); let mut v = reflect::MovePtrAdaptor::new(u); @@ -579,22 +588,22 @@ fn test_repr() { assert_eq!(s.as_slice(), e); } - exact_test(&10, "10"); + exact_test(&10i, "10"); exact_test(&true, "true"); exact_test(&false, "false"); - exact_test(&1.234, "1.234f64"); + exact_test(&1.234f64, "1.234f64"); exact_test(&("hello"), "\"hello\""); - exact_test(&(box(GC) 10), "box(GC) 10"); - exact_test(&(box 10), "box 10"); - exact_test(&(&10), "&10"); - let mut x = 10; + exact_test(&(box(GC) 10i), "box(GC) 10"); + exact_test(&(box 10i), "box 10"); + exact_test(&(&10i), "&10"); + let mut x = 10i; exact_test(&(&mut x), "&mut 10"); - exact_test(&(0 as *()), "(0x0 as *())"); - exact_test(&(0 as *mut ()), "(0x0 as *mut ())"); + exact_test(&(0i as *const()), "(0x0 as *const ())"); + exact_test(&(0i as *mut ()), "(0x0 as *mut ())"); - exact_test(&(1,), "(1,)"); + exact_test(&(1i,), "(1,)"); exact_test(&(&["hi", "there"]), "&[\"hi\", \"there\"]"); exact_test(&(P{a:10, b:1.234}), @@ -604,8 +613,8 @@ fn test_repr() { exact_test(&(box P{a:10, b:1.234}), "box repr::P{a: 10, b: 1.234f64}"); - exact_test(&(&[1, 2]), "&[1, 2]"); - exact_test(&(&mut [1, 2]), "&mut [1, 2]"); + exact_test(&(&[1i, 2i]), "&[1, 2]"); + exact_test(&(&mut [1i, 2i]), "&mut [1, 2]"); exact_test(&'\'', "'\\''"); exact_test(&'"', "'\"'"); diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index 7d0ae03c878..d944818abc5 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -38,18 +38,18 @@ use libc::{c_void, size_t, c_int}; #[link(name = "miniz", kind = "static")] extern { /// Raw miniz compression function. - fn tdefl_compress_mem_to_heap(psrc_buf: *c_void, - src_buf_len: size_t, - pout_len: *mut size_t, - flags: c_int) - -> *mut c_void; + fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void, + src_buf_len: size_t, + pout_len: *mut size_t, + flags: c_int) + -> *mut c_void; /// Raw miniz decompression function. - fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void, - src_buf_len: size_t, - pout_len: *mut size_t, - flags: c_int) - -> *mut c_void; + fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void, + src_buf_len: size_t, + pout_len: *mut size_t, + flags: c_int) + -> *mut c_void; } static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal" @@ -59,10 +59,10 @@ static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> { unsafe { let mut outsz : size_t = 0; - let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void, - bytes.len() as size_t, - &mut outsz, - flags); + let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _, + bytes.len() as size_t, + &mut outsz, + flags); if !res.is_null() { Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))) } else { @@ -84,10 +84,10 @@ pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> { fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> { unsafe { let mut outsz : size_t = 0; - let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void, - bytes.len() as size_t, - &mut outsz, - flags); + let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _, + bytes.len() as size_t, + &mut outsz, + flags); if !res.is_null() { Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))) } else { diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index ccb1adf93de..00e6df9ffbb 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -370,7 +370,7 @@ impl Matches { } fn is_arg(arg: &str) -> bool { - arg.len() > 1 && arg[0] == '-' as u8 + arg.len() > 1 && arg.as_bytes()[0] == '-' as u8 } fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> { @@ -553,7 +553,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { } else { let mut names; let mut i_arg = None; - if cur.as_slice()[1] == '-' as u8 { + if cur.as_bytes()[1] == '-' as u8 { let tail = cur.as_slice().slice(2, curlen); let tail_eq: Vec<&str> = tail.split('=').collect(); if tail_eq.len() <= 1 { diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index a34791f470e..bd19f19cec6 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -8,8 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::collections::Collection; +use std::default::Default; use std::fmt; use std::iter::FromIterator; +use std::path::BytesContainer; use std::slice; // Note 1: It is not clear whether the flexibility of providing both @@ -61,6 +64,32 @@ impl<'a,T> MaybeOwnedVector<'a,T> { } } +impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> { + fn eq(&self, other: &MaybeOwnedVector<T>) -> bool { + self.as_slice() == other.as_slice() + } +} + +impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {} + +impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> { + fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> { + self.as_slice().partial_cmp(&other.as_slice()) + } +} + +impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> { + fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering { + self.as_slice().cmp(&other.as_slice()) + } +} + +impl<'a, T: PartialEq, V: Vector<T>> Equiv<V> for MaybeOwnedVector<'a, T> { + fn equiv(&self, other: &V) -> bool { + self.as_slice() == other.as_slice() + } +} + // The `Vector` trait is provided in the prelude and is implemented on // both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it // seamlessly. The other vector related traits from the prelude do @@ -108,6 +137,34 @@ impl<'a,T:Clone> CloneableVector<T> for MaybeOwnedVector<'a,T> { } } +impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> { + fn clone(&self) -> MaybeOwnedVector<'a, T> { + match *self { + Growable(ref v) => Growable(v.to_owned()), + Borrowed(v) => Borrowed(v) + } + } +} + + +impl<'a, T> Default for MaybeOwnedVector<'a, T> { + fn default() -> MaybeOwnedVector<'a, T> { + Growable(Vec::new()) + } +} + +impl<'a, T> Collection for MaybeOwnedVector<'a, T> { + fn len(&self) -> uint { + self.as_slice().len() + } +} + +impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> { + fn container_as_bytes<'a>(&'a self) -> &'a [u8] { + self.as_slice() + } +} + impl<'a,T:Clone> MaybeOwnedVector<'a,T> { /// Convert `self` into a growable `Vec`, not making a copy if possible. pub fn into_vec(self) -> Vec<T> { diff --git a/src/libgreen/context.rs b/src/libgreen/context.rs index f11a1d2c667..8c60f3d9fe1 100644 --- a/src/libgreen/context.rs +++ b/src/libgreen/context.rs @@ -27,7 +27,7 @@ pub struct Context { stack_bounds: Option<(uint, uint)>, } -pub type InitFn = extern "C" fn(uint, *(), *()) -> !; +pub type InitFn = extern "C" fn(uint, *mut (), *mut ()) -> !; impl Context { pub fn empty() -> Context { @@ -49,7 +49,7 @@ impl Context { pub fn new(init: InitFn, arg: uint, start: proc():Send, stack: &mut Stack) -> Context { - let sp: *uint = stack.end(); + let sp: *const uint = stack.end(); let sp: *mut uint = sp as *mut uint; // Save and then immediately load the current context, // which we will then modify to call the given function when restored @@ -66,7 +66,7 @@ impl Context { // them in terms of the code running on them (and hopefully they don't // overflow). Additionally, their coroutine stacks are listed as being // zero-length, so that's how we detect what's what here. - let stack_base: *uint = stack.start(); + let stack_base: *const uint = stack.start(); let bounds = if sp as uint == stack_base as uint { None } else { @@ -116,7 +116,7 @@ impl Context { #[link(name = "context_switch", kind = "static")] extern { - fn rust_swap_registers(out_regs: *mut Registers, in_regs: *Registers); + fn rust_swap_registers(out_regs: *mut Registers, in_regs: *const Registers); } // Register contexts used in various architectures diff --git a/src/libgreen/lib.rs b/src/libgreen/lib.rs index 1d23b0f1832..1b34679b0a1 100644 --- a/src/libgreen/lib.rs +++ b/src/libgreen/lib.rs @@ -116,7 +116,7 @@ //! extern crate green; //! //! #[start] -//! fn start(argc: int, argv: **u8) -> int { +//! fn start(argc: int, argv: *const *const u8) -> int { //! green::start(argc, argv, green::basic::event_loop, main) //! } //! @@ -135,7 +135,7 @@ //! extern crate rustuv; //! //! #[start] -//! fn start(argc: int, argv: **u8) -> int { +//! fn start(argc: int, argv: *const *const u8) -> int { //! green::start(argc, argv, rustuv::event_loop, main) //! } //! @@ -267,7 +267,7 @@ macro_rules! green_start( ($f:ident) => ( extern crate rustuv; #[start] - fn start(argc: int, argv: **u8) -> int { + fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, super::$f) } } @@ -291,7 +291,7 @@ macro_rules! green_start( ($f:ident) => ( /// /// The return value is used as the process return code. 0 on success, 101 on /// error. -pub fn start(argc: int, argv: **u8, +pub fn start(argc: int, argv: *const *const u8, event_loop_factory: fn() -> Box<rtio::EventLoop + Send>, main: proc():Send) -> int { rt::init(argc, argv); diff --git a/src/libgreen/sched.rs b/src/libgreen/sched.rs index f8272e5f237..7603b0a8013 100644 --- a/src/libgreen/sched.rs +++ b/src/libgreen/sched.rs @@ -611,13 +611,13 @@ impl Scheduler { // old task as inputs. pub fn change_task_context(mut ~self, - current_task: Box<GreenTask>, + mut current_task: Box<GreenTask>, mut next_task: Box<GreenTask>, f: |&mut Scheduler, Box<GreenTask>|) -> Box<GreenTask> { let f_opaque = ClosureConverter::from_fn(f); - let current_task_dupe = &*current_task as *GreenTask; + let current_task_dupe = &mut *current_task as *mut GreenTask; // The current task is placed inside an enum with the cleanup // function. This enum is then placed inside the scheduler. @@ -871,7 +871,7 @@ impl Scheduler { // * Utility Functions - pub fn sched_id(&self) -> uint { self as *Scheduler as uint } + pub fn sched_id(&self) -> uint { self as *const Scheduler as uint } pub fn run_cleanup_job(&mut self) { let cleanup_job = self.cleanup_job.take_unwrap(); @@ -1413,7 +1413,7 @@ mod test { impl Drop for S { fn drop(&mut self) { - let _foo = box 0; + let _foo = box 0i; } } diff --git a/src/libgreen/simple.rs b/src/libgreen/simple.rs index 7b738ed9c7c..874ddbfe7ed 100644 --- a/src/libgreen/simple.rs +++ b/src/libgreen/simple.rs @@ -32,7 +32,7 @@ impl Runtime for SimpleTask { assert!(times == 1); let me = &mut *self as *mut SimpleTask; - let cur_dupe = &*cur_task as *Task; + let cur_dupe = &mut *cur_task as *mut Task; cur_task.put_runtime(self); let task = BlockedTask::block(cur_task); diff --git a/src/libgreen/stack.rs b/src/libgreen/stack.rs index 526ce66b1ea..c4885edb7d3 100644 --- a/src/libgreen/stack.rs +++ b/src/libgreen/stack.rs @@ -78,14 +78,14 @@ impl Stack { } /// Point to the low end of the allocated stack - pub fn start(&self) -> *uint { - self.buf.data as *uint + pub fn start(&self) -> *const uint { + self.buf.data as *const uint } /// Point one uint beyond the high end of the allocated stack - pub fn end(&self) -> *uint { + pub fn end(&self) -> *const uint { unsafe { - self.buf.data.offset(self.buf.len as int) as *uint + self.buf.data.offset(self.buf.len as int) as *const uint } } } @@ -168,8 +168,8 @@ fn max_cached_stacks() -> uint { } extern { - fn rust_valgrind_stack_register(start: *libc::uintptr_t, - end: *libc::uintptr_t) -> libc::c_uint; + fn rust_valgrind_stack_register(start: *const libc::uintptr_t, + end: *const libc::uintptr_t) -> libc::c_uint; fn rust_valgrind_stack_deregister(id: libc::c_uint); } diff --git a/src/libgreen/task.rs b/src/libgreen/task.rs index 25c2a952341..68a454233cf 100644 --- a/src/libgreen/task.rs +++ b/src/libgreen/task.rs @@ -89,7 +89,7 @@ pub enum Home { /// /// The goal for having this weird-looking function is to reduce the number of /// allocations done on a green-task startup as much as possible. -extern fn bootstrap_green_task(task: uint, code: *(), env: *()) -> ! { +extern fn bootstrap_green_task(task: uint, code: *mut (), env: *mut ()) -> ! { // Acquire ownership of the `proc()` let start: proc() = unsafe { mem::transmute(raw::Procedure { code: code, env: env }) @@ -256,7 +256,7 @@ impl GreenTask { // context switches pub fn as_uint(&self) -> uint { - self as *GreenTask as uint + self as *const GreenTask as uint } pub unsafe fn from_uint(val: uint) -> Box<GreenTask> { diff --git a/src/libhexfloat/lib.rs b/src/libhexfloat/lib.rs index d0e9e2e436e..6b2c39628fc 100644 --- a/src/libhexfloat/lib.rs +++ b/src/libhexfloat/lib.rs @@ -77,12 +77,12 @@ fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { if chars.next() != Some('x') { return Some((i, "Expected 'x'".to_string())); } i+=1; - let mut d_len = 0; + let mut d_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;} if chars.next() != Some('.') { return Some((i, "Expected '.'".to_string())); } i+=1; - let mut f_len = 0; + let mut f_len = 0i; for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;} if d_len == 0 && f_len == 0 { return Some((i, "Expected digits before or after decimal \ @@ -92,7 +92,7 @@ fn hex_float_lit_err(s: &str) -> Option<(uint, String)> { return Some((i, "Expected 'p'".to_string())); } i+=1; if chars.peek() == Some(&'-') { chars.next(); i+= 1 } - let mut e_len = 0; + let mut e_len = 0i; for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1} if e_len == 0 { return Some((i, "Expected exponent digits".to_string())); diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index 83b6c696adf..81e50889952 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -369,14 +369,14 @@ pub mod types { pub struct glob_t { pub gl_pathc: size_t, - pub gl_pathv: **c_char, + pub gl_pathv: *mut *mut c_char, pub gl_offs: size_t, - pub __unused1: *c_void, - pub __unused2: *c_void, - pub __unused3: *c_void, - pub __unused4: *c_void, - pub __unused5: *c_void, + pub __unused1: *mut c_void, + pub __unused2: *mut c_void, + pub __unused3: *mut c_void, + pub __unused4: *mut c_void, + pub __unused5: *mut c_void, } pub struct timeval { @@ -444,18 +444,18 @@ pub mod types { pub ai_addrlen: socklen_t, #[cfg(target_os = "linux")] - pub ai_addr: *sockaddr, + pub ai_addr: *mut sockaddr, #[cfg(target_os = "linux")] - pub ai_canonname: *c_char, + pub ai_canonname: *mut c_char, #[cfg(target_os = "android")] - pub ai_canonname: *c_char, + pub ai_canonname: *mut c_char, #[cfg(target_os = "android")] - pub ai_addr: *sockaddr, + pub ai_addr: *mut sockaddr, - pub ai_next: *addrinfo, + pub ai_next: *mut addrinfo, } pub struct sockaddr_un { pub sun_family: sa_family_t, @@ -755,15 +755,15 @@ pub mod types { pub __unused1: size_t, pub gl_offs: size_t, pub __unused2: c_int, - pub gl_pathv: **c_char, + pub gl_pathv: *mut *mut c_char, - pub __unused3: *c_void, + pub __unused3: *mut c_void, - pub __unused4: *c_void, - pub __unused5: *c_void, - pub __unused6: *c_void, - pub __unused7: *c_void, - pub __unused8: *c_void, + pub __unused4: *mut c_void, + pub __unused5: *mut c_void, + pub __unused6: *mut c_void, + pub __unused7: *mut c_void, + pub __unused8: *mut c_void, } pub struct timeval { @@ -834,9 +834,9 @@ pub mod types { pub ai_socktype: c_int, pub ai_protocol: c_int, pub ai_addrlen: socklen_t, - pub ai_canonname: *c_char, - pub ai_addr: *sockaddr, - pub ai_next: *addrinfo, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut sockaddr, + pub ai_next: *mut addrinfo, } pub struct sockaddr_un { pub sun_len: u8, @@ -926,7 +926,7 @@ pub mod types { pub modtime: time_t, } - pub type pthread_attr_t = *c_void; + pub type pthread_attr_t = *mut c_void; } pub mod posix08 { } @@ -1032,9 +1032,9 @@ pub mod types { pub ai_socktype: c_int, pub ai_protocol: c_int, pub ai_addrlen: size_t, - pub ai_canonname: *c_char, - pub ai_addr: *sockaddr, - pub ai_next: *addrinfo, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut sockaddr, + pub ai_next: *mut addrinfo, } pub struct sockaddr_un { pub sun_family: sa_family_t, @@ -1146,8 +1146,8 @@ pub mod types { pub type LARGE_INTEGER = c_longlong; pub type PLARGE_INTEGER = *mut c_longlong; - pub type LPCWSTR = *WCHAR; - pub type LPCSTR = *CHAR; + pub type LPCWSTR = *const WCHAR; + pub type LPCSTR = *const CHAR; pub type LPWSTR = *mut WCHAR; pub type LPSTR = *mut CHAR; @@ -1163,7 +1163,7 @@ pub mod types { pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; pub type LPVOID = *mut c_void; - pub type LPCVOID = *c_void; + pub type LPCVOID = *const c_void; pub type LPBYTE = *mut BYTE; pub type LPWORD = *mut WORD; pub type LPDWORD = *mut DWORD; @@ -1235,8 +1235,8 @@ pub mod types { pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; pub struct OVERLAPPED { - pub Internal: *c_ulong, - pub InternalHigh: *c_ulong, + pub Internal: *mut c_ulong, + pub InternalHigh: *mut c_ulong, pub Offset: DWORD, pub OffsetHigh: DWORD, pub hEvent: HANDLE, @@ -1312,15 +1312,15 @@ pub mod types { pub __unused1: c_int, pub gl_offs: size_t, pub __unused2: c_int, - pub gl_pathv: **c_char, + pub gl_pathv: *mut *mut c_char, - pub __unused3: *c_void, + pub __unused3: *mut c_void, - pub __unused4: *c_void, - pub __unused5: *c_void, - pub __unused6: *c_void, - pub __unused7: *c_void, - pub __unused8: *c_void, + pub __unused4: *mut c_void, + pub __unused5: *mut c_void, + pub __unused6: *mut c_void, + pub __unused7: *mut c_void, + pub __unused8: *mut c_void, } pub struct timeval { @@ -1392,9 +1392,9 @@ pub mod types { pub ai_socktype: c_int, pub ai_protocol: c_int, pub ai_addrlen: socklen_t, - pub ai_canonname: *c_char, - pub ai_addr: *sockaddr, - pub ai_next: *addrinfo, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut sockaddr, + pub ai_next: *mut addrinfo, } pub struct sockaddr_un { pub sun_len: u8, @@ -3543,53 +3543,56 @@ pub mod funcs { use types::os::arch::c95::{c_char, c_int, c_long, size_t}; extern { - pub fn fopen(filename: *c_char, mode: *c_char) -> *FILE; - pub fn freopen(filename: *c_char, mode: *c_char, file: *FILE) - -> *FILE; - pub fn fflush(file: *FILE) -> c_int; - pub fn fclose(file: *FILE) -> c_int; - pub fn remove(filename: *c_char) -> c_int; - pub fn rename(oldname: *c_char, newname: *c_char) -> c_int; - pub fn tmpfile() -> *FILE; - pub fn setvbuf(stream: *FILE, - buffer: *c_char, + pub fn fopen(filename: *const c_char, + mode: *const c_char) -> *mut FILE; + pub fn freopen(filename: *const c_char, mode: *const c_char, + file: *mut FILE) + -> *mut FILE; + pub fn fflush(file: *mut FILE) -> c_int; + pub fn fclose(file: *mut FILE) -> c_int; + pub fn remove(filename: *const c_char) -> c_int; + pub fn rename(oldname: *const c_char, + newname: *const c_char) -> c_int; + pub fn tmpfile() -> *mut FILE; + pub fn setvbuf(stream: *mut FILE, + buffer: *mut c_char, mode: c_int, size: size_t) -> c_int; - pub fn setbuf(stream: *FILE, buf: *c_char); + pub fn setbuf(stream: *mut FILE, buf: *mut c_char); // Omitted: printf and scanf variants. - pub fn fgetc(stream: *FILE) -> c_int; - pub fn fgets(buf: *mut c_char, n: c_int, stream: *FILE) - -> *c_char; - pub fn fputc(c: c_int, stream: *FILE) -> c_int; - pub fn fputs(s: *c_char, stream: *FILE) -> *c_char; + pub fn fgetc(stream: *mut FILE) -> c_int; + pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE) + -> *mut c_char; + pub fn fputc(c: c_int, stream: *mut FILE) -> c_int; + pub fn fputs(s: *const c_char, stream: *mut FILE)-> c_int; // Omitted: getc, getchar (might be macros). // Omitted: gets, so ridiculously unsafe that it should not // survive. // Omitted: putc, putchar (might be macros). - pub fn puts(s: *c_char) -> c_int; - pub fn ungetc(c: c_int, stream: *FILE) -> c_int; + pub fn puts(s: *const c_char) -> c_int; + pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int; pub fn fread(ptr: *mut c_void, size: size_t, nobj: size_t, - stream: *FILE) + stream: *mut FILE) -> size_t; - pub fn fwrite(ptr: *c_void, + pub fn fwrite(ptr: *const c_void, size: size_t, nobj: size_t, - stream: *FILE) + stream: *mut FILE) -> size_t; - pub fn fseek(stream: *FILE, offset: c_long, whence: c_int) + pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int; - pub fn ftell(stream: *FILE) -> c_long; - pub fn rewind(stream: *FILE); - pub fn fgetpos(stream: *FILE, ptr: *fpos_t) -> c_int; - pub fn fsetpos(stream: *FILE, ptr: *fpos_t) -> c_int; - pub fn feof(stream: *FILE) -> c_int; - pub fn ferror(stream: *FILE) -> c_int; - pub fn perror(s: *c_char); + pub fn ftell(stream: *mut FILE) -> c_long; + pub fn rewind(stream: *mut FILE); + pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int; + pub fn fsetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int; + pub fn feof(stream: *mut FILE) -> c_int; + pub fn ferror(stream: *mut FILE) -> c_int; + pub fn perror(s: *const c_char); } } @@ -3603,22 +3606,23 @@ pub mod funcs { pub fn abs(i: c_int) -> c_int; pub fn labs(i: c_long) -> c_long; // Omitted: div, ldiv (return pub type incomplete). - pub fn atof(s: *c_char) -> c_double; - pub fn atoi(s: *c_char) -> c_int; - pub fn strtod(s: *c_char, endp: **c_char) -> c_double; - pub fn strtol(s: *c_char, endp: **c_char, base: c_int) - -> c_long; - pub fn strtoul(s: *c_char, endp: **c_char, base: c_int) - -> c_ulong; - pub fn calloc(nobj: size_t, size: size_t) -> *c_void; + pub fn atof(s: *const c_char) -> c_double; + pub fn atoi(s: *const c_char) -> c_int; + pub fn strtod(s: *const c_char, + endp: *mut *mut c_char) -> c_double; + pub fn strtol(s: *const c_char, + endp: *mut *mut c_char, base: c_int) -> c_long; + pub fn strtoul(s: *const c_char, endp: *mut *mut c_char, + base: c_int) -> c_ulong; + pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void; pub fn malloc(size: size_t) -> *mut c_void; pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void; pub fn free(p: *mut c_void); pub fn exit(status: c_int) -> !; pub fn _exit(status: c_int) -> !; // Omitted: atexit. - pub fn system(s: *c_char) -> c_int; - pub fn getenv(s: *c_char) -> *c_char; + pub fn system(s: *const c_char) -> c_int; + pub fn getenv(s: *const c_char) -> *mut c_char; // Omitted: bsearch, qsort pub fn rand() -> c_int; pub fn srand(seed: c_uint); @@ -3631,32 +3635,40 @@ pub mod funcs { use types::os::arch::c95::{wchar_t}; extern { - pub fn strcpy(dst: *c_char, src: *c_char) -> *c_char; - pub fn strncpy(dst: *c_char, src: *c_char, n: size_t) - -> *c_char; - pub fn strcat(s: *c_char, ct: *c_char) -> *c_char; - pub fn strncat(s: *c_char, ct: *c_char, n: size_t) -> *c_char; - pub fn strcmp(cs: *c_char, ct: *c_char) -> c_int; - pub fn strncmp(cs: *c_char, ct: *c_char, n: size_t) -> c_int; - pub fn strcoll(cs: *c_char, ct: *c_char) -> c_int; - pub fn strchr(cs: *c_char, c: c_int) -> *c_char; - pub fn strrchr(cs: *c_char, c: c_int) -> *c_char; - pub fn strspn(cs: *c_char, ct: *c_char) -> size_t; - pub fn strcspn(cs: *c_char, ct: *c_char) -> size_t; - pub fn strpbrk(cs: *c_char, ct: *c_char) -> *c_char; - pub fn strstr(cs: *c_char, ct: *c_char) -> *c_char; - pub fn strlen(cs: *c_char) -> size_t; - pub fn strerror(n: c_int) -> *c_char; - pub fn strtok(s: *c_char, t: *c_char) -> *c_char; - pub fn strxfrm(s: *c_char, ct: *c_char, n: size_t) -> size_t; - pub fn wcslen(buf: *wchar_t) -> size_t; + pub fn strcpy(dst: *mut c_char, + src: *const c_char) -> *mut c_char; + pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t) + -> *mut c_char; + pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char; + pub fn strncat(s: *mut c_char, ct: *const c_char, + n: size_t) -> *mut c_char; + pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int; + pub fn strncmp(cs: *const c_char, ct: *const c_char, + n: size_t) -> c_int; + pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int; + pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char; + pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char; + pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t; + pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t; + pub fn strpbrk(cs: *const c_char, + ct: *const c_char) -> *mut c_char; + pub fn strstr(cs: *const c_char, + ct: *const c_char) -> *mut c_char; + pub fn strlen(cs: *const c_char) -> size_t; + pub fn strerror(n: c_int) -> *mut c_char; + pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char; + pub fn strxfrm(s: *mut c_char, ct: *const c_char, + n: size_t) -> size_t; + pub fn wcslen(buf: *const wchar_t) -> size_t; // Omitted: memcpy, memmove, memset (provided by LLVM) // These are fine to execute on the Rust stack. They must be, // in fact, because LLVM generates calls to them! - pub fn memcmp(cx: *c_void, ct: *c_void, n: size_t) -> c_int; - pub fn memchr(cx: *c_void, c: c_int, n: size_t) -> *c_void; + pub fn memcmp(cx: *const c_void, ct: *const c_void, + n: size_t) -> c_int; + pub fn memchr(cx: *const c_void, c: c_int, + n: size_t) -> *mut c_void; } } } @@ -3675,21 +3687,21 @@ pub mod funcs { extern { #[link_name = "_chmod"] - pub fn chmod(path: *c_char, mode: c_int) -> c_int; + pub fn chmod(path: *const c_char, mode: c_int) -> c_int; #[link_name = "_wchmod"] - pub fn wchmod(path: *wchar_t, mode: c_int) -> c_int; + pub fn wchmod(path: *const wchar_t, mode: c_int) -> c_int; #[link_name = "_mkdir"] - pub fn mkdir(path: *c_char) -> c_int; + pub fn mkdir(path: *const c_char) -> c_int; #[link_name = "_wrmdir"] - pub fn wrmdir(path: *wchar_t) -> c_int; + pub fn wrmdir(path: *const wchar_t) -> c_int; #[link_name = "_fstat64"] pub fn fstat(fildes: c_int, buf: *mut stat) -> c_int; #[link_name = "_stat64"] - pub fn stat(path: *c_char, buf: *mut stat) -> c_int; + pub fn stat(path: *const c_char, buf: *mut stat) -> c_int; #[link_name = "_wstat64"] - pub fn wstat(path: *wchar_t, buf: *mut stat) -> c_int; + pub fn wstat(path: *const wchar_t, buf: *mut stat) -> c_int; #[link_name = "_wutime64"] - pub fn wutime(file: *wchar_t, buf: *utimbuf) -> c_int; + pub fn wutime(file: *const wchar_t, buf: *mut utimbuf) -> c_int; } } @@ -3699,13 +3711,14 @@ pub mod funcs { extern { #[link_name = "_popen"] - pub fn popen(command: *c_char, mode: *c_char) -> *FILE; + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut FILE; #[link_name = "_pclose"] - pub fn pclose(stream: *FILE) -> c_int; + pub fn pclose(stream: *mut FILE) -> c_int; #[link_name = "_fdopen"] - pub fn fdopen(fd: c_int, mode: *c_char) -> *FILE; + pub fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE; #[link_name = "_fileno"] - pub fn fileno(stream: *FILE) -> c_int; + pub fn fileno(stream: *mut FILE) -> c_int; } } @@ -3713,13 +3726,13 @@ pub mod funcs { use types::os::arch::c95::{c_int, c_char, wchar_t}; extern { #[link_name = "_open"] - pub fn open(path: *c_char, oflag: c_int, mode: c_int) + pub fn open(path: *const c_char, oflag: c_int, mode: c_int) -> c_int; #[link_name = "_wopen"] - pub fn wopen(path: *wchar_t, oflag: c_int, mode: c_int) + pub fn wopen(path: *const wchar_t, oflag: c_int, mode: c_int) -> c_int; #[link_name = "_creat"] - pub fn creat(path: *c_char, mode: c_int) -> c_int; + pub fn creat(path: *const c_char, mode: c_int) -> c_int; } } @@ -3735,9 +3748,9 @@ pub mod funcs { extern { #[link_name = "_access"] - pub fn access(path: *c_char, amode: c_int) -> c_int; + pub fn access(path: *const c_char, amode: c_int) -> c_int; #[link_name = "_chdir"] - pub fn chdir(dir: *c_char) -> c_int; + pub fn chdir(dir: *const c_char) -> c_int; #[link_name = "_close"] pub fn close(fd: c_int) -> c_int; #[link_name = "_dup"] @@ -3745,17 +3758,20 @@ pub mod funcs { #[link_name = "_dup2"] pub fn dup2(src: c_int, dst: c_int) -> c_int; #[link_name = "_execv"] - pub fn execv(prog: *c_char, argv: **c_char) -> intptr_t; + pub fn execv(prog: *const c_char, + argv: *mut *const c_char) -> intptr_t; #[link_name = "_execve"] - pub fn execve(prog: *c_char, argv: **c_char, envp: **c_char) + pub fn execve(prog: *const c_char, argv: *mut *const c_char, + envp: *mut *const c_char) -> c_int; #[link_name = "_execvp"] - pub fn execvp(c: *c_char, argv: **c_char) -> c_int; + pub fn execvp(c: *const c_char, + argv: *mut *const c_char) -> c_int; #[link_name = "_execvpe"] - pub fn execvpe(c: *c_char, argv: **c_char, envp: **c_char) - -> c_int; + pub fn execvpe(c: *const c_char, argv: *mut *const c_char, + envp: *mut *const c_char) -> c_int; #[link_name = "_getcwd"] - pub fn getcwd(buf: *mut c_char, size: size_t) -> *c_char; + pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; #[link_name = "_getpid"] pub fn getpid() -> c_int; #[link_name = "_isatty"] @@ -3770,11 +3786,12 @@ pub mod funcs { pub fn read(fd: c_int, buf: *mut c_void, count: c_uint) -> c_int; #[link_name = "_rmdir"] - pub fn rmdir(path: *c_char) -> c_int; + pub fn rmdir(path: *const c_char) -> c_int; #[link_name = "_unlink"] - pub fn unlink(c: *c_char) -> c_int; + pub fn unlink(c: *const c_char) -> c_int; #[link_name = "_write"] - pub fn write(fd: c_int, buf: *c_void, count: c_uint) -> c_int; + pub fn write(fd: c_int, buf: *const c_void, + count: c_uint) -> c_int; } } @@ -3795,7 +3812,7 @@ pub mod funcs { use types::os::arch::posix88::mode_t; extern { - pub fn chmod(path: *c_char, mode: mode_t) -> c_int; + pub fn chmod(path: *const c_char, mode: mode_t) -> c_int; pub fn fchmod(fd: c_int, mode: mode_t) -> c_int; #[cfg(target_os = "linux")] @@ -3808,18 +3825,18 @@ pub mod funcs { #[link_name = "fstat64"] pub fn fstat(fildes: c_int, buf: *mut stat) -> c_int; - pub fn mkdir(path: *c_char, mode: mode_t) -> c_int; - pub fn mkfifo(path: *c_char, mode: mode_t) -> c_int; + pub fn mkdir(path: *const c_char, mode: mode_t) -> c_int; + pub fn mkfifo(path: *const c_char, mode: mode_t) -> c_int; #[cfg(target_os = "linux")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "android")] #[cfg(target_os = "ios")] - pub fn stat(path: *c_char, buf: *mut stat) -> c_int; + pub fn stat(path: *const c_char, buf: *mut stat) -> c_int; #[cfg(target_os = "macos")] #[link_name = "stat64"] - pub fn stat(path: *c_char, buf: *mut stat) -> c_int; + pub fn stat(path: *const c_char, buf: *mut stat) -> c_int; } } @@ -3828,10 +3845,11 @@ pub mod funcs { use types::os::arch::c95::{c_char, c_int}; extern { - pub fn popen(command: *c_char, mode: *c_char) -> *FILE; - pub fn pclose(stream: *FILE) -> c_int; - pub fn fdopen(fd: c_int, mode: *c_char) -> *FILE; - pub fn fileno(stream: *FILE) -> c_int; + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut FILE; + pub fn pclose(stream: *mut FILE) -> c_int; + pub fn fdopen(fd: c_int, mode: *const c_char) -> *mut FILE; + pub fn fileno(stream: *mut FILE) -> c_int; } } @@ -3840,9 +3858,9 @@ pub mod funcs { use types::os::arch::posix88::mode_t; extern { - pub fn open(path: *c_char, oflag: c_int, mode: c_int) + pub fn open(path: *const c_char, oflag: c_int, mode: c_int) -> c_int; - pub fn creat(path: *c_char, mode: mode_t) -> c_int; + pub fn creat(path: *const c_char, mode: mode_t) -> c_int; pub fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int; } } @@ -3860,17 +3878,17 @@ pub mod funcs { extern { #[link_name="rust_opendir"] - pub fn opendir(dirname: *c_char) -> *DIR; + pub fn opendir(dirname: *const c_char) -> *mut DIR; #[link_name="rust_readdir_r"] - pub fn readdir_r(dirp: *DIR, entry: *mut dirent_t, + pub fn readdir_r(dirp: *mut DIR, entry: *mut dirent_t, result: *mut *mut dirent_t) -> c_int; } extern { - pub fn closedir(dirp: *DIR) -> c_int; - pub fn rewinddir(dirp: *DIR); - pub fn seekdir(dirp: *DIR, loc: c_long); - pub fn telldir(dirp: *DIR) -> c_long; + pub fn closedir(dirp: *mut DIR) -> c_int; + pub fn rewinddir(dirp: *mut DIR); + pub fn seekdir(dirp: *mut DIR, loc: c_long); + pub fn telldir(dirp: *mut DIR) -> c_long; } } @@ -3886,60 +3904,65 @@ pub mod funcs { pub static _PC_NAME_MAX: c_int = 4; extern { - pub fn access(path: *c_char, amode: c_int) -> c_int; + pub fn access(path: *const c_char, amode: c_int) -> c_int; pub fn alarm(seconds: c_uint) -> c_uint; - pub fn chdir(dir: *c_char) -> c_int; - pub fn chown(path: *c_char, uid: uid_t, gid: gid_t) -> c_int; + pub fn chdir(dir: *const c_char) -> c_int; + pub fn chown(path: *const c_char, uid: uid_t, + gid: gid_t) -> c_int; pub fn close(fd: c_int) -> c_int; pub fn dup(fd: c_int) -> c_int; pub fn dup2(src: c_int, dst: c_int) -> c_int; - pub fn execv(prog: *c_char, argv: **c_char) -> c_int; - pub fn execve(prog: *c_char, argv: **c_char, envp: **c_char) + pub fn execv(prog: *const c_char, + argv: *mut *const c_char) -> c_int; + pub fn execve(prog: *const c_char, argv: *mut *const c_char, + envp: *mut *const c_char) -> c_int; - pub fn execvp(c: *c_char, argv: **c_char) -> c_int; + pub fn execvp(c: *const c_char, + argv: *mut *const c_char) -> c_int; pub fn fork() -> pid_t; pub fn fpathconf(filedes: c_int, name: c_int) -> c_long; - pub fn getcwd(buf: *mut c_char, size: size_t) -> *c_char; + pub fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char; pub fn getegid() -> gid_t; pub fn geteuid() -> uid_t; pub fn getgid() -> gid_t ; pub fn getgroups(ngroups_max: c_int, groups: *mut gid_t) -> c_int; - pub fn getlogin() -> *c_char; - pub fn getopt(argc: c_int, argv: **c_char, optstr: *c_char) - -> c_int; + pub fn getlogin() -> *mut c_char; + pub fn getopt(argc: c_int, argv: *mut *const c_char, + optstr: *const c_char) -> c_int; pub fn getpgrp() -> pid_t; pub fn getpid() -> pid_t; pub fn getppid() -> pid_t; pub fn getuid() -> uid_t; pub fn isatty(fd: c_int) -> c_int; - pub fn link(src: *c_char, dst: *c_char) -> c_int; + pub fn link(src: *const c_char, dst: *const c_char) -> c_int; pub fn lseek(fd: c_int, offset: off_t, whence: c_int) -> off_t; - pub fn pathconf(path: *c_char, name: c_int) -> c_long; + pub fn pathconf(path: *mut c_char, name: c_int) -> c_long; pub fn pause() -> c_int; pub fn pipe(fds: *mut c_int) -> c_int; pub fn read(fd: c_int, buf: *mut c_void, count: size_t) -> ssize_t; - pub fn rmdir(path: *c_char) -> c_int; + pub fn rmdir(path: *const c_char) -> c_int; pub fn setgid(gid: gid_t) -> c_int; pub fn setpgid(pid: pid_t, pgid: pid_t) -> c_int; pub fn setsid() -> pid_t; pub fn setuid(uid: uid_t) -> c_int; pub fn sleep(secs: c_uint) -> c_uint; pub fn usleep(secs: c_uint) -> c_int; - pub fn nanosleep(rqtp: *timespec, rmtp: *mut timespec) -> c_int; + pub fn nanosleep(rqtp: *const timespec, + rmtp: *mut timespec) -> c_int; pub fn sysconf(name: c_int) -> c_long; pub fn tcgetpgrp(fd: c_int) -> pid_t; - pub fn ttyname(fd: c_int) -> *c_char; - pub fn unlink(c: *c_char) -> c_int; - pub fn write(fd: c_int, buf: *c_void, count: size_t) + pub fn ttyname(fd: c_int) -> *mut c_char; + pub fn unlink(c: *const c_char) -> c_int; + pub fn write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t; - pub fn pread(fd: c_int, buf: *c_void, count: size_t, + pub fn pread(fd: c_int, buf: *mut c_void, count: size_t, offset: off_t) -> ssize_t; - pub fn pwrite(fd: c_int, buf: *c_void, count: size_t, + pub fn pwrite(fd: c_int, buf: *const c_void, count: size_t, offset: off_t) -> ssize_t; - pub fn utime(file: *c_char, buf: *utimbuf) -> c_int; + pub fn utime(file: *const c_char, buf: *const utimbuf) -> c_int; } } @@ -3958,8 +3981,8 @@ pub mod funcs { use types::os::arch::posix88::{mode_t, off_t}; extern { - pub fn mlock(addr: *c_void, len: size_t) -> c_int; - pub fn munlock(addr: *c_void, len: size_t) -> c_int; + pub fn mlock(addr: *const c_void, len: size_t) -> c_int; + pub fn munlock(addr: *const c_void, len: size_t) -> c_int; pub fn mlockall(flags: c_int) -> c_int; pub fn munlockall() -> c_int; @@ -3977,9 +4000,9 @@ pub mod funcs { pub fn msync(addr: *mut c_void, len: size_t, flags: c_int) -> c_int; - pub fn shm_open(name: *c_char, oflag: c_int, mode: mode_t) + pub fn shm_open(name: *const c_char, oflag: c_int, mode: mode_t) -> c_int; - pub fn shm_unlink(name: *c_char) -> c_int; + pub fn shm_unlink(name: *const c_char) -> c_int; } } } @@ -3999,11 +4022,11 @@ pub mod funcs { #[cfg(target_os = "freebsd")] #[cfg(target_os = "android")] #[cfg(target_os = "ios")] - pub fn lstat(path: *c_char, buf: *mut stat) -> c_int; + pub fn lstat(path: *const c_char, buf: *mut stat) -> c_int; #[cfg(target_os = "macos")] #[link_name = "lstat64"] - pub fn lstat(path: *c_char, buf: *mut stat) -> c_int; + pub fn lstat(path: *const c_char, buf: *mut stat) -> c_int; } } @@ -4012,7 +4035,7 @@ pub mod funcs { use types::os::arch::posix88::{ssize_t, off_t}; extern { - pub fn readlink(path: *c_char, + pub fn readlink(path: *const c_char, buf: *mut c_char, bufsz: size_t) -> ssize_t; @@ -4023,12 +4046,13 @@ pub mod funcs { #[cfg(target_os = "android")] pub fn fdatasync(fd: c_int) -> c_int; - pub fn setenv(name: *c_char, val: *c_char, overwrite: c_int) - -> c_int; - pub fn unsetenv(name: *c_char) -> c_int; - pub fn putenv(string: *c_char) -> c_int; + pub fn setenv(name: *const c_char, val: *const c_char, + overwrite: c_int) -> c_int; + pub fn unsetenv(name: *const c_char) -> c_int; + pub fn putenv(string: *mut c_char) -> c_int; - pub fn symlink(path1: *c_char, path2: *c_char) -> c_int; + pub fn symlink(path1: *const c_char, + path2: *const c_char) -> c_int; pub fn ftruncate(fd: c_int, length: off_t) -> c_int; } @@ -4057,9 +4081,10 @@ pub mod funcs { use types::os::common::posix01::{glob_t}; extern { - pub fn glob(pattern: *c_char, + pub fn glob(pattern: *const c_char, flags: c_int, - errfunc: ::Nullable<extern "C" fn(epath: *c_char, errno: int) -> int>, + errfunc: ::Nullable<extern "C" fn(epath: *const c_char, + errno: int) -> int>, pglob: *mut glob_t); pub fn globfree(pglob: *mut glob_t); } @@ -4070,7 +4095,7 @@ pub mod funcs { use types::os::arch::c95::{c_int, size_t}; extern { - pub fn posix_madvise(addr: *c_void, + pub fn posix_madvise(addr: *mut c_void, len: size_t, advice: c_int) -> c_int; @@ -4114,9 +4139,9 @@ pub mod funcs { extern "system" { pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int; - pub fn connect(socket: c_int, address: *sockaddr, + pub fn connect(socket: c_int, address: *const sockaddr, len: socklen_t) -> c_int; - pub fn bind(socket: c_int, address: *sockaddr, + pub fn bind(socket: c_int, address: *const sockaddr, address_len: socklen_t) -> c_int; pub fn listen(socket: c_int, backlog: c_int) -> c_int; pub fn accept(socket: c_int, address: *mut sockaddr, @@ -4126,7 +4151,8 @@ pub mod funcs { pub fn getsockname(socket: c_int, address: *mut sockaddr, address_len: *mut socklen_t) -> c_int; pub fn setsockopt(socket: c_int, level: c_int, name: c_int, - value: *c_void, option_len: socklen_t) -> c_int; + value: *const c_void, + option_len: socklen_t) -> c_int; pub fn recv(socket: c_int, buf: *mut c_void, len: size_t, flags: c_int) -> ssize_t; pub fn send(socket: c_int, buf: *mut c_void, len: size_t, @@ -4134,8 +4160,8 @@ pub mod funcs { pub fn recvfrom(socket: c_int, buf: *mut c_void, len: size_t, flags: c_int, addr: *mut sockaddr, addrlen: *mut socklen_t) -> ssize_t; - pub fn sendto(socket: c_int, buf: *c_void, len: size_t, - flags: c_int, addr: *sockaddr, + pub fn sendto(socket: c_int, buf: *const c_void, len: size_t, + flags: c_int, addr: *const sockaddr, addrlen: socklen_t) -> ssize_t; pub fn shutdown(socket: c_int, how: c_int) -> c_int; } @@ -4150,9 +4176,9 @@ pub mod funcs { extern "system" { pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> SOCKET; - pub fn connect(socket: SOCKET, address: *sockaddr, + pub fn connect(socket: SOCKET, address: *const sockaddr, len: socklen_t) -> c_int; - pub fn bind(socket: SOCKET, address: *sockaddr, + pub fn bind(socket: SOCKET, address: *const sockaddr, address_len: socklen_t) -> c_int; pub fn listen(socket: SOCKET, backlog: c_int) -> c_int; pub fn accept(socket: SOCKET, address: *mut sockaddr, @@ -4162,7 +4188,8 @@ pub mod funcs { pub fn getsockname(socket: SOCKET, address: *mut sockaddr, address_len: *mut socklen_t) -> c_int; pub fn setsockopt(socket: SOCKET, level: c_int, name: c_int, - value: *c_void, option_len: socklen_t) -> c_int; + value: *const c_void, + option_len: socklen_t) -> c_int; pub fn closesocket(socket: SOCKET) -> c_int; pub fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, flags: c_int) -> c_int; @@ -4171,8 +4198,8 @@ pub mod funcs { pub fn recvfrom(socket: SOCKET, buf: *mut c_void, len: c_int, flags: c_int, addr: *mut sockaddr, addrlen: *mut c_int) -> ssize_t; - pub fn sendto(socket: SOCKET, buf: *c_void, len: c_int, - flags: c_int, addr: *sockaddr, + pub fn sendto(socket: SOCKET, buf: *const c_void, len: c_int, + flags: c_int, addr: *const sockaddr, addrlen: c_int) -> c_int; pub fn shutdown(socket: SOCKET, how: c_int) -> c_int; } @@ -4186,27 +4213,27 @@ pub mod funcs { use types::os::arch::c95::{c_char, c_uchar, c_int, c_uint, size_t}; extern { - pub fn sysctl(name: *c_int, + pub fn sysctl(name: *mut c_int, namelen: c_uint, oldp: *mut c_void, oldlenp: *mut size_t, - newp: *c_void, + newp: *mut c_void, newlen: size_t) -> c_int; - pub fn sysctlbyname(name: *c_char, + pub fn sysctlbyname(name: *const c_char, oldp: *mut c_void, oldlenp: *mut size_t, - newp: *c_void, + newp: *mut c_void, newlen: size_t) -> c_int; - pub fn sysctlnametomib(name: *c_char, + pub fn sysctlnametomib(name: *const c_char, mibp: *mut c_int, sizep: *mut size_t) -> c_int; pub fn getdtablesize() -> c_int; - pub fn madvise(addr: *c_void, len: size_t, advice: c_int) + pub fn madvise(addr: *mut c_void, len: size_t, advice: c_int) -> c_int; - pub fn mincore(addr: *c_void, len: size_t, vec: *c_uchar) + pub fn mincore(addr: *mut c_void, len: size_t, vec: *mut c_uchar) -> c_int; } } @@ -4298,7 +4325,7 @@ pub mod funcs { -> DWORD; pub fn SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL; pub fn GetLastError() -> DWORD; - pub fn FindFirstFileW(fileName: *u16, findFileData: HANDLE) + pub fn FindFirstFileW(fileName: LPCWSTR, findFileData: HANDLE) -> HANDLE; pub fn FindNextFileW(findFile: HANDLE, findFileData: HANDLE) -> BOOL; diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 59bed3840a3..b99a9d75f33 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -144,8 +144,8 @@ static DEFAULT_LOG_LEVEL: u32 = 1; /// logging statement should be run. static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL; -static mut DIRECTIVES: *Vec<directive::LogDirective> = - 0 as *Vec<directive::LogDirective>; +static mut DIRECTIVES: *const Vec<directive::LogDirective> = + 0 as *const Vec<directive::LogDirective>; /// Debug log level pub static DEBUG: u32 = 4; @@ -351,7 +351,7 @@ fn init() { assert!(!DIRECTIVES.is_null()); let _directives: Box<Vec<directive::LogDirective>> = mem::transmute(DIRECTIVES); - DIRECTIVES = 0 as *Vec<directive::LogDirective>; + DIRECTIVES = 0 as *const Vec<directive::LogDirective>; }); } } diff --git a/src/libnative/io/addrinfo.rs b/src/libnative/io/addrinfo.rs index 255c3f4bd21..0977b55d8b9 100644 --- a/src/libnative/io/addrinfo.rs +++ b/src/libnative/io/addrinfo.rs @@ -37,19 +37,21 @@ impl GetAddrInfoRequest { ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, - ai_canonname: null(), - ai_addr: null(), - ai_next: null() + ai_canonname: mut_null(), + ai_addr: mut_null(), + ai_next: mut_null() } }); - let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo); + let hint_ptr = hint.as_ref().map_or(null(), |x| { + x as *const libc::addrinfo + }); let mut res = mut_null(); // Make the call let s = unsafe { - let ch = if c_host.is_null() { null() } else { c_host.with_ref(|x| x) }; - let cs = if c_serv.is_null() { null() } else { c_serv.with_ref(|x| x) }; + let ch = if c_host.is_null() { null() } else { c_host.as_ptr() }; + let cs = if c_serv.is_null() { null() } else { c_serv.as_ptr() }; getaddrinfo(ch, cs, hint_ptr, &mut res) }; @@ -87,11 +89,12 @@ impl GetAddrInfoRequest { } extern "system" { - fn getaddrinfo(node: *c_char, service: *c_char, - hints: *libc::addrinfo, res: *mut *mut libc::addrinfo) -> c_int; + fn getaddrinfo(node: *const c_char, service: *const c_char, + hints: *const libc::addrinfo, + res: *mut *mut libc::addrinfo) -> c_int; fn freeaddrinfo(res: *mut libc::addrinfo); #[cfg(not(windows))] - fn gai_strerror(errcode: c_int) -> *c_char; + fn gai_strerror(errcode: c_int) -> *const c_char; } #[cfg(windows)] diff --git a/src/libnative/io/c_unix.rs b/src/libnative/io/c_unix.rs index b1bc36e0b05..9fbf3659d3f 100644 --- a/src/libnative/io/c_unix.rs +++ b/src/libnative/io/c_unix.rs @@ -57,12 +57,12 @@ pub static WNOHANG: libc::c_int = 1; extern { pub fn gettimeofday(timeval: *mut libc::timeval, - tzp: *libc::c_void) -> libc::c_int; + tzp: *mut libc::c_void) -> libc::c_int; pub fn select(nfds: libc::c_int, - readfds: *fd_set, - writefds: *fd_set, - errorfds: *fd_set, - timeout: *libc::timeval) -> libc::c_int; + readfds: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *mut libc::timeval) -> libc::c_int; pub fn getsockopt(sockfd: libc::c_int, level: libc::c_int, optname: libc::c_int, @@ -75,7 +75,7 @@ extern { options: libc::c_int) -> libc::pid_t; pub fn sigaction(signum: libc::c_int, - act: *sigaction, + act: *const sigaction, oldact: *mut sigaction) -> libc::c_int; pub fn sigaddset(set: *mut sigset_t, signum: libc::c_int) -> libc::c_int; diff --git a/src/libnative/io/c_win32.rs b/src/libnative/io/c_win32.rs index 1b6525c6e38..802526c9196 100644 --- a/src/libnative/io/c_win32.rs +++ b/src/libnative/io/c_win32.rs @@ -28,7 +28,7 @@ pub struct WSADATA { pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], pub iMaxSockets: u16, pub iMaxUdpDg: u16, - pub lpVendorInfo: *u8, + pub lpVendorInfo: *mut u8, } pub type LPWSADATA = *mut WSADATA; @@ -53,10 +53,10 @@ extern "system" { pub fn ioctlsocket(s: libc::SOCKET, cmd: libc::c_long, argp: *mut libc::c_ulong) -> libc::c_int; pub fn select(nfds: libc::c_int, - readfds: *fd_set, - writefds: *fd_set, - exceptfds: *fd_set, - timeout: *libc::timeval) -> libc::c_int; + readfds: *mut fd_set, + writefds: *mut fd_set, + exceptfds: *mut fd_set, + timeout: *mut libc::timeval) -> libc::c_int; pub fn getsockopt(sockfd: libc::SOCKET, level: libc::c_int, optname: libc::c_int, @@ -70,6 +70,7 @@ extern "system" { pub mod compat { use std::intrinsics::{atomic_store_relaxed, transmute}; + use std::iter::Iterator; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; extern "system" { @@ -82,7 +83,8 @@ pub mod compat { // layer (after it's loaded) shouldn't be any slower than a regular DLL // call. unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) { - let module = module.to_utf16().append_one(0); + let module: Vec<u16> = module.utf16_units().collect(); + let module = module.append_one(0); symbol.with_c_str(|symbol| { let handle = GetModuleHandleW(module.as_ptr()); let func: uint = transmute(GetProcAddress(handle, symbol)); diff --git a/src/libnative/io/file_unix.rs b/src/libnative/io/file_unix.rs index edf2becc777..ddcff2be5f3 100644 --- a/src/libnative/io/file_unix.rs +++ b/src/libnative/io/file_unix.rs @@ -68,7 +68,7 @@ impl FileDesc { pub fn inner_write(&mut self, buf: &[u8]) -> IoResult<()> { let ret = keep_going(buf, |buf, len| { unsafe { - libc::write(self.fd(), buf as *libc::c_void, + libc::write(self.fd(), buf as *const libc::c_void, len as libc::size_t) as i64 } }); @@ -91,7 +91,7 @@ impl rtio::RtioFileStream for FileDesc { } fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> { match retry(|| unsafe { - libc::pread(self.fd(), buf.as_ptr() as *libc::c_void, + libc::pread(self.fd(), buf.as_ptr() as *mut _, buf.len() as libc::size_t, offset as libc::off_t) as libc::c_int }) { @@ -101,7 +101,7 @@ impl rtio::RtioFileStream for FileDesc { } fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::pwrite(self.fd(), buf.as_ptr() as *libc::c_void, + libc::pwrite(self.fd(), buf.as_ptr() as *const _, buf.len() as libc::size_t, offset as libc::off_t) } as c_int)) } @@ -222,7 +222,7 @@ impl Drop for Inner { } pub struct CFile { - file: *libc::FILE, + file: *mut libc::FILE, fd: FileDesc, } @@ -231,7 +231,7 @@ impl CFile { /// /// The `CFile` takes ownership of the `FILE` pointer and will close it upon /// destruction. - pub fn new(file: *libc::FILE) -> CFile { + pub fn new(file: *mut libc::FILE) -> CFile { CFile { file: file, fd: FileDesc::new(unsafe { libc::fileno(file) }, false) @@ -263,7 +263,7 @@ impl rtio::RtioFileStream for CFile { fn write(&mut self, buf: &[u8]) -> IoResult<()> { let ret = keep_going(buf, |buf, len| { unsafe { - libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t, + libc::fwrite(buf as *const libc::c_void, 1, len as libc::size_t, self.file) as i64 } }); @@ -339,7 +339,7 @@ pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) libc::S_IRUSR | libc::S_IWUSR), }; - match retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) }) { + match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) { -1 => Err(super::last_error()), fd => Ok(FileDesc::new(fd, true)), } @@ -347,7 +347,7 @@ pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) pub fn mkdir(p: &CString, mode: uint) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::mkdir(p.with_ref(|p| p), mode as libc::mode_t) + libc::mkdir(p.as_ptr(), mode as libc::mode_t) })) } @@ -356,7 +356,7 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> { use libc::{opendir, readdir_r, closedir}; fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> { - let root = unsafe { CString::new(root.with_ref(|p| p), false) }; + let root = unsafe { CString::new(root.as_ptr(), false) }; let root = Path::new(root); dirs.move_iter().filter(|path| { @@ -366,14 +366,14 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> { extern { fn rust_dirent_t_size() -> libc::c_int; - fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char; + fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char; } let size = unsafe { rust_dirent_t_size() }; let mut buf = Vec::<u8>::with_capacity(size as uint); let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t; - let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) }); + let dir_ptr = unsafe {opendir(p.as_ptr())}; if dir_ptr as uint != 0 { let mut paths = vec!(); @@ -393,37 +393,37 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> { } pub fn unlink(p: &CString) -> IoResult<()> { - super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) })) + super::mkerr_libc(retry(|| unsafe { libc::unlink(p.as_ptr()) })) } pub fn rename(old: &CString, new: &CString) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::rename(old.with_ref(|p| p), new.with_ref(|p| p)) + libc::rename(old.as_ptr(), new.as_ptr()) })) } pub fn chmod(p: &CString, mode: uint) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::chmod(p.with_ref(|p| p), mode as libc::mode_t) + libc::chmod(p.as_ptr(), mode as libc::mode_t) })) } pub fn rmdir(p: &CString) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::rmdir(p.with_ref(|p| p)) + libc::rmdir(p.as_ptr()) })) } pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::chown(p.with_ref(|p| p), uid as libc::uid_t, + libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })) } pub fn readlink(p: &CString) -> IoResult<CString> { - let p = p.with_ref(|p| p); - let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) }; + let p = p.as_ptr(); + let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) }; if len == -1 { len = 1024; // FIXME: read PATH_MAX from C ffi? } @@ -443,13 +443,13 @@ pub fn readlink(p: &CString) -> IoResult<CString> { pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p)) + libc::symlink(src.as_ptr(), dst.as_ptr()) })) } pub fn link(src: &CString, dst: &CString) -> IoResult<()> { super::mkerr_libc(retry(|| unsafe { - libc::link(src.with_ref(|p| p), dst.with_ref(|p| p)) + libc::link(src.as_ptr(), dst.as_ptr()) })) } @@ -489,7 +489,7 @@ fn mkstat(stat: &libc::stat) -> rtio::FileStat { pub fn stat(p: &CString) -> IoResult<rtio::FileStat> { let mut stat: libc::stat = unsafe { mem::zeroed() }; - match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) { + match retry(|| unsafe { libc::stat(p.as_ptr(), &mut stat) }) { 0 => Ok(mkstat(&stat)), _ => Err(super::last_error()), } @@ -497,7 +497,7 @@ pub fn stat(p: &CString) -> IoResult<rtio::FileStat> { pub fn lstat(p: &CString) -> IoResult<rtio::FileStat> { let mut stat: libc::stat = unsafe { mem::zeroed() }; - match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) { + match retry(|| unsafe { libc::lstat(p.as_ptr(), &mut stat) }) { 0 => Ok(mkstat(&stat)), _ => Err(super::last_error()), } @@ -509,7 +509,7 @@ pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> { modtime: (mtime / 1000) as libc::time_t, }; super::mkerr_libc(retry(|| unsafe { - libc::utime(p.with_ref(|p| p), &buf) + libc::utime(p.as_ptr(), &buf) })) } diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index cd9abc70a4e..98553603313 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -255,7 +255,7 @@ impl Drop for Inner { pub fn to_utf16(s: &CString) -> IoResult<Vec<u16>> { match s.as_str() { - Some(s) => Ok(s.to_utf16().append_one(0)), + Some(s) => Ok(s.utf16_units().collect::<Vec<u16>>().append_one(0)), None => Err(IoError { code: libc::ERROR_INVALID_NAME as uint, extra: 0, @@ -347,7 +347,7 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> { use std::rt::libc_heap::malloc_raw; fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> { - let root = unsafe { CString::new(root.with_ref(|p| p), false) }; + let root = unsafe { CString::new(root.as_ptr(), false) }; let root = Path::new(root); dirs.move_iter().filter(|path| { @@ -357,21 +357,22 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> { extern { fn rust_list_dir_wfd_size() -> libc::size_t; - fn rust_list_dir_wfd_fp_buf(wfd: *libc::c_void) -> *u16; + fn rust_list_dir_wfd_fp_buf(wfd: *mut libc::c_void) -> *const u16; } let star = Path::new(unsafe { - CString::new(p.with_ref(|p| p), false) + CString::new(p.as_ptr(), false) }).join("*"); let path = try!(to_utf16(&star.to_c_str())); unsafe { let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint); - let find_handle = libc::FindFirstFileW(path.as_ptr(), wfd_ptr as libc::HANDLE); + let find_handle = libc::FindFirstFileW(path.as_ptr(), + wfd_ptr as libc::HANDLE); if find_handle as libc::c_int != libc::INVALID_HANDLE_VALUE { let mut paths = vec!(); let mut more_files = 1 as libc::c_int; while more_files != 0 { - let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr as *c_void); + let fp_buf = rust_list_dir_wfd_fp_buf(wfd_ptr as *mut c_void); if fp_buf as uint == 0 { fail!("os::list_dir() failure: got null ptr from wfd"); } else { @@ -446,7 +447,7 @@ pub fn readlink(p: &CString) -> IoResult<CString> { // without the null pointer let ret = fill_utf16_buf_and_decode(|buf, sz| unsafe { GetFinalPathNameByHandleW(handle, - buf as *u16, + buf as *const u16, sz - 1, libc::VOLUME_NAME_DOS) }); @@ -514,12 +515,12 @@ pub fn lstat(_p: &CString) -> IoResult<rtio::FileStat> { } pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> { - let buf = libc::utimbuf { + let mut buf = libc::utimbuf { actime: (atime / 1000) as libc::time64_t, modtime: (mtime / 1000) as libc::time64_t, }; let p = try!(to_utf16(p)); super::mkerr_libc(unsafe { - libc::wutime(p.as_ptr(), &buf) + libc::wutime(p.as_ptr(), &mut buf) }) } diff --git a/src/libnative/io/mod.rs b/src/libnative/io/mod.rs index 32775e2cfb5..f6764b8f26a 100644 --- a/src/libnative/io/mod.rs +++ b/src/libnative/io/mod.rs @@ -132,7 +132,7 @@ fn retry(f: || -> libc::c_int) -> libc::c_int { } } -fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 { +fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data = data.as_ptr(); let mut amt = origamt; diff --git a/src/libnative/io/net.rs b/src/libnative/io/net.rs index 5dfae8d9efe..dfc2c55cde7 100644 --- a/src/libnative/io/net.rs +++ b/src/libnative/io/net.rs @@ -105,7 +105,7 @@ fn socket(addr: rtio::SocketAddr, ty: libc::c_int) -> IoResult<sock_t> { fn setsockopt<T>(fd: sock_t, opt: libc::c_int, val: libc::c_int, payload: T) -> IoResult<()> { unsafe { - let payload = &payload as *T as *libc::c_void; + let payload = &payload as *const T as *const libc::c_void; let ret = libc::setsockopt(fd, opt, val, payload, mem::size_of::<T>() as libc::socklen_t); @@ -278,7 +278,7 @@ impl TcpStream { let ret = TcpStream::new(Inner::new(fd)); let (addr, len) = addr_to_sockaddr(addr); - let addrp = &addr as *_ as *libc::sockaddr; + let addrp = &addr as *const _ as *const libc::sockaddr; let len = len as libc::socklen_t; match timeout { @@ -369,7 +369,7 @@ impl rtio::RtioTcpStream for TcpStream { fn write(&mut self, buf: &[u8]) -> IoResult<()> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); - let dowrite = |nb: bool, buf: *u8, len: uint| unsafe { + let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::send(fd, buf as *mut libc::c_void, @@ -456,7 +456,7 @@ impl TcpListener { let ret = TcpListener { inner: Inner::new(fd) }; let (addr, len) = addr_to_sockaddr(addr); - let addrp = &addr as *_ as *libc::sockaddr; + let addrp = &addr as *const _ as *const libc::sockaddr; let len = len as libc::socklen_t; // On platforms with Berkeley-derived sockets, this allows @@ -564,7 +564,7 @@ impl UdpSocket { }; let (addr, len) = addr_to_sockaddr(addr); - let addrp = &addr as *_ as *libc::sockaddr; + let addrp = &addr as *const _ as *const libc::sockaddr; let len = len as libc::socklen_t; match unsafe { libc::bind(fd, addrp, len) } { @@ -630,7 +630,7 @@ impl rtio::RtioSocket for UdpSocket { #[cfg(unix)] type msglen_t = libc::size_t; impl rtio::RtioUdpSocket for UdpSocket { - fn recvfrom(&mut self, buf: &mut [u8]) -> IoResult<(uint, rtio::SocketAddr)> { + fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, rtio::SocketAddr)> { let fd = self.fd(); let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; let storagep = &mut storage as *mut _ as *mut libc::sockaddr; @@ -652,17 +652,17 @@ impl rtio::RtioUdpSocket for UdpSocket { }) } - fn sendto(&mut self, buf: &[u8], dst: rtio::SocketAddr) -> IoResult<()> { + fn send_to(&mut self, buf: &[u8], dst: rtio::SocketAddr) -> IoResult<()> { let (dst, dstlen) = addr_to_sockaddr(dst); - let dstp = &dst as *_ as *libc::sockaddr; + let dstp = &dst as *const _ as *const libc::sockaddr; let dstlen = dstlen as libc::socklen_t; let fd = self.fd(); let dolock = || self.lock_nonblocking(); - let dowrite = |nb, buf: *u8, len: uint| unsafe { + let dowrite = |nb, buf: *const u8, len: uint| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::sendto(fd, - buf as *libc::c_void, + buf as *const libc::c_void, len as msglen_t, flags, dstp, @@ -842,7 +842,7 @@ pub fn write<T>(fd: sock_t, buf: &[u8], write_everything: bool, lock: || -> T, - write: |bool, *u8, uint| -> i64) -> IoResult<uint> { + write: |bool, *const u8, uint| -> i64) -> IoResult<uint> { let mut ret = -1; let mut written = 0; if deadline == 0 { diff --git a/src/libnative/io/pipe_unix.rs b/src/libnative/io/pipe_unix.rs index db0d1743c72..b5b2065f996 100644 --- a/src/libnative/io/pipe_unix.rs +++ b/src/libnative/io/pipe_unix.rs @@ -78,7 +78,7 @@ fn connect(addr: &CString, ty: libc::c_int, timeout: Option<u64>) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); - let addrp = &addr as *_ as *libc::sockaddr; + let addrp = &addr as *const _ as *const libc::sockaddr; let len = len as libc::socklen_t; match timeout { @@ -98,9 +98,9 @@ fn connect(addr: &CString, ty: libc::c_int, fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> { let (addr, len) = try!(addr_to_sockaddr_un(addr)); let inner = Inner::new(try!(unix_socket(ty))); - let addrp = &addr as *libc::sockaddr_storage; + let addrp = &addr as *const _; match unsafe { - libc::bind(inner.fd, addrp as *libc::sockaddr, len as libc::socklen_t) + libc::bind(inner.fd, addrp as *const _, len as libc::socklen_t) } { -1 => Err(super::last_error()), _ => Ok(inner) @@ -166,7 +166,7 @@ impl rtio::RtioPipe for UnixStream { fn write(&mut self, buf: &[u8]) -> IoResult<()> { let fd = self.fd(); let dolock = || self.lock_nonblocking(); - let dowrite = |nb: bool, buf: *u8, len: uint| unsafe { + let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe { let flags = if nb {c::MSG_DONTWAIT} else {0}; libc::send(fd, buf as *mut libc::c_void, @@ -278,7 +278,7 @@ impl Drop for UnixListener { // careful to unlink the path before we close the file descriptor to // prevent races where we unlink someone else's path. unsafe { - let _ = libc::unlink(self.path.with_ref(|p| p)); + let _ = libc::unlink(self.path.as_ptr()); } } } diff --git a/src/libnative/io/pipe_win32.rs b/src/libnative/io/pipe_win32.rs index 5d9ddb1f59c..da713e3f2a9 100644 --- a/src/libnative/io/pipe_win32.rs +++ b/src/libnative/io/pipe_win32.rs @@ -152,7 +152,7 @@ impl Drop for Inner { } } -unsafe fn pipe(name: *u16, init: bool) -> libc::HANDLE { +unsafe fn pipe(name: *const u16, init: bool) -> libc::HANDLE { libc::CreateNamedPipeW( name, libc::PIPE_ACCESS_DUPLEX | @@ -210,7 +210,7 @@ pub struct UnixStream { } impl UnixStream { - fn try_connect(p: *u16) -> Option<libc::HANDLE> { + fn try_connect(p: *const u16) -> Option<libc::HANDLE> { // Note that most of this is lifted from the libuv implementation. // The idea is that if we fail to open a pipe in read/write mode // that we try afterwards in just read or just write diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index 59a075f22b2..6fab73115cf 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -43,7 +43,7 @@ pub struct Process { /// A handle to the process - on unix this will always be NULL, but on /// windows it will be a HANDLE to the process, which will prevent the /// pid being re-used until the handle is closed. - handle: *(), + handle: *mut (), /// None until finish() is called. exit_code: Option<rtio::ProcessExit>, @@ -269,7 +269,7 @@ unsafe fn killpid(pid: pid_t, signal: int) -> IoResult<()> { struct SpawnProcessResult { pid: pid_t, - handle: *(), + handle: *mut (), } #[cfg(windows)] @@ -294,6 +294,8 @@ fn spawn_process_os(cfg: ProcessConfig, use libc::funcs::extra::msvcrt::get_osfhandle; use std::mem; + use std::iter::Iterator; + use std::str::StrSlice; if cfg.gid.is_some() || cfg.uid.is_some() { return Err(IoError { @@ -328,7 +330,8 @@ fn spawn_process_os(cfg: ProcessConfig, lpSecurityDescriptor: ptr::mut_null(), bInheritHandle: 1, }; - let filename = "NUL".to_utf16().append_one(0); + let filename: Vec<u16> = "NUL".utf16_units().collect(); + let filename = filename.append_one(0); *slot = libc::CreateFileW(filename.as_ptr(), access, libc::FILE_SHARE_READ | @@ -371,7 +374,8 @@ fn spawn_process_os(cfg: ProcessConfig, with_envp(cfg.env, |envp| { with_dirp(cfg.cwd, |dirp| { - let mut cmd_str = cmd_str.to_utf16().append_one(0); + let mut cmd_str: Vec<u16> = cmd_str.as_slice().utf16_units().collect(); + cmd_str = cmd_str.append_one(0); let created = CreateProcessW(ptr::null(), cmd_str.as_mut_ptr(), ptr::mut_null(), @@ -403,7 +407,7 @@ fn spawn_process_os(cfg: ProcessConfig, Ok(SpawnProcessResult { pid: pi.dwProcessId as pid_t, - handle: pi.hProcess as *() + handle: pi.hProcess as *mut () }) } } @@ -515,14 +519,14 @@ fn spawn_process_os(cfg: ProcessConfig, } #[cfg(target_os = "macos")] - unsafe fn set_environ(envp: *c_void) { - extern { fn _NSGetEnviron() -> *mut *c_void; } + unsafe fn set_environ(envp: *const c_void) { + extern { fn _NSGetEnviron() -> *mut *const c_void; } *_NSGetEnviron() = envp; } #[cfg(not(target_os = "macos"))] - unsafe fn set_environ(envp: *c_void) { - extern { static mut environ: *c_void; } + unsafe fn set_environ(envp: *const c_void) { + extern { static mut environ: *const c_void; } environ = envp; } @@ -531,7 +535,7 @@ fn spawn_process_os(cfg: ProcessConfig, assert_eq!(ret, 0); } - let dirp = cfg.cwd.map(|c| c.with_ref(|p| p)).unwrap_or(ptr::null()); + let dirp = cfg.cwd.map(|c| c.as_ptr()).unwrap_or(ptr::null()); let cfg = unsafe { mem::transmute::<ProcessConfig,ProcessConfig<'static>>(cfg) @@ -568,7 +572,7 @@ fn spawn_process_os(cfg: ProcessConfig, Err(..) => { Ok(SpawnProcessResult { pid: pid, - handle: ptr::null() + handle: ptr::mut_null() }) } Ok(..) => fail!("short read on the cloexec pipe"), @@ -633,7 +637,7 @@ fn spawn_process_os(cfg: ProcessConfig, } else { libc::O_RDWR }; - devnull.with_ref(|p| libc::open(p, flags, 0)) + libc::open(devnull.as_ptr(), flags, 0) } Some(obj) => { let fd = obj.fd(); @@ -668,17 +672,18 @@ fn spawn_process_os(cfg: ProcessConfig, } match cfg.uid { Some(u) => { - // When dropping privileges from root, the `setgroups` call will - // remove any extraneous groups. If we don't call this, then - // even though our uid has dropped, we may still have groups - // that enable us to do super-user things. This will fail if we - // aren't root, so don't bother checking the return value, this - // is just done as an optimistic privilege dropping function. + // When dropping privileges from root, the `setgroups` call + // will remove any extraneous groups. If we don't call this, + // then even though our uid has dropped, we may still have + // groups that enable us to do super-user things. This will + // fail if we aren't root, so don't bother checking the + // return value, this is just done as an optimistic + // privilege dropping function. extern { fn setgroups(ngroups: libc::c_int, - ptr: *libc::c_void) -> libc::c_int; + ptr: *const libc::c_void) -> libc::c_int; } - let _ = setgroups(0, 0 as *libc::c_void); + let _ = setgroups(0, 0 as *const libc::c_void); if libc::setuid(u as libc::uid_t) != 0 { fail(&mut output); @@ -698,23 +703,24 @@ fn spawn_process_os(cfg: ProcessConfig, if !envp.is_null() { set_environ(envp); } - let _ = execvp(*argv, argv); + let _ = execvp(*argv, argv as *mut _); fail(&mut output); }) }) } #[cfg(unix)] -fn with_argv<T>(prog: &CString, args: &[CString], cb: proc(**libc::c_char) -> T) -> T { - let mut ptrs: Vec<*libc::c_char> = Vec::with_capacity(args.len()+1); +fn with_argv<T>(prog: &CString, args: &[CString], + cb: proc(*const *const libc::c_char) -> T) -> T { + let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1); // Convert the CStrings into an array of pointers. Note: the // lifetime of the various CStrings involved is guaranteed to be // larger than the lifetime of our invocation of cb, but this is // technically unsafe as the callback could leak these pointers // out of our scope. - ptrs.push(prog.with_ref(|buf| buf)); - ptrs.extend(args.iter().map(|tmp| tmp.with_ref(|buf| buf))); + ptrs.push(prog.as_ptr()); + ptrs.extend(args.iter().map(|tmp| tmp.as_ptr())); // Add a terminating null pointer (required by libc). ptrs.push(ptr::null()); @@ -723,7 +729,8 @@ fn with_argv<T>(prog: &CString, args: &[CString], cb: proc(**libc::c_char) -> T) } #[cfg(unix)] -fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: proc(*c_void) -> T) -> T { +fn with_envp<T>(env: Option<&[(CString, CString)]>, + cb: proc(*const c_void) -> T) -> T { // On posixy systems we can pass a char** for envp, which is a // null-terminated array of "k=v\0" strings. Since we must create // these strings locally, yet expose a raw pointer to them, we @@ -742,13 +749,13 @@ fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: proc(*c_void) -> T) -> T } // As with `with_argv`, this is unsafe, since cb could leak the pointers. - let mut ptrs: Vec<*libc::c_char> = + let mut ptrs: Vec<*const libc::c_char> = tmps.iter() - .map(|tmp| tmp.as_ptr() as *libc::c_char) + .map(|tmp| tmp.as_ptr() as *const libc::c_char) .collect(); ptrs.push(ptr::null()); - cb(ptrs.as_ptr() as *c_void) + cb(ptrs.as_ptr() as *const c_void) } _ => cb(ptr::null()) } @@ -767,7 +774,7 @@ fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: |*mut c_void| -> T) -> T let kv = format!("{}={}", pair.ref0().as_str().unwrap(), pair.ref1().as_str().unwrap()); - blk.push_all(kv.to_utf16().as_slice()); + blk.extend(kv.as_slice().utf16_units()); blk.push(0); } @@ -780,12 +787,14 @@ fn with_envp<T>(env: Option<&[(CString, CString)]>, cb: |*mut c_void| -> T) -> T } #[cfg(windows)] -fn with_dirp<T>(d: Option<&CString>, cb: |*u16| -> T) -> T { +fn with_dirp<T>(d: Option<&CString>, cb: |*const u16| -> T) -> T { match d { Some(dir) => { let dir_str = dir.as_str() .expect("expected workingdirectory to be utf-8 encoded"); - let dir_str = dir_str.to_utf16().append_one(0); + let dir_str: Vec<u16> = dir_str.utf16_units().collect(); + let dir_str = dir_str.append_one(0); + cb(dir_str.as_ptr()) }, None => cb(ptr::null()) @@ -793,14 +802,14 @@ fn with_dirp<T>(d: Option<&CString>, cb: |*u16| -> T) -> T { } #[cfg(windows)] -fn free_handle(handle: *()) { +fn free_handle(handle: *mut ()) { assert!(unsafe { libc::CloseHandle(mem::transmute(handle)) != 0 }) } #[cfg(unix)] -fn free_handle(_handle: *()) { +fn free_handle(_handle: *mut ()) { // unix has no process handle object, just a pid } @@ -1014,15 +1023,16 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> { let now = ::io::timer::now(); let ms = if now < deadline {deadline - now} else {0}; tv = util::ms_to_timeval(ms); - (&tv as *_, idx) + (&mut tv as *mut _, idx) } - None => (ptr::null(), -1), + None => (ptr::mut_null(), -1), }; // Wait for something to happen c::fd_set(&mut set, input); c::fd_set(&mut set, read_fd); - match unsafe { c::select(max, &set, ptr::null(), ptr::null(), p) } { + match unsafe { c::select(max, &mut set, ptr::mut_null(), + ptr::mut_null(), p) } { // interrupted, retry -1 if os::errno() == libc::EINTR as int => continue, @@ -1132,9 +1142,9 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> { // which will wake up the other end at some point, so we just allow this // signal to be coalesced with the pending signals on the pipe. extern fn sigchld_handler(_signum: libc::c_int) { - let mut msg = 1; + let msg = 1i; match unsafe { - libc::write(WRITE_FD, &mut msg as *mut _ as *libc::c_void, 1) + libc::write(WRITE_FD, &msg as *const _ as *const libc::c_void, 1) } { 1 => {} -1 if util::wouldblock() => {} // see above comments diff --git a/src/libnative/io/timer_unix.rs b/src/libnative/io/timer_unix.rs index 304ff973835..8d6563bafad 100644 --- a/src/libnative/io/timer_unix.rs +++ b/src/libnative/io/timer_unix.rs @@ -88,7 +88,7 @@ pub enum Req { pub fn now() -> u64 { unsafe { let mut now: libc::timeval = mem::zeroed(); - assert_eq!(c::gettimeofday(&mut now, ptr::null()), 0); + assert_eq!(c::gettimeofday(&mut now, ptr::mut_null()), 0); return (now.tv_sec as u64) * 1000 + (now.tv_usec as u64) / 1000; } } @@ -146,7 +146,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: int) { 'outer: loop { let timeout = if active.len() == 0 { // Empty array? no timeout (wait forever for the next request) - ptr::null() + ptr::mut_null() } else { let now = now(); // If this request has already expired, then signal it and go @@ -162,12 +162,13 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: int) { let tm = active.get(0).target - now; timeout.tv_sec = (tm / 1000) as libc::time_t; timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t; - &timeout as *libc::timeval + &mut timeout as *mut libc::timeval }; c::fd_set(&mut set, input); match unsafe { - c::select(input + 1, &set, ptr::null(), ptr::null(), timeout) + c::select(input + 1, &mut set, ptr::mut_null(), + ptr::mut_null(), timeout) } { // timed out 0 => signal(&mut active, &mut dead), diff --git a/src/libnative/io/timer_win32.rs b/src/libnative/io/timer_win32.rs index 9be09c6de07..1e5594126b1 100644 --- a/src/libnative/io/timer_win32.rs +++ b/src/libnative/io/timer_win32.rs @@ -141,7 +141,7 @@ impl rtio::RtioTimer for Timer { // 100ns intervals, so we multiply by 10^4. let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; assert_eq!(unsafe { - imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(), + imp::SetWaitableTimer(self.obj, &due, 0, ptr::mut_null(), ptr::mut_null(), 0) }, 1); @@ -154,7 +154,7 @@ impl rtio::RtioTimer for Timer { // see above for the calculation let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; assert_eq!(unsafe { - imp::SetWaitableTimer(self.obj, &due, 0, ptr::null(), + imp::SetWaitableTimer(self.obj, &due, 0, ptr::mut_null(), ptr::mut_null(), 0) }, 1); @@ -169,7 +169,7 @@ impl rtio::RtioTimer for Timer { let due = -(msecs as i64 * 10000) as libc::LARGE_INTEGER; assert_eq!(unsafe { imp::SetWaitableTimer(self.obj, &due, msecs as libc::LONG, - ptr::null(), ptr::mut_null(), 0) + ptr::mut_null(), ptr::mut_null(), 0) }, 1); unsafe { HELPER.send(NewTimer(self.obj, cb, false)) } @@ -188,20 +188,20 @@ mod imp { use libc::{LPSECURITY_ATTRIBUTES, BOOL, LPCSTR, HANDLE, LARGE_INTEGER, LONG, LPVOID, DWORD, c_void}; - pub type PTIMERAPCROUTINE = *c_void; + pub type PTIMERAPCROUTINE = *mut c_void; extern "system" { pub fn CreateWaitableTimerA(lpTimerAttributes: LPSECURITY_ATTRIBUTES, bManualReset: BOOL, lpTimerName: LPCSTR) -> HANDLE; pub fn SetWaitableTimer(hTimer: HANDLE, - pDueTime: *LARGE_INTEGER, + pDueTime: *const LARGE_INTEGER, lPeriod: LONG, pfnCompletionRoutine: PTIMERAPCROUTINE, lpArgToCompletionRoutine: LPVOID, fResume: BOOL) -> BOOL; pub fn WaitForMultipleObjects(nCount: DWORD, - lpHandles: *HANDLE, + lpHandles: *const HANDLE, bWaitAll: BOOL, dwMilliseconds: DWORD) -> DWORD; pub fn WaitForSingleObject(hHandle: HANDLE, diff --git a/src/libnative/io/util.rs b/src/libnative/io/util.rs index a3c5349fa45..31ba2223082 100644 --- a/src/libnative/io/util.rs +++ b/src/libnative/io/util.rs @@ -90,7 +90,7 @@ pub fn set_nonblocking(fd: net::sock_t, nb: bool) -> IoResult<()> { // See http://developerweb.net/viewtopic.php?id=3196 for where this is // derived from. pub fn connect_timeout(fd: net::sock_t, - addrp: *libc::sockaddr, + addrp: *const libc::sockaddr, len: libc::socklen_t, timeout_ms: u64) -> IoResult<()> { use std::os; @@ -145,16 +145,16 @@ pub fn connect_timeout(fd: net::sock_t, // Recalculate the timeout each iteration (it is generally // undefined what the value of the 'tv' is after select // returns EINTR). - let tv = ms_to_timeval(timeout - (::io::timer::now() - start)); - c::select(fd + 1, ptr::null(), set as *mut _ as *_, - ptr::null(), &tv) + let mut tv = ms_to_timeval(timeout - (::io::timer::now() - start)); + c::select(fd + 1, ptr::mut_null(), set as *mut _, + ptr::mut_null(), &mut tv) }) } #[cfg(windows)] fn await(_fd: net::sock_t, set: &mut c::fd_set, timeout: u64) -> libc::c_int { - let tv = ms_to_timeval(timeout); - unsafe { c::select(1, ptr::null(), &*set, ptr::null(), &tv) } + let mut tv = ms_to_timeval(timeout); + unsafe { c::select(1, ptr::mut_null(), set, ptr::mut_null(), &mut tv) } } } @@ -163,25 +163,25 @@ pub fn await(fd: net::sock_t, deadline: Option<u64>, let mut set: c::fd_set = unsafe { mem::zeroed() }; c::fd_set(&mut set, fd); let (read, write) = match status { - Readable => (&set as *_, ptr::null()), - Writable => (ptr::null(), &set as *_), + Readable => (&mut set as *mut _, ptr::mut_null()), + Writable => (ptr::mut_null(), &mut set as *mut _), }; let mut tv: libc::timeval = unsafe { mem::zeroed() }; match retry(|| { let now = ::io::timer::now(); let tvp = match deadline { - None => ptr::null(), + None => ptr::mut_null(), Some(deadline) => { // If we're past the deadline, then pass a 0 timeout to // select() so we can poll the status let ms = if deadline < now {0} else {deadline - now}; tv = ms_to_timeval(ms); - &tv as *_ + &mut tv as *mut _ } }; let n = if cfg!(windows) {1} else {fd as libc::c_int + 1}; - let r = unsafe { c::select(n, read, write, ptr::null(), tvp) }; + let r = unsafe { c::select(n, read, write, ptr::mut_null(), tvp) }; r }) { -1 => Err(last_error()), diff --git a/src/libnative/lib.rs b/src/libnative/lib.rs index ade7a479d1e..2e43ddba644 100644 --- a/src/libnative/lib.rs +++ b/src/libnative/lib.rs @@ -20,7 +20,9 @@ //! extern crate native; //! //! #[start] -//! fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } +//! fn start(argc: int, argv: *const *const u8) -> int { +//! native::start(argc, argv, main) +//! } //! //! fn main() { //! // this code is running on the main OS thread @@ -55,7 +57,6 @@ #![deny(unused_result, unused_must_use)] #![allow(non_camel_case_types, deprecated)] -#![allow(unknown_features)] // NOTE: remove after a stage0 snap #![feature(default_type_params, lang_items)] // NB this crate explicitly does *not* allow glob imports, please seriously @@ -84,7 +85,7 @@ static OS_DEFAULT_STACK_ESTIMATE: uint = 2 * (1 << 20); #[lang = "start"] #[cfg(not(test))] -pub fn lang_start(main: *u8, argc: int, argv: **u8) -> int { +pub fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { use std::mem; start(argc, argv, proc() { let main: extern "Rust" fn() = unsafe { mem::transmute(main) }; @@ -101,9 +102,9 @@ pub fn lang_start(main: *u8, argc: int, argv: **u8) -> int { /// /// This function will only return once *all* native threads in the system have /// exited. -pub fn start(argc: int, argv: **u8, main: proc()) -> int { +pub fn start(argc: int, argv: *const *const u8, main: proc()) -> int { let something_around_the_top_of_the_stack = 1; - let addr = &something_around_the_top_of_the_stack as *int; + let addr = &something_around_the_top_of_the_stack as *const int; let my_stack_top = addr as uint; // FIXME #11359 we just assume that this thread has a stack of a diff --git a/src/libnative/task.rs b/src/libnative/task.rs index 0b863d9f694..7ba588ac21c 100644 --- a/src/libnative/task.rs +++ b/src/libnative/task.rs @@ -81,7 +81,7 @@ pub fn spawn_opts(opts: TaskOpts, f: proc():Send) { // which our stack started). Thread::spawn_stack(stack, proc() { let something_around_the_top_of_the_stack = 1; - let addr = &something_around_the_top_of_the_stack as *int; + let addr = &something_around_the_top_of_the_stack as *const int; let my_stack = addr as uint; unsafe { stack::record_stack_bounds(my_stack - stack + 1024, my_stack); @@ -198,7 +198,7 @@ impl rt::Runtime for Ops { cur_task.put_runtime(self); unsafe { - let cur_task_dupe = &*cur_task as *Task; + let cur_task_dupe = &mut *cur_task as *mut Task; let task = BlockedTask::block(cur_task); if times == 1 { diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 06e4792cdcc..cc3753def59 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -91,8 +91,8 @@ impl Eq for BigUint {} impl PartialOrd for BigUint { #[inline] - fn lt(&self, other: &BigUint) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> { + Some(self.cmp(other)) } } @@ -215,7 +215,7 @@ impl Sub<BigUint, BigUint> for BigUint { let zeros = ZERO_VEC.iter().cycle(); let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros)); - let mut borrow = 0; + let mut borrow = 0i; let diff: Vec<BigDigit> = a.take(new_len).zip(b).map(|(ai, bi)| { let (hi, lo) = BigDigit::from_doublebigdigit( BigDigit::base @@ -816,8 +816,8 @@ impl Eq for BigInt {} impl PartialOrd for BigInt { #[inline] - fn lt(&self, other: &BigInt) -> bool { - self.cmp(other) == Less + fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> { + Some(self.cmp(other)) } } diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index 971b6b1b51b..9a455edf2c0 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -193,7 +193,8 @@ macro_rules! cmp_impl { }; } cmp_impl!(impl PartialEq, eq, ne) -cmp_impl!(impl PartialOrd, lt, gt, le, ge) +cmp_impl!(impl PartialOrd, lt -> bool, gt -> bool, le -> bool, ge -> bool, + partial_cmp -> Option<cmp::Ordering>) cmp_impl!(impl Eq, ) cmp_impl!(impl Ord, cmp -> cmp::Ordering) diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index 6caa936636a..134e7af5070 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -389,10 +389,10 @@ impl Isaac64Rng { } }} ); - rngstepp!(0, 21); - rngstepn!(1, 5); - rngstepp!(2, 12); - rngstepn!(3, 33); + rngstepp!(0u, 21); + rngstepn!(1u, 5); + rngstepp!(2u, 12); + rngstepn!(3u, 33); } } diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 6195756e4c0..593b9785d47 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -111,7 +111,7 @@ pub trait Rng { // (3) adds more `unsafe` that needs to be checked, (4) // probably doesn't give much performance gain if // optimisations are on. - let mut count = 0; + let mut count = 0i; let mut num = 0; for byte in dest.mut_iter() { if count == 0 { diff --git a/src/librand/rand_impls.rs b/src/librand/rand_impls.rs index 3dd054cee9d..77433877ec6 100644 --- a/src/librand/rand_impls.rs +++ b/src/librand/rand_impls.rs @@ -203,6 +203,8 @@ tuple_impl!{A, B, C, D, E, F, G} tuple_impl!{A, B, C, D, E, F, G, H} tuple_impl!{A, B, C, D, E, F, G, H, I} tuple_impl!{A, B, C, D, E, F, G, H, I, J} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} impl<T:Rand> Rand for Option<T> { #[inline] diff --git a/src/libregex/parse/mod.rs b/src/libregex/parse/mod.rs index 2fea75746be..9cde40c1960 100644 --- a/src/libregex/parse/mod.rs +++ b/src/libregex/parse/mod.rs @@ -770,7 +770,7 @@ impl<'a> Parser<'a> { } let start = self.chari; let mut flags = self.flags; - let mut sign = 1; + let mut sign = 1i; let mut saw_flag = false; loop { try!(self.noteof("expected non-empty set of flags or closing ')'")) diff --git a/src/librlibc/lib.rs b/src/librlibc/lib.rs index 144479e882d..8c7bf3496ee 100644 --- a/src/librlibc/lib.rs +++ b/src/librlibc/lib.rs @@ -27,7 +27,6 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/0.11.0/")] #![feature(intrinsics)] -#![allow(unknown_features)] // NOTE: remove after stage0 snapshot #![no_std] #![experimental] @@ -43,31 +42,36 @@ // implementations below. If pointer arithmetic is done through integers the // optimizations start to break down. extern "rust-intrinsic" { - fn offset<T>(dst: *T, offset: int) -> *T; + fn offset<T>(dst: *const T, offset: int) -> *const T; } #[no_mangle] -pub unsafe extern "C" fn memcpy(dest: *mut u8, src: *u8, n: uint) -> *mut u8 { +pub unsafe extern "C" fn memcpy(dest: *mut u8, src: *const u8, + n: uint) -> *mut u8 { let mut i = 0; while i < n { - *(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int); + *(offset(dest as *const u8, i as int) as *mut u8) = + *offset(src, i as int); i += 1; } return dest; } #[no_mangle] -pub unsafe extern "C" fn memmove(dest: *mut u8, src: *u8, n: uint) -> *mut u8 { - if src < dest as *u8 { // copy from end +pub unsafe extern "C" fn memmove(dest: *mut u8, src: *const u8, + n: uint) -> *mut u8 { + if src < dest as *const u8 { // copy from end let mut i = n; while i != 0 { i -= 1; - *(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int); + *(offset(dest as *const u8, i as int) as *mut u8) = + *offset(src, i as int); } } else { // copy from beginning let mut i = 0; while i < n { - *(offset(dest as *u8, i as int) as *mut u8) = *offset(src, i as int); + *(offset(dest as *const u8, i as int) as *mut u8) = + *offset(src, i as int); i += 1; } } @@ -78,14 +82,14 @@ pub unsafe extern "C" fn memmove(dest: *mut u8, src: *u8, n: uint) -> *mut u8 { pub unsafe extern "C" fn memset(s: *mut u8, c: i32, n: uint) -> *mut u8 { let mut i = 0; while i < n { - *(offset(s as *u8, i as int) as *mut u8) = c as u8; + *(offset(s as *const u8, i as int) as *mut u8) = c as u8; i += 1; } return s; } #[no_mangle] -pub unsafe extern "C" fn memcmp(s1: *u8, s2: *u8, n: uint) -> i32 { +pub unsafe extern "C" fn memcmp(s1: *const u8, s2: *const u8, n: uint) -> i32 { let mut i = 0; while i < n { let a = *offset(s1, i as int); diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 42e699fb691..17f29639601 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -412,7 +412,7 @@ pub mod write { { let add = |arg: &str| { let s = arg.to_c_str(); - llvm_args.push(s.with_ref(|p| p)); + llvm_args.push(s.as_ptr()); llvm_c_strs.push(s); }; add("rustc"); // fake program name @@ -657,8 +657,8 @@ pub fn sanitize(s: &str) -> String { // Underscore-qualify anything that didn't start as an ident. if result.len() > 0u && - result.as_slice()[0] != '_' as u8 && - ! char::is_XID_start(result.as_slice()[0] as char) { + result.as_bytes()[0] != '_' as u8 && + ! char::is_XID_start(result.as_bytes()[0] as char) { return format!("_{}", result.as_slice()); } @@ -737,9 +737,9 @@ pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems, let extra2 = id % EXTRA_CHARS.len(); let id = id / EXTRA_CHARS.len(); let extra3 = id % EXTRA_CHARS.len(); - hash.push_char(EXTRA_CHARS[extra1] as char); - hash.push_char(EXTRA_CHARS[extra2] as char); - hash.push_char(EXTRA_CHARS[extra3] as char); + hash.push_char(EXTRA_CHARS.as_bytes()[extra1] as char); + hash.push_char(EXTRA_CHARS.as_bytes()[extra2] as char); + hash.push_char(EXTRA_CHARS.as_bytes()[extra3] as char); exported_name(path, hash.as_slice(), diff --git a/src/librustc/back/lto.rs b/src/librustc/back/lto.rs index 7449622366f..b9ae9530f8e 100644 --- a/src/librustc/back/lto.rs +++ b/src/librustc/back/lto.rs @@ -82,7 +82,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, (), |()| unsafe { if !llvm::LLVMRustLinkInExternalBitcode(llmod, - ptr as *libc::c_char, + ptr as *const libc::c_char, bc.len() as libc::size_t) { link::llvm_err(sess, format!("failed to load bc of `{}`", @@ -94,10 +94,11 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, // Internalize everything but the reachable symbols of the current module let cstrs: Vec<::std::c_str::CString> = reachable.iter().map(|s| s.as_slice().to_c_str()).collect(); - let arr: Vec<*i8> = cstrs.iter().map(|c| c.with_ref(|p| p)).collect(); + let arr: Vec<*const i8> = cstrs.iter().map(|c| c.as_ptr()).collect(); let ptr = arr.as_ptr(); unsafe { - llvm::LLVMRustRunRestrictionPass(llmod, ptr as **libc::c_char, + llvm::LLVMRustRunRestrictionPass(llmod, + ptr as *const *const libc::c_char, arr.len() as libc::size_t); } diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index d6f1bfeb9ef..d07e74493be 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -255,45 +255,45 @@ pub enum CodeGenModel { // Opaque pointer types pub enum Module_opaque {} -pub type ModuleRef = *Module_opaque; +pub type ModuleRef = *mut Module_opaque; pub enum Context_opaque {} -pub type ContextRef = *Context_opaque; +pub type ContextRef = *mut Context_opaque; pub enum Type_opaque {} -pub type TypeRef = *Type_opaque; +pub type TypeRef = *mut Type_opaque; pub enum Value_opaque {} -pub type ValueRef = *Value_opaque; +pub type ValueRef = *mut Value_opaque; pub enum BasicBlock_opaque {} -pub type BasicBlockRef = *BasicBlock_opaque; +pub type BasicBlockRef = *mut BasicBlock_opaque; pub enum Builder_opaque {} -pub type BuilderRef = *Builder_opaque; +pub type BuilderRef = *mut Builder_opaque; pub enum ExecutionEngine_opaque {} -pub type ExecutionEngineRef = *ExecutionEngine_opaque; +pub type ExecutionEngineRef = *mut ExecutionEngine_opaque; pub enum MemoryBuffer_opaque {} -pub type MemoryBufferRef = *MemoryBuffer_opaque; +pub type MemoryBufferRef = *mut MemoryBuffer_opaque; pub enum PassManager_opaque {} -pub type PassManagerRef = *PassManager_opaque; +pub type PassManagerRef = *mut PassManager_opaque; pub enum PassManagerBuilder_opaque {} -pub type PassManagerBuilderRef = *PassManagerBuilder_opaque; +pub type PassManagerBuilderRef = *mut PassManagerBuilder_opaque; pub enum Use_opaque {} -pub type UseRef = *Use_opaque; +pub type UseRef = *mut Use_opaque; pub enum TargetData_opaque {} -pub type TargetDataRef = *TargetData_opaque; +pub type TargetDataRef = *mut TargetData_opaque; pub enum ObjectFile_opaque {} -pub type ObjectFileRef = *ObjectFile_opaque; +pub type ObjectFileRef = *mut ObjectFile_opaque; pub enum SectionIterator_opaque {} -pub type SectionIteratorRef = *SectionIterator_opaque; +pub type SectionIteratorRef = *mut SectionIterator_opaque; pub enum Pass_opaque {} -pub type PassRef = *Pass_opaque; +pub type PassRef = *mut Pass_opaque; pub enum TargetMachine_opaque {} -pub type TargetMachineRef = *TargetMachine_opaque; +pub type TargetMachineRef = *mut TargetMachine_opaque; pub enum Archive_opaque {} -pub type ArchiveRef = *Archive_opaque; +pub type ArchiveRef = *mut Archive_opaque; pub mod debuginfo { use super::{ValueRef}; pub enum DIBuilder_opaque {} - pub type DIBuilderRef = *DIBuilder_opaque; + pub type DIBuilderRef = *mut DIBuilder_opaque; pub type DIDescriptor = ValueRef; pub type DIScope = DIDescriptor; @@ -354,30 +354,30 @@ pub mod llvm { pub fn LLVMContextCreate() -> ContextRef; pub fn LLVMContextDispose(C: ContextRef); pub fn LLVMGetMDKindIDInContext(C: ContextRef, - Name: *c_char, + Name: *const c_char, SLen: c_uint) -> c_uint; /* Create and destroy modules. */ - pub fn LLVMModuleCreateWithNameInContext(ModuleID: *c_char, + pub fn LLVMModuleCreateWithNameInContext(ModuleID: *const c_char, C: ContextRef) -> ModuleRef; pub fn LLVMGetModuleContext(M: ModuleRef) -> ContextRef; pub fn LLVMDisposeModule(M: ModuleRef); /** Data layout. See Module::getDataLayout. */ - pub fn LLVMGetDataLayout(M: ModuleRef) -> *c_char; - pub fn LLVMSetDataLayout(M: ModuleRef, Triple: *c_char); + pub fn LLVMGetDataLayout(M: ModuleRef) -> *const c_char; + pub fn LLVMSetDataLayout(M: ModuleRef, Triple: *const c_char); /** Target triple. See Module::getTargetTriple. */ - pub fn LLVMGetTarget(M: ModuleRef) -> *c_char; - pub fn LLVMSetTarget(M: ModuleRef, Triple: *c_char); + pub fn LLVMGetTarget(M: ModuleRef) -> *const c_char; + pub fn LLVMSetTarget(M: ModuleRef, Triple: *const c_char); /** See Module::dump. */ pub fn LLVMDumpModule(M: ModuleRef); /** See Module::setModuleInlineAsm. */ - pub fn LLVMSetModuleInlineAsm(M: ModuleRef, Asm: *c_char); + pub fn LLVMSetModuleInlineAsm(M: ModuleRef, Asm: *const c_char); /** See llvm::LLVMTypeKind::getTypeID. */ pub fn LLVMGetTypeKind(Ty: TypeRef) -> TypeKind; @@ -405,18 +405,18 @@ pub mod llvm { /* Operations on function types */ pub fn LLVMFunctionType(ReturnType: TypeRef, - ParamTypes: *TypeRef, + ParamTypes: *const TypeRef, ParamCount: c_uint, IsVarArg: Bool) -> TypeRef; pub fn LLVMIsFunctionVarArg(FunctionTy: TypeRef) -> Bool; pub fn LLVMGetReturnType(FunctionTy: TypeRef) -> TypeRef; pub fn LLVMCountParamTypes(FunctionTy: TypeRef) -> c_uint; - pub fn LLVMGetParamTypes(FunctionTy: TypeRef, Dest: *TypeRef); + pub fn LLVMGetParamTypes(FunctionTy: TypeRef, Dest: *const TypeRef); /* Operations on struct types */ pub fn LLVMStructTypeInContext(C: ContextRef, - ElementTypes: *TypeRef, + ElementTypes: *const TypeRef, ElementCount: c_uint, Packed: Bool) -> TypeRef; @@ -436,7 +436,7 @@ pub mod llvm { pub fn LLVMGetArrayLength(ArrayTy: TypeRef) -> c_uint; pub fn LLVMGetPointerAddressSpace(PointerTy: TypeRef) -> c_uint; pub fn LLVMGetPointerToGlobal(EE: ExecutionEngineRef, V: ValueRef) - -> *(); + -> *const (); pub fn LLVMGetVectorSize(VectorTy: TypeRef) -> c_uint; /* Operations on other types */ @@ -446,8 +446,8 @@ pub mod llvm { /* Operations on all values */ pub fn LLVMTypeOf(Val: ValueRef) -> TypeRef; - pub fn LLVMGetValueName(Val: ValueRef) -> *c_char; - pub fn LLVMSetValueName(Val: ValueRef, Name: *c_char); + pub fn LLVMGetValueName(Val: ValueRef) -> *const c_char; + pub fn LLVMSetValueName(Val: ValueRef, Name: *const c_char); pub fn LLVMDumpValue(Val: ValueRef); pub fn LLVMReplaceAllUsesWith(OldVal: ValueRef, NewVal: ValueRef); pub fn LLVMHasMetadata(Val: ValueRef) -> c_int; @@ -482,32 +482,32 @@ pub mod llvm { /* Operations on metadata */ pub fn LLVMMDStringInContext(C: ContextRef, - Str: *c_char, + Str: *const c_char, SLen: c_uint) -> ValueRef; pub fn LLVMMDNodeInContext(C: ContextRef, - Vals: *ValueRef, + Vals: *const ValueRef, Count: c_uint) -> ValueRef; pub fn LLVMAddNamedMetadataOperand(M: ModuleRef, - Str: *c_char, + Str: *const c_char, Val: ValueRef); /* Operations on scalar constants */ pub fn LLVMConstInt(IntTy: TypeRef, N: c_ulonglong, SignExtend: Bool) -> ValueRef; - pub fn LLVMConstIntOfString(IntTy: TypeRef, Text: *c_char, Radix: u8) + pub fn LLVMConstIntOfString(IntTy: TypeRef, Text: *const c_char, Radix: u8) -> ValueRef; pub fn LLVMConstIntOfStringAndSize(IntTy: TypeRef, - Text: *c_char, + Text: *const c_char, SLen: c_uint, Radix: u8) -> ValueRef; pub fn LLVMConstReal(RealTy: TypeRef, N: f64) -> ValueRef; - pub fn LLVMConstRealOfString(RealTy: TypeRef, Text: *c_char) + pub fn LLVMConstRealOfString(RealTy: TypeRef, Text: *const c_char) -> ValueRef; pub fn LLVMConstRealOfStringAndSize(RealTy: TypeRef, - Text: *c_char, + Text: *const c_char, SLen: c_uint) -> ValueRef; pub fn LLVMConstIntGetZExtValue(ConstantVal: ValueRef) -> c_ulonglong; @@ -516,21 +516,21 @@ pub mod llvm { /* Operations on composite constants */ pub fn LLVMConstStringInContext(C: ContextRef, - Str: *c_char, + Str: *const c_char, Length: c_uint, DontNullTerminate: Bool) -> ValueRef; pub fn LLVMConstStructInContext(C: ContextRef, - ConstantVals: *ValueRef, + ConstantVals: *const ValueRef, Count: c_uint, Packed: Bool) -> ValueRef; pub fn LLVMConstArray(ElementTy: TypeRef, - ConstantVals: *ValueRef, + ConstantVals: *const ValueRef, Length: c_uint) -> ValueRef; - pub fn LLVMConstVector(ScalarConstantVals: *ValueRef, Size: c_uint) + pub fn LLVMConstVector(ScalarConstantVals: *const ValueRef, Size: c_uint) -> ValueRef; /* Constant expressions */ @@ -593,11 +593,11 @@ pub mod llvm { pub fn LLVMConstAShr(LHSConstant: ValueRef, RHSConstant: ValueRef) -> ValueRef; pub fn LLVMConstGEP(ConstantVal: ValueRef, - ConstantIndices: *ValueRef, + ConstantIndices: *const ValueRef, NumIndices: c_uint) -> ValueRef; pub fn LLVMConstInBoundsGEP(ConstantVal: ValueRef, - ConstantIndices: *ValueRef, + ConstantIndices: *const ValueRef, NumIndices: c_uint) -> ValueRef; pub fn LLVMConstTrunc(ConstantVal: ValueRef, ToType: TypeRef) @@ -654,17 +654,17 @@ pub mod llvm { MaskConstant: ValueRef) -> ValueRef; pub fn LLVMConstExtractValue(AggConstant: ValueRef, - IdxList: *c_uint, + IdxList: *const c_uint, NumIdx: c_uint) -> ValueRef; pub fn LLVMConstInsertValue(AggConstant: ValueRef, ElementValueConstant: ValueRef, - IdxList: *c_uint, + IdxList: *const c_uint, NumIdx: c_uint) -> ValueRef; pub fn LLVMConstInlineAsm(Ty: TypeRef, - AsmString: *c_char, - Constraints: *c_char, + AsmString: *const c_char, + Constraints: *const c_char, HasSideEffects: Bool, IsAlignStack: Bool) -> ValueRef; @@ -677,8 +677,8 @@ pub mod llvm { pub fn LLVMIsDeclaration(Global: ValueRef) -> Bool; pub fn LLVMGetLinkage(Global: ValueRef) -> c_uint; pub fn LLVMSetLinkage(Global: ValueRef, Link: c_uint); - pub fn LLVMGetSection(Global: ValueRef) -> *c_char; - pub fn LLVMSetSection(Global: ValueRef, Section: *c_char); + pub fn LLVMGetSection(Global: ValueRef) -> *const c_char; + pub fn LLVMSetSection(Global: ValueRef, Section: *const c_char); pub fn LLVMGetVisibility(Global: ValueRef) -> c_uint; pub fn LLVMSetVisibility(Global: ValueRef, Viz: c_uint); pub fn LLVMGetAlignment(Global: ValueRef) -> c_uint; @@ -686,14 +686,14 @@ pub mod llvm { /* Operations on global variables */ - pub fn LLVMAddGlobal(M: ModuleRef, Ty: TypeRef, Name: *c_char) + pub fn LLVMAddGlobal(M: ModuleRef, Ty: TypeRef, Name: *const c_char) -> ValueRef; pub fn LLVMAddGlobalInAddressSpace(M: ModuleRef, Ty: TypeRef, - Name: *c_char, + Name: *const c_char, AddressSpace: c_uint) -> ValueRef; - pub fn LLVMGetNamedGlobal(M: ModuleRef, Name: *c_char) -> ValueRef; + pub fn LLVMGetNamedGlobal(M: ModuleRef, Name: *const c_char) -> ValueRef; pub fn LLVMGetFirstGlobal(M: ModuleRef) -> ValueRef; pub fn LLVMGetLastGlobal(M: ModuleRef) -> ValueRef; pub fn LLVMGetNextGlobal(GlobalVar: ValueRef) -> ValueRef; @@ -711,37 +711,37 @@ pub mod llvm { pub fn LLVMAddAlias(M: ModuleRef, Ty: TypeRef, Aliasee: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; /* Operations on functions */ pub fn LLVMAddFunction(M: ModuleRef, - Name: *c_char, + Name: *const c_char, FunctionTy: TypeRef) -> ValueRef; - pub fn LLVMGetNamedFunction(M: ModuleRef, Name: *c_char) -> ValueRef; + pub fn LLVMGetNamedFunction(M: ModuleRef, Name: *const c_char) -> ValueRef; pub fn LLVMGetFirstFunction(M: ModuleRef) -> ValueRef; pub fn LLVMGetLastFunction(M: ModuleRef) -> ValueRef; pub fn LLVMGetNextFunction(Fn: ValueRef) -> ValueRef; pub fn LLVMGetPreviousFunction(Fn: ValueRef) -> ValueRef; pub fn LLVMDeleteFunction(Fn: ValueRef); pub fn LLVMGetOrInsertFunction(M: ModuleRef, - Name: *c_char, + Name: *const c_char, FunctionTy: TypeRef) -> ValueRef; pub fn LLVMGetIntrinsicID(Fn: ValueRef) -> c_uint; pub fn LLVMGetFunctionCallConv(Fn: ValueRef) -> c_uint; pub fn LLVMSetFunctionCallConv(Fn: ValueRef, CC: c_uint); - pub fn LLVMGetGC(Fn: ValueRef) -> *c_char; - pub fn LLVMSetGC(Fn: ValueRef, Name: *c_char); + pub fn LLVMGetGC(Fn: ValueRef) -> *const c_char; + pub fn LLVMSetGC(Fn: ValueRef, Name: *const c_char); pub fn LLVMAddFunctionAttribute(Fn: ValueRef, index: c_uint, PA: uint64_t); - pub fn LLVMAddFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *c_char); - pub fn LLVMRemoveFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *c_char); + pub fn LLVMAddFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char); + pub fn LLVMRemoveFunctionAttrString(Fn: ValueRef, index: c_uint, Name: *const c_char); pub fn LLVMGetFunctionAttr(Fn: ValueRef) -> c_ulonglong; /* Operations on parameters */ pub fn LLVMCountParams(Fn: ValueRef) -> c_uint; - pub fn LLVMGetParams(Fn: ValueRef, Params: *ValueRef); + pub fn LLVMGetParams(Fn: ValueRef, Params: *const ValueRef); pub fn LLVMGetParam(Fn: ValueRef, Index: c_uint) -> ValueRef; pub fn LLVMGetParamParent(Inst: ValueRef) -> ValueRef; pub fn LLVMGetFirstParam(Fn: ValueRef) -> ValueRef; @@ -759,7 +759,7 @@ pub mod llvm { pub fn LLVMValueAsBasicBlock(Val: ValueRef) -> BasicBlockRef; pub fn LLVMGetBasicBlockParent(BB: BasicBlockRef) -> ValueRef; pub fn LLVMCountBasicBlocks(Fn: ValueRef) -> c_uint; - pub fn LLVMGetBasicBlocks(Fn: ValueRef, BasicBlocks: *ValueRef); + pub fn LLVMGetBasicBlocks(Fn: ValueRef, BasicBlocks: *const ValueRef); pub fn LLVMGetFirstBasicBlock(Fn: ValueRef) -> BasicBlockRef; pub fn LLVMGetLastBasicBlock(Fn: ValueRef) -> BasicBlockRef; pub fn LLVMGetNextBasicBlock(BB: BasicBlockRef) -> BasicBlockRef; @@ -768,11 +768,11 @@ pub mod llvm { pub fn LLVMAppendBasicBlockInContext(C: ContextRef, Fn: ValueRef, - Name: *c_char) + Name: *const c_char) -> BasicBlockRef; pub fn LLVMInsertBasicBlockInContext(C: ContextRef, BB: BasicBlockRef, - Name: *c_char) + Name: *const c_char) -> BasicBlockRef; pub fn LLVMDeleteBasicBlock(BB: BasicBlockRef); @@ -816,8 +816,8 @@ pub mod llvm { /* Operations on phi nodes */ pub fn LLVMAddIncoming(PhiNode: ValueRef, - IncomingValues: *ValueRef, - IncomingBlocks: *BasicBlockRef, + IncomingValues: *const ValueRef, + IncomingBlocks: *const BasicBlockRef, Count: c_uint); pub fn LLVMCountIncoming(PhiNode: ValueRef) -> c_uint; pub fn LLVMGetIncomingValue(PhiNode: ValueRef, Index: c_uint) @@ -839,7 +839,7 @@ pub mod llvm { pub fn LLVMInsertIntoBuilder(Builder: BuilderRef, Instr: ValueRef); pub fn LLVMInsertIntoBuilderWithName(Builder: BuilderRef, Instr: ValueRef, - Name: *c_char); + Name: *const c_char); pub fn LLVMDisposeBuilder(Builder: BuilderRef); pub fn LLVMDisposeExecutionEngine(EE: ExecutionEngineRef); @@ -852,7 +852,7 @@ pub mod llvm { pub fn LLVMBuildRetVoid(B: BuilderRef) -> ValueRef; pub fn LLVMBuildRet(B: BuilderRef, V: ValueRef) -> ValueRef; pub fn LLVMBuildAggregateRet(B: BuilderRef, - RetVals: *ValueRef, + RetVals: *const ValueRef, N: c_uint) -> ValueRef; pub fn LLVMBuildBr(B: BuilderRef, Dest: BasicBlockRef) -> ValueRef; @@ -872,17 +872,17 @@ pub mod llvm { -> ValueRef; pub fn LLVMBuildInvoke(B: BuilderRef, Fn: ValueRef, - Args: *ValueRef, + Args: *const ValueRef, NumArgs: c_uint, Then: BasicBlockRef, Catch: BasicBlockRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildLandingPad(B: BuilderRef, Ty: TypeRef, PersFn: ValueRef, NumClauses: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildResume(B: BuilderRef, Exn: ValueRef) -> ValueRef; pub fn LLVMBuildUnreachable(B: BuilderRef) -> ValueRef; @@ -905,164 +905,164 @@ pub mod llvm { pub fn LLVMBuildAdd(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNSWAdd(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNUWAdd(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFAdd(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSub(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNSWSub(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNUWSub(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFSub(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildMul(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNSWMul(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildNUWMul(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFMul(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildUDiv(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSDiv(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildExactSDiv(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFDiv(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildURem(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSRem(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFRem(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildShl(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildLShr(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildAShr(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildAnd(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildOr(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildXor(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildBinOp(B: BuilderRef, Op: Opcode, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; - pub fn LLVMBuildNeg(B: BuilderRef, V: ValueRef, Name: *c_char) + pub fn LLVMBuildNeg(B: BuilderRef, V: ValueRef, Name: *const c_char) -> ValueRef; - pub fn LLVMBuildNSWNeg(B: BuilderRef, V: ValueRef, Name: *c_char) + pub fn LLVMBuildNSWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char) -> ValueRef; - pub fn LLVMBuildNUWNeg(B: BuilderRef, V: ValueRef, Name: *c_char) + pub fn LLVMBuildNUWNeg(B: BuilderRef, V: ValueRef, Name: *const c_char) -> ValueRef; - pub fn LLVMBuildFNeg(B: BuilderRef, V: ValueRef, Name: *c_char) + pub fn LLVMBuildFNeg(B: BuilderRef, V: ValueRef, Name: *const c_char) -> ValueRef; - pub fn LLVMBuildNot(B: BuilderRef, V: ValueRef, Name: *c_char) + pub fn LLVMBuildNot(B: BuilderRef, V: ValueRef, Name: *const c_char) -> ValueRef; /* Memory */ - pub fn LLVMBuildMalloc(B: BuilderRef, Ty: TypeRef, Name: *c_char) + pub fn LLVMBuildMalloc(B: BuilderRef, Ty: TypeRef, Name: *const c_char) -> ValueRef; pub fn LLVMBuildArrayMalloc(B: BuilderRef, Ty: TypeRef, Val: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; - pub fn LLVMBuildAlloca(B: BuilderRef, Ty: TypeRef, Name: *c_char) + pub fn LLVMBuildAlloca(B: BuilderRef, Ty: TypeRef, Name: *const c_char) -> ValueRef; pub fn LLVMBuildArrayAlloca(B: BuilderRef, Ty: TypeRef, Val: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFree(B: BuilderRef, PointerVal: ValueRef) -> ValueRef; pub fn LLVMBuildLoad(B: BuilderRef, PointerVal: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildStore(B: BuilderRef, Val: ValueRef, Ptr: ValueRef) @@ -1070,125 +1070,125 @@ pub mod llvm { pub fn LLVMBuildGEP(B: BuilderRef, Pointer: ValueRef, - Indices: *ValueRef, + Indices: *const ValueRef, NumIndices: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildInBoundsGEP(B: BuilderRef, Pointer: ValueRef, - Indices: *ValueRef, + Indices: *const ValueRef, NumIndices: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildStructGEP(B: BuilderRef, Pointer: ValueRef, Idx: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildGlobalString(B: BuilderRef, - Str: *c_char, - Name: *c_char) + Str: *const c_char, + Name: *const c_char) -> ValueRef; pub fn LLVMBuildGlobalStringPtr(B: BuilderRef, - Str: *c_char, - Name: *c_char) + Str: *const c_char, + Name: *const c_char) -> ValueRef; /* Casts */ pub fn LLVMBuildTrunc(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildZExt(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSExt(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFPToUI(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFPToSI(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildUIToFP(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSIToFP(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFPTrunc(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFPExt(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildPtrToInt(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildIntToPtr(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildBitCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildZExtOrBitCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSExtOrBitCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildTruncOrBitCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildCast(B: BuilderRef, Op: Opcode, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) -> ValueRef; + Name: *const c_char) -> ValueRef; pub fn LLVMBuildPointerCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildIntCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFPCast(B: BuilderRef, Val: ValueRef, DestTy: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; /* Comparisons */ @@ -1196,78 +1196,78 @@ pub mod llvm { Op: c_uint, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildFCmp(B: BuilderRef, Op: c_uint, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; /* Miscellaneous instructions */ - pub fn LLVMBuildPhi(B: BuilderRef, Ty: TypeRef, Name: *c_char) + pub fn LLVMBuildPhi(B: BuilderRef, Ty: TypeRef, Name: *const c_char) -> ValueRef; pub fn LLVMBuildCall(B: BuilderRef, Fn: ValueRef, - Args: *ValueRef, + Args: *const ValueRef, NumArgs: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildSelect(B: BuilderRef, If: ValueRef, Then: ValueRef, Else: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildVAArg(B: BuilderRef, list: ValueRef, Ty: TypeRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildExtractElement(B: BuilderRef, VecVal: ValueRef, Index: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildInsertElement(B: BuilderRef, VecVal: ValueRef, EltVal: ValueRef, Index: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildShuffleVector(B: BuilderRef, V1: ValueRef, V2: ValueRef, Mask: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildExtractValue(B: BuilderRef, AggVal: ValueRef, Index: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; pub fn LLVMBuildInsertValue(B: BuilderRef, AggVal: ValueRef, EltVal: ValueRef, Index: c_uint, - Name: *c_char) + Name: *const c_char) -> ValueRef; - pub fn LLVMBuildIsNull(B: BuilderRef, Val: ValueRef, Name: *c_char) + pub fn LLVMBuildIsNull(B: BuilderRef, Val: ValueRef, Name: *const c_char) -> ValueRef; - pub fn LLVMBuildIsNotNull(B: BuilderRef, Val: ValueRef, Name: *c_char) + pub fn LLVMBuildIsNotNull(B: BuilderRef, Val: ValueRef, Name: *const c_char) -> ValueRef; pub fn LLVMBuildPtrDiff(B: BuilderRef, LHS: ValueRef, RHS: ValueRef, - Name: *c_char) + Name: *const c_char) -> ValueRef; /* Atomic Operations */ pub fn LLVMBuildAtomicLoad(B: BuilderRef, PointerVal: ValueRef, - Name: *c_char, + Name: *const c_char, Order: AtomicOrdering, Alignment: c_uint) -> ValueRef; @@ -1302,10 +1302,10 @@ pub mod llvm { pub fn LLVMIsAStoreInst(Inst: ValueRef) -> ValueRef; /** Writes a module to the specified path. Returns 0 on success. */ - pub fn LLVMWriteBitcodeToFile(M: ModuleRef, Path: *c_char) -> c_int; + pub fn LLVMWriteBitcodeToFile(M: ModuleRef, Path: *const c_char) -> c_int; /** Creates target data from a target layout string. */ - pub fn LLVMCreateTargetData(StringRep: *c_char) -> TargetDataRef; + pub fn LLVMCreateTargetData(StringRep: *const c_char) -> TargetDataRef; /// Adds the target data to the given pass manager. The pass manager /// references the target data only weakly. pub fn LLVMAddTargetData(TD: TargetDataRef, PM: PassManagerRef); @@ -1464,21 +1464,21 @@ pub mod llvm { /** Returns the current section size. */ pub fn LLVMGetSectionSize(SI: SectionIteratorRef) -> c_ulonglong; /** Returns the current section contents as a string buffer. */ - pub fn LLVMGetSectionContents(SI: SectionIteratorRef) -> *c_char; + pub fn LLVMGetSectionContents(SI: SectionIteratorRef) -> *const c_char; /** Reads the given file and returns it as a memory buffer. Use LLVMDisposeMemoryBuffer() to get rid of it. */ - pub fn LLVMRustCreateMemoryBufferWithContentsOfFile(Path: *c_char) + pub fn LLVMRustCreateMemoryBufferWithContentsOfFile(Path: *const c_char) -> MemoryBufferRef; /** Borrows the contents of the memory buffer (doesn't copy it) */ - pub fn LLVMCreateMemoryBufferWithMemoryRange(InputData: *c_char, + pub fn LLVMCreateMemoryBufferWithMemoryRange(InputData: *const c_char, InputDataLength: size_t, - BufferName: *c_char, + BufferName: *const c_char, RequiresNull: Bool) -> MemoryBufferRef; - pub fn LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: *c_char, + pub fn LLVMCreateMemoryBufferWithMemoryRangeCopy(InputData: *const c_char, InputDataLength: size_t, - BufferName: *c_char) + BufferName: *const c_char) -> MemoryBufferRef; pub fn LLVMIsMultithreaded() -> Bool; @@ -1486,20 +1486,20 @@ pub mod llvm { /** Returns a string describing the last error caused by an LLVMRust* call. */ - pub fn LLVMRustGetLastError() -> *c_char; + pub fn LLVMRustGetLastError() -> *const c_char; /// Print the pass timings since static dtors aren't picking them up. pub fn LLVMRustPrintPassTimings(); - pub fn LLVMStructCreateNamed(C: ContextRef, Name: *c_char) -> TypeRef; + pub fn LLVMStructCreateNamed(C: ContextRef, Name: *const c_char) -> TypeRef; pub fn LLVMStructSetBody(StructTy: TypeRef, - ElementTypes: *TypeRef, + ElementTypes: *const TypeRef, ElementCount: c_uint, Packed: Bool); pub fn LLVMConstNamedStruct(S: TypeRef, - ConstantVals: *ValueRef, + ConstantVals: *const ValueRef, Count: c_uint) -> ValueRef; @@ -1508,8 +1508,8 @@ pub mod llvm { /** Prepares inline assembly. */ pub fn LLVMInlineAsm(Ty: TypeRef, - AsmString: *c_char, - Constraints: *c_char, + AsmString: *const c_char, + Constraints: *const c_char, SideEffects: Bool, AlignStack: Bool, Dialect: c_uint) @@ -1518,7 +1518,7 @@ pub mod llvm { pub static LLVMRustDebugMetadataVersion: u32; pub fn LLVMRustAddModuleFlag(M: ModuleRef, - name: *c_char, + name: *const c_char, value: u32); pub fn LLVMDIBuilderCreate(M: ModuleRef) -> DIBuilderRef; @@ -1529,17 +1529,17 @@ pub mod llvm { pub fn LLVMDIBuilderCreateCompileUnit(Builder: DIBuilderRef, Lang: c_uint, - File: *c_char, - Dir: *c_char, - Producer: *c_char, + File: *const c_char, + Dir: *const c_char, + Producer: *const c_char, isOptimized: bool, - Flags: *c_char, + Flags: *const c_char, RuntimeVer: c_uint, - SplitName: *c_char); + SplitName: *const c_char); pub fn LLVMDIBuilderCreateFile(Builder: DIBuilderRef, - Filename: *c_char, - Directory: *c_char) + Filename: *const c_char, + Directory: *const c_char) -> DIFile; pub fn LLVMDIBuilderCreateSubroutineType(Builder: DIBuilderRef, @@ -1549,8 +1549,8 @@ pub mod llvm { pub fn LLVMDIBuilderCreateFunction(Builder: DIBuilderRef, Scope: DIDescriptor, - Name: *c_char, - LinkageName: *c_char, + Name: *const c_char, + LinkageName: *const c_char, File: DIFile, LineNo: c_uint, Ty: DIType, @@ -1565,7 +1565,7 @@ pub mod llvm { -> DISubprogram; pub fn LLVMDIBuilderCreateBasicType(Builder: DIBuilderRef, - Name: *c_char, + Name: *const c_char, SizeInBits: c_ulonglong, AlignInBits: c_ulonglong, Encoding: c_uint) @@ -1575,12 +1575,12 @@ pub mod llvm { PointeeTy: DIType, SizeInBits: c_ulonglong, AlignInBits: c_ulonglong, - Name: *c_char) + Name: *const c_char) -> DIDerivedType; pub fn LLVMDIBuilderCreateStructType(Builder: DIBuilderRef, Scope: DIDescriptor, - Name: *c_char, + Name: *const c_char, File: DIFile, LineNumber: c_uint, SizeInBits: c_ulonglong, @@ -1590,12 +1590,12 @@ pub mod llvm { Elements: DIArray, RunTimeLang: c_uint, VTableHolder: ValueRef, - UniqueId: *c_char) + UniqueId: *const c_char) -> DICompositeType; pub fn LLVMDIBuilderCreateMemberType(Builder: DIBuilderRef, Scope: DIDescriptor, - Name: *c_char, + Name: *const c_char, File: DIFile, LineNo: c_uint, SizeInBits: c_ulonglong, @@ -1615,8 +1615,8 @@ pub mod llvm { pub fn LLVMDIBuilderCreateStaticVariable(Builder: DIBuilderRef, Context: DIDescriptor, - Name: *c_char, - LinkageName: *c_char, + Name: *const c_char, + LinkageName: *const c_char, File: DIFile, LineNo: c_uint, Ty: DIType, @@ -1628,7 +1628,7 @@ pub mod llvm { pub fn LLVMDIBuilderCreateLocalVariable(Builder: DIBuilderRef, Tag: c_uint, Scope: DIDescriptor, - Name: *c_char, + Name: *const c_char, File: DIFile, LineNo: c_uint, Ty: DIType, @@ -1657,7 +1657,7 @@ pub mod llvm { -> DISubrange; pub fn LLVMDIBuilderGetOrCreateArray(Builder: DIBuilderRef, - Ptr: *DIDescriptor, + Ptr: *const DIDescriptor, Count: c_uint) -> DIArray; @@ -1674,13 +1674,13 @@ pub mod llvm { -> ValueRef; pub fn LLVMDIBuilderCreateEnumerator(Builder: DIBuilderRef, - Name: *c_char, + Name: *const c_char, Val: c_ulonglong) -> ValueRef; pub fn LLVMDIBuilderCreateEnumerationType(Builder: DIBuilderRef, Scope: ValueRef, - Name: *c_char, + Name: *const c_char, File: ValueRef, LineNumber: c_uint, SizeInBits: c_ulonglong, @@ -1691,7 +1691,7 @@ pub mod llvm { pub fn LLVMDIBuilderCreateUnionType(Builder: DIBuilderRef, Scope: ValueRef, - Name: *c_char, + Name: *const c_char, File: ValueRef, LineNumber: c_uint, SizeInBits: c_ulonglong, @@ -1699,14 +1699,14 @@ pub mod llvm { Flags: c_uint, Elements: ValueRef, RunTimeLang: c_uint, - UniqueId: *c_char) + UniqueId: *const c_char) -> ValueRef; pub fn LLVMSetUnnamedAddr(GlobalVar: ValueRef, UnnamedAddr: Bool); pub fn LLVMDIBuilderCreateTemplateTypeParameter(Builder: DIBuilderRef, Scope: ValueRef, - Name: *c_char, + Name: *const c_char, Ty: ValueRef, File: ValueRef, LineNo: c_uint, @@ -1720,25 +1720,25 @@ pub mod llvm { pub fn LLVMDIBuilderCreateComplexVariable(Builder: DIBuilderRef, Tag: c_uint, Scope: ValueRef, - Name: *c_char, + Name: *const c_char, File: ValueRef, LineNo: c_uint, Ty: ValueRef, - AddrOps: *ValueRef, + AddrOps: *const ValueRef, AddrOpsCount: c_uint, ArgNo: c_uint) -> ValueRef; pub fn LLVMDIBuilderCreateNameSpace(Builder: DIBuilderRef, Scope: ValueRef, - Name: *c_char, + Name: *const c_char, File: ValueRef, LineNo: c_uint) -> ValueRef; pub fn LLVMDICompositeTypeSetTypeArray(CompositeType: ValueRef, TypeArray: ValueRef); - pub fn LLVMTypeToString(Type: TypeRef) -> *c_char; - pub fn LLVMValueToString(value_ref: ValueRef) -> *c_char; + pub fn LLVMTypeToString(Type: TypeRef) -> *const c_char; + pub fn LLVMValueToString(value_ref: ValueRef) -> *const c_char; pub fn LLVMIsAArgument(value_ref: ValueRef) -> ValueRef; @@ -1760,10 +1760,10 @@ pub mod llvm { pub fn LLVMInitializeMipsAsmPrinter(); pub fn LLVMInitializeMipsAsmParser(); - pub fn LLVMRustAddPass(PM: PassManagerRef, Pass: *c_char) -> bool; - pub fn LLVMRustCreateTargetMachine(Triple: *c_char, - CPU: *c_char, - Features: *c_char, + pub fn LLVMRustAddPass(PM: PassManagerRef, Pass: *const c_char) -> bool; + pub fn LLVMRustCreateTargetMachine(Triple: *const c_char, + CPU: *const c_char, + Features: *const c_char, Model: CodeGenModel, Reloc: RelocMode, Level: CodeGenOptLevel, @@ -1785,27 +1785,27 @@ pub mod llvm { pub fn LLVMRustWriteOutputFile(T: TargetMachineRef, PM: PassManagerRef, M: ModuleRef, - Output: *c_char, + Output: *const c_char, FileType: FileType) -> bool; pub fn LLVMRustPrintModule(PM: PassManagerRef, M: ModuleRef, - Output: *c_char); - pub fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: **c_char); + Output: *const c_char); + pub fn LLVMRustSetLLVMOptions(Argc: c_int, Argv: *const *const c_char); pub fn LLVMRustPrintPasses(); - pub fn LLVMRustSetNormalizedTarget(M: ModuleRef, triple: *c_char); + pub fn LLVMRustSetNormalizedTarget(M: ModuleRef, triple: *const c_char); pub fn LLVMRustAddAlwaysInlinePass(P: PassManagerBuilderRef, AddLifetimes: bool); pub fn LLVMRustLinkInExternalBitcode(M: ModuleRef, - bc: *c_char, + bc: *const c_char, len: size_t) -> bool; pub fn LLVMRustRunRestrictionPass(M: ModuleRef, - syms: **c_char, + syms: *const *const c_char, len: size_t); pub fn LLVMRustMarkAllFunctionsNounwind(M: ModuleRef); - pub fn LLVMRustOpenArchive(path: *c_char) -> ArchiveRef; - pub fn LLVMRustArchiveReadSection(AR: ArchiveRef, name: *c_char, - out_len: *mut size_t) -> *c_char; + pub fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef; + pub fn LLVMRustArchiveReadSection(AR: ArchiveRef, name: *const c_char, + out_len: *mut size_t) -> *const c_char; pub fn LLVMRustDestroyArchive(AR: ArchiveRef); pub fn LLVMRustSetDLLExportStorageClass(V: ValueRef); @@ -1813,7 +1813,7 @@ pub mod llvm { pub fn LLVMVersionMinor() -> c_int; pub fn LLVMRustGetSectionName(SI: SectionIteratorRef, - data: *mut *c_char) -> c_int; + data: *mut *const c_char) -> c_int; } } diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 5078ae80d75..30296cb3186 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -30,7 +30,7 @@ use middle::def::*; 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}; +use middle::{typeck, ty, def, pat_util, stability}; use util::ppaux::{ty_to_str}; use util::nodemap::NodeSet; use lint::{Context, LintPass, LintArray}; @@ -391,8 +391,8 @@ pub struct HeapMemory; impl HeapMemory { fn check_heap_type(&self, cx: &Context, span: Span, ty: ty::t) { - let mut n_box = 0; - let mut n_uniq = 0; + let mut n_box = 0i; + let mut n_uniq = 0i; ty::fold_ty(cx.tcx, ty, |t| { match ty::get(t).sty { ty::ty_box(_) => { @@ -975,14 +975,52 @@ declare_lint!(UNNECESSARY_PARENS, Warn, pub struct UnnecessaryParens; impl UnnecessaryParens { - fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str) { + fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str, + struct_lit_needs_parens: bool) { match value.node { - ast::ExprParen(_) => { - cx.span_lint(UNNECESSARY_PARENS, value.span, - format!("unnecessary parentheses around {}", msg).as_slice()) + ast::ExprParen(ref inner) => { + let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner); + if !necessary { + cx.span_lint(UNNECESSARY_PARENS, value.span, + format!("unnecessary parentheses around {}", + msg).as_slice()) + } } _ => {} } + + /// Expressions that syntatically contain an "exterior" struct + /// literal i.e. not surrounded by any parens or other + /// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo + /// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X { + /// y: 1 }) == foo` does not. + fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { + match value.node { + ast::ExprStruct(..) => true, + + ast::ExprAssign(ref lhs, ref rhs) | + ast::ExprAssignOp(_, ref lhs, ref rhs) | + ast::ExprBinary(_, ref lhs, ref rhs) => { + // X { y: 1 } + X { y: 2 } + contains_exterior_struct_lit(&**lhs) || + contains_exterior_struct_lit(&**rhs) + } + ast::ExprUnary(_, ref x) | + ast::ExprCast(ref x, _) | + ast::ExprField(ref x, _, _) | + ast::ExprIndex(ref x, _) => { + // &X { y: 1 }, X { y: 1 }.y + contains_exterior_struct_lit(&**x) + } + + ast::ExprMethodCall(_, _, ref exprs) => { + // X { y: 1 }.bar(...) + contains_exterior_struct_lit(&**exprs.get(0)) + } + + _ => false + } + } } } @@ -992,16 +1030,16 @@ impl LintPass for UnnecessaryParens { } fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { - let (value, msg) = match e.node { - ast::ExprIf(cond, _, _) => (cond, "`if` condition"), - ast::ExprWhile(cond, _) => (cond, "`while` condition"), - ast::ExprMatch(head, _) => (head, "`match` head expression"), - ast::ExprRet(Some(value)) => (value, "`return` value"), - ast::ExprAssign(_, value) => (value, "assigned value"), - ast::ExprAssignOp(_, _, value) => (value, "assigned value"), + let (value, msg, struct_lit_needs_parens) = match e.node { + ast::ExprIf(cond, _, _) => (cond, "`if` condition", true), + ast::ExprWhile(cond, _) => (cond, "`while` condition", true), + ast::ExprMatch(head, _) => (head, "`match` head expression", true), + ast::ExprRet(Some(value)) => (value, "`return` value", false), + ast::ExprAssign(_, value) => (value, "assigned value", false), + ast::ExprAssignOp(_, _, value) => (value, "assigned value", false), _ => return }; - self.check_unnecessary_parens_core(cx, &*value, msg); + self.check_unnecessary_parens_core(cx, &*value, msg, struct_lit_needs_parens); } fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { @@ -1015,7 +1053,7 @@ impl LintPass for UnnecessaryParens { }, _ => return }; - self.check_unnecessary_parens_core(cx, &*value, msg); + self.check_unnecessary_parens_core(cx, &*value, msg, false); } } @@ -1388,11 +1426,7 @@ impl LintPass for Stability { Some(method) => { match method.origin { typeck::MethodStatic(def_id) => { - // If this implements a trait method, get def_id - // of the method inside trait definition. - // Otherwise, use the current def_id (which refers - // to the method inside impl). - ty::trait_method_of_method(cx.tcx, def_id).unwrap_or(def_id) + def_id } typeck::MethodParam(typeck::MethodParam { trait_id: trait_id, @@ -1416,8 +1450,7 @@ impl LintPass for Stability { // check anything for crate-local usage. if ast_util::is_local(id) { return } - let stability = cx.tcx.stability.borrow_mut().lookup(&cx.tcx.sess.cstore, id); - + let stability = stability::lookup(cx.tcx, id); let (lint, label) = match stability { // no stability attributes == Unstable None => (UNSTABLE, "unmarked"), diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 5aa10b5ab8e..8896a068baa 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -176,7 +176,7 @@ pub struct LintId { impl PartialEq for LintId { fn eq(&self, other: &LintId) -> bool { - (self.lint as *Lint) == (other.lint as *Lint) + (self.lint as *const Lint) == (other.lint as *const Lint) } } @@ -184,7 +184,7 @@ impl Eq for LintId { } impl<S: hash::Writer> hash::Hash<S> for LintId { fn hash(&self, state: &mut S) { - let ptr = self.lint as *Lint; + let ptr = self.lint as *const Lint; ptr.hash(state); } } diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index f5ce8cda8c4..78a29b52bdf 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -181,7 +181,7 @@ fn item_sized(item: ebml::Doc) -> ast::Sized { fn item_method_sort(item: ebml::Doc) -> char { let mut ret = 'r'; reader::tagged_docs(item, tag_item_trait_method_sort, |doc| { - ret = doc.as_str_slice()[0] as char; + ret = doc.as_str_slice().as_bytes()[0] as char; false }); ret @@ -757,13 +757,13 @@ fn get_explicit_self(item: ebml::Doc) -> ast::ExplicitSelf_ { let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self); let string = explicit_self_doc.as_str_slice(); - let explicit_self_kind = string[0]; + let explicit_self_kind = string.as_bytes()[0]; match explicit_self_kind as char { 's' => ast::SelfStatic, 'v' => ast::SelfValue, '~' => ast::SelfUniq, // FIXME(#4846) expl. region - '&' => ast::SelfRegion(None, get_mutability(string[1])), + '&' => ast::SelfRegion(None, get_mutability(string.as_bytes()[1])), _ => fail!("unknown self type code: `{}`", explicit_self_kind as char) } } diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index b606ba3b87a..96284f8de26 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -24,6 +24,7 @@ use middle::ty::{node_id_to_type, lookup_item_type}; use middle::astencode; use middle::ty; use middle::typeck; +use middle::stability; use middle; use util::nodemap::{NodeMap, NodeSet}; @@ -328,7 +329,7 @@ fn encode_enum_variant_info(ecx: &EncodeContext, encode_visibility(ebml_w, variant.node.vis); encode_attributes(ebml_w, variant.node.attrs.as_slice()); - let stab = ecx.tcx.stability.borrow().lookup_local(variant.node.id); + let stab = stability::lookup(ecx.tcx, ast_util::local_def(variant.node.id)); encode_stability(ebml_w, stab); match variant.node.kind { @@ -592,7 +593,9 @@ fn encode_info_for_mod(ecx: &EncodeContext, encode_path(ebml_w, path.clone()); encode_visibility(ebml_w, vis); - encode_stability(ebml_w, ecx.tcx.stability.borrow().lookup_local(id)); + + let stab = stability::lookup(ecx.tcx, ast_util::local_def(id)); + encode_stability(ebml_w, stab); // Encode the reexports of this module, if this module is public. if vis == Public { @@ -722,7 +725,8 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext, encode_symbol(ecx, ebml_w, ctor_id); } - encode_stability(ebml_w, ecx.tcx.stability.borrow().lookup_local(ctor_id)); + let stab = stability::lookup(ecx.tcx, ast_util::local_def(ctor_id)); + encode_stability(ebml_w, stab); // indicate that this is a tuple struct ctor, because downstream users will normally want // the tuple struct definition, but without this there is no way for them to tell that @@ -768,7 +772,7 @@ fn encode_info_for_method(ecx: &EncodeContext, encode_method_ty_fields(ecx, ebml_w, m); encode_parent_item(ebml_w, local_def(parent_id)); - let stab = ecx.tcx.stability.borrow().lookup_local(m.def_id.node); + let stab = stability::lookup(ecx.tcx, m.def_id); encode_stability(ebml_w, stab); // The type for methods gets encoded twice, which is unfortunate. @@ -915,10 +919,10 @@ fn encode_info_for_item(ecx: &EncodeContext, } debug!("encoding info for item at {}", - ecx.tcx.sess.codemap().span_to_str(item.span)); + tcx.sess.codemap().span_to_str(item.span)); let def_id = local_def(item.id); - let stab = tcx.stability.borrow().lookup_local(item.id); + let stab = stability::lookup(tcx, ast_util::local_def(item.id)); match item.node { ItemStatic(_, m, _) => { @@ -1206,7 +1210,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_method_ty_fields(ecx, ebml_w, &*method_ty); encode_parent_item(ebml_w, def_id); - let stab = tcx.stability.borrow().lookup_local(method_def_id.node); + let stab = stability::lookup(tcx, method_def_id); encode_stability(ebml_w, stab); let elem = ast_map::PathName(method_ty.ident.name); @@ -1308,7 +1312,7 @@ fn my_visit_expr(_e: &Expr) { } fn my_visit_item(i: &Item, ebml_w: &mut Encoder, - ecx_ptr: *int, + ecx_ptr: *const int, index: &mut Vec<entry<i64>>) { let mut ebml_w = unsafe { ebml_w.unsafe_clone() }; // See above @@ -1320,7 +1324,7 @@ fn my_visit_item(i: &Item, fn my_visit_foreign_item(ni: &ForeignItem, ebml_w: &mut Encoder, - ecx_ptr:*int, + ecx_ptr:*const int, index: &mut Vec<entry<i64>>) { // See above let ecx: &EncodeContext = unsafe { mem::transmute(ecx_ptr) }; @@ -1341,7 +1345,7 @@ fn my_visit_foreign_item(ni: &ForeignItem, struct EncodeVisitor<'a,'b> { ebml_w_for_visit_item: &'a mut Encoder<'b>, - ecx_ptr:*int, + ecx_ptr:*const int, index: &'a mut Vec<entry<i64>>, } @@ -1386,7 +1390,7 @@ fn encode_info_for_items(ecx: &EncodeContext, Public); // See comment in `encode_side_tables_for_ii` in astencode - let ecx_ptr: *int = unsafe { mem::transmute(ecx) }; + let ecx_ptr: *const int = unsafe { mem::transmute(ecx) }; visit::walk_crate(&mut EncodeVisitor { index: &mut index, ecx_ptr: ecx_ptr, diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index eca0432229e..ccab76ca6f0 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -545,14 +545,15 @@ fn get_metadata_section_imp(os: abi::Os, filename: &Path) -> Result<MetadataBlob while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False { let mut name_buf = ptr::null(); let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf); - let name = str::raw::from_buf_len(name_buf as *u8, name_len as uint); + let name = str::raw::from_buf_len(name_buf as *const u8, + name_len as uint); debug!("get_metadata_section: name {}", name); if read_meta_section_name(os).as_slice() == name.as_slice() { let cbuf = llvm::LLVMGetSectionContents(si.llsi); let csz = llvm::LLVMGetSectionSize(si.llsi) as uint; let mut found = Err(format!("metadata not found: '{}'", filename.display())); - let cvbuf: *u8 = mem::transmute(cbuf); + let cvbuf: *const u8 = mem::transmute(cbuf); let vlen = encoder::metadata_encoding_version.len(); debug!("checking {} bytes of metadata-version stamp", vlen); diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 31a3057e8a6..19e7b9329b1 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -943,7 +943,7 @@ impl<'a> write_tag_and_id for Encoder<'a> { } struct SideTableEncodingIdVisitor<'a,'b> { - ecx_ptr: *libc::c_void, + ecx_ptr: *const libc::c_void, new_ebml_w: &'a mut Encoder<'b>, } diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 156b8840067..e7457f370d9 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -399,7 +399,7 @@ struct DeadVisitor<'a> { impl<'a> DeadVisitor<'a> { fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool { let (is_named, has_leading_underscore) = match node.ident() { - Some(ref ident) => (true, token::get_ident(*ident).get()[0] == ('_' as u8)), + Some(ref ident) => (true, token::get_ident(*ident).get().as_bytes()[0] == ('_' as u8)), _ => (false, false) }; let field_type = ty::node_id_to_type(self.tcx, node.id); diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index f09af6ea441..5c09466cd96 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -360,7 +360,8 @@ fn visit_fn(ir: &mut IrMaps, let mut fn_maps = IrMaps::new(ir.tcx); unsafe { - debug!("creating fn_maps: {}", transmute::<&IrMaps, *IrMaps>(&fn_maps)); + debug!("creating fn_maps: {}", + transmute::<&IrMaps, *const IrMaps>(&fn_maps)); } for arg in decl.inputs.iter() { @@ -1510,7 +1511,7 @@ impl<'a> Liveness<'a> { fn should_warn(&self, var: Variable) -> Option<String> { let name = self.ir.variable_name(var); - if name.len() == 0 || name.as_slice()[0] == ('_' as u8) { + if name.len() == 0 || name.as_bytes()[0] == ('_' as u8) { None } else { Some(name) diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index d26ccc40d3a..e1a2a5741fb 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -126,7 +126,6 @@ pub enum FieldName { #[deriving(Clone, PartialEq, Eq, Hash)] pub enum ElementKind { VecElement, - StrElement, OtherElement, } @@ -794,7 +793,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { //! - `derefs`: the deref number to be used for //! the implicit index deref, if any (see above) - let element_ty = match ty::index(base_cmt.ty) { + let element_ty = match ty::array_element_ty(base_cmt.ty) { Some(ref mt) => mt.ty, None => { self.tcx().sess.span_bug( @@ -1137,9 +1136,6 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { cat_interior(_, InteriorElement(VecElement)) => { "vec content".to_string() } - cat_interior(_, InteriorElement(StrElement)) => { - "str content".to_string() - } cat_interior(_, InteriorElement(OtherElement)) => { "indexed content".to_string() } @@ -1320,7 +1316,6 @@ fn element_kind(t: ty::t) -> ElementKind { ty::ty_rptr(_, ty::mt{ty:ty, ..}) | ty::ty_uniq(ty) => match ty::get(ty).sty { ty::ty_vec(_, None) => VecElement, - ty::ty_str => StrElement, _ => OtherElement }, ty::ty_vec(..) => VecElement, diff --git a/src/librustc/middle/save/span_utils.rs b/src/librustc/middle/save/span_utils.rs index e646827fa23..57006d5e72b 100644 --- a/src/librustc/middle/save/span_utils.rs +++ b/src/librustc/middle/save/span_utils.rs @@ -90,7 +90,7 @@ impl<'a> SpanUtils<'a> { let mut result = None; let mut toks = self.retokenise_span(span); - let mut bracket_count = 0; + let mut bracket_count = 0u; loop { let ts = toks.next_token(); if ts.tok == token::EOF { @@ -113,7 +113,7 @@ impl<'a> SpanUtils<'a> { // Return the span for the first identifier in the path. pub fn span_for_first_ident(&self, span: Span) -> Option<Span> { let mut toks = self.retokenise_span(span); - let mut bracket_count = 0; + let mut bracket_count = 0u; loop { let ts = toks.next_token(); if ts.tok == token::EOF { @@ -139,7 +139,7 @@ impl<'a> SpanUtils<'a> { let mut toks = self.retokenise_span(span); let mut prev = toks.next_token(); let mut result = None; - let mut bracket_count = 0; + let mut bracket_count = 0u; let mut last_span = None; while prev.tok != token::EOF { last_span = None; @@ -187,7 +187,7 @@ impl<'a> SpanUtils<'a> { let mut toks = self.retokenise_span(span); let mut prev = toks.next_token(); let mut result = None; - let mut bracket_count = 0; + let mut bracket_count = 0u; loop { let next = toks.next_token(); @@ -232,7 +232,7 @@ impl<'a> SpanUtils<'a> { let mut toks = self.retokenise_span(span); // We keep track of how many brackets we're nested in - let mut bracket_count = 0; + let mut bracket_count = 0i; loop { let ts = toks.next_token(); if ts.tok == token::EOF { @@ -291,7 +291,7 @@ impl<'a> SpanUtils<'a> { let mut next = toks.next_token(); let mut stored_val = false; let mut found_val = false; - let mut bracket_count = 0; + let mut bracket_count = 0u; while next.tok != token::EOF { if bracket_count == 1 { if next.tok == tok2 { diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index fc76648ec55..ac17bd07503 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -20,7 +20,8 @@ use syntax::ast::{Generics, StructDef, Ident}; use syntax::ast_util::is_local; use syntax::attr::Stability; use syntax::visit::{FnKind, FkMethod, Visitor}; -use metadata::{cstore, csearch}; +use middle::ty; +use metadata::csearch; /// A stability index, giving the stability level for items and methods. pub struct Index { @@ -105,21 +106,24 @@ impl Index { attr::find_stability(krate.attrs.as_slice())); annotator.index } +} - /// Lookup the stability for a node, loading external crate - /// metadata as necessary. - pub fn lookup(&mut self, cstore: &cstore::CStore, id: DefId) -> Option<Stability> { - if is_local(id) { - self.lookup_local(id.node) - } else { - let stab = csearch::get_stability(cstore, id); - self.extern_cache.insert(id, stab.clone()); +/// Lookup the stability for a node, loading external crate +/// metadata as necessary. +pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option<Stability> { + // is this definition the implementation of a trait method? + match ty::trait_method_of_method(tcx, id) { + Some(trait_method_id) if trait_method_id != id => { + lookup(tcx, trait_method_id) + } + _ if is_local(id) => { + tcx.stability.borrow().local.find_copy(&id.node) + } + _ => { + let stab = csearch::get_stability(&tcx.sess.cstore, id); + let mut index = tcx.stability.borrow_mut(); + (*index).extern_cache.insert(id, stab.clone()); stab } } - - /// Lookup the stability for a local node without loading any external crates - pub fn lookup_local(&self, id: NodeId) -> Option<Stability> { - self.local.find_copy(&id) - } } diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 5e7284dbfd1..0cd3b6e7d79 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -44,7 +44,7 @@ impl<T> HomogeneousTuple3<T> for (T, T, T) { fn as_slice<'a>(&'a self) -> &'a [T] { unsafe { - let ptr: *T = mem::transmute(self); + let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } @@ -52,7 +52,7 @@ impl<T> HomogeneousTuple3<T> for (T, T, T) { fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { - let ptr: *T = mem::transmute(self); + let ptr: *const T = mem::transmute(self); let slice = raw::Slice { data: ptr, len: 3 }; mem::transmute(slice) } diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 210de1946c9..75271804b79 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -1220,7 +1220,7 @@ pub fn init_function<'a>(fcx: &'a FunctionContext<'a>, // - new_fn_ctxt // - trans_args -fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue { +pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue { use middle::trans::datum::{ByRef, ByValue}; datum::Rvalue { diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index e04454d4a68..e1c02f543bf 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -453,7 +453,7 @@ pub fn StructGEP(cx: &Block, pointer: ValueRef, idx: uint) -> ValueRef { } } -pub fn GlobalString(cx: &Block, _str: *c_char) -> ValueRef { +pub fn GlobalString(cx: &Block, _str: *const c_char) -> ValueRef { unsafe { if cx.unreachable.get() { return llvm::LLVMGetUndef(Type::i8p(cx.ccx()).to_ref()); @@ -462,7 +462,7 @@ pub fn GlobalString(cx: &Block, _str: *c_char) -> ValueRef { } } -pub fn GlobalStringPtr(cx: &Block, _str: *c_char) -> ValueRef { +pub fn GlobalStringPtr(cx: &Block, _str: *const c_char) -> ValueRef { unsafe { if cx.unreachable.get() { return llvm::LLVMGetUndef(Type::i8p(cx.ccx()).to_ref()); @@ -577,7 +577,8 @@ pub fn TruncOrBitCast(cx: &Block, val: ValueRef, dest_ty: Type) -> ValueRef { } } -pub fn Cast(cx: &Block, op: Opcode, val: ValueRef, dest_ty: Type, _: *u8) +pub fn Cast(cx: &Block, op: Opcode, val: ValueRef, dest_ty: Type, + _: *const u8) -> ValueRef { unsafe { if cx.unreachable.get() { return llvm::LLVMGetUndef(dest_ty.to_ref()); } @@ -636,7 +637,8 @@ pub fn EmptyPhi(cx: &Block, ty: Type) -> ValueRef { } } -pub fn Phi(cx: &Block, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef { +pub fn Phi(cx: &Block, ty: Type, vals: &[ValueRef], + bbs: &[BasicBlockRef]) -> ValueRef { unsafe { if cx.unreachable.get() { return llvm::LLVMGetUndef(ty.to_ref()); } B(cx).phi(ty, vals, bbs) @@ -672,7 +674,7 @@ pub fn add_comment(cx: &Block, text: &str) { B(cx).add_comment(text) } -pub fn InlineAsmCall(cx: &Block, asm: *c_char, cons: *c_char, +pub fn InlineAsmCall(cx: &Block, asm: *const c_char, cons: *const c_char, inputs: &[ValueRef], output: Type, volatile: bool, alignstack: bool, dia: AsmDialect) -> ValueRef { diff --git a/src/librustc/middle/trans/builder.rs b/src/librustc/middle/trans/builder.rs index 4078268c6a5..a9c1adac3d7 100644 --- a/src/librustc/middle/trans/builder.rs +++ b/src/librustc/middle/trans/builder.rs @@ -31,9 +31,9 @@ pub struct Builder<'a> { // This is a really awful way to get a zero-length c-string, but better (and a // lot more efficient) than doing str::as_c_str("", ...) every time. -pub fn noname() -> *c_char { +pub fn noname() -> *const c_char { static cnull: c_char = 0; - &cnull as *c_char + &cnull as *const c_char } impl<'a> Builder<'a> { @@ -159,6 +159,14 @@ impl<'a> Builder<'a> { attributes: &[(uint, u64)]) -> ValueRef { self.count_insn("invoke"); + + debug!("Invoke {} with args ({})", + self.ccx.tn.val_to_str(llfn), + args.iter() + .map(|&v| self.ccx.tn.val_to_str(v)) + .collect::<Vec<String>>() + .connect(", ")); + unsafe { let v = llvm::LLVMBuildInvoke(self.llbuilder, llfn, @@ -564,14 +572,14 @@ impl<'a> Builder<'a> { } } - pub fn global_string(&self, _str: *c_char) -> ValueRef { + pub fn global_string(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstring"); unsafe { llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname()) } } - pub fn global_string_ptr(&self, _str: *c_char) -> ValueRef { + pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstringptr"); unsafe { llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname()) @@ -774,7 +782,7 @@ impl<'a> Builder<'a> { } } - pub fn inline_asm_call(&self, asm: *c_char, cons: *c_char, + pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char, inputs: &[ValueRef], output: Type, volatile: bool, alignstack: bool, dia: AsmDialect) -> ValueRef { diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index 8b484e90898..116b2e6b421 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -16,7 +16,9 @@ * closure. */ +use arena::TypedArena; use back::abi; +use back::link; use driver::session; use lib::llvm::ValueRef; use lib::llvm::llvm; @@ -33,28 +35,26 @@ use middle::trans::cleanup::CleanupMethods; use middle::trans::common; use middle::trans::common::*; use middle::trans::datum::*; -use middle::trans::datum::Datum; +use middle::trans::datum::{Datum, KindOps}; use middle::trans::expr; use middle::trans::glue; use middle::trans::inline; +use middle::trans::foreign; use middle::trans::meth; use middle::trans::monomorphize; +use middle::trans::type_::Type; use middle::trans::type_of; -use middle::trans::foreign; use middle::ty; use middle::typeck; use middle::typeck::coherence::make_substs_for_receiver_types; use middle::typeck::MethodCall; use util::ppaux::Repr; -use middle::trans::type_::Type; - +use std::gc::Gc; use syntax::ast; use synabi = syntax::abi; use syntax::ast_map; -use std::gc::Gc; - pub struct MethodData { pub llfn: ValueRef, pub llself: ValueRef, @@ -224,6 +224,134 @@ fn resolve_default_method_vtables(bcx: &Block, param_vtables } +/// Translates the adapter that deconstructs a `Box<Trait>` object into +/// `Trait` so that a by-value self method can be called. +pub fn trans_unboxing_shim(bcx: &Block, + llshimmedfn: ValueRef, + method: &ty::Method, + method_id: ast::DefId, + substs: subst::Substs) + -> ValueRef { + let _icx = push_ctxt("trans_unboxing_shim"); + let ccx = bcx.ccx(); + let tcx = bcx.tcx(); + + // Transform the self type to `Box<self_type>`. + let self_type = *method.fty.sig.inputs.get(0); + let boxed_self_type = ty::mk_uniq(tcx, self_type); + let boxed_function_type = ty::FnSig { + binder_id: method.fty.sig.binder_id, + inputs: method.fty.sig.inputs.iter().enumerate().map(|(i, typ)| { + if i == 0 { + boxed_self_type + } else { + *typ + } + }).collect(), + output: method.fty.sig.output, + variadic: false, + }; + let boxed_function_type = ty::BareFnTy { + fn_style: method.fty.fn_style, + abi: method.fty.abi, + sig: boxed_function_type, + }; + let boxed_function_type = + ty::mk_bare_fn(tcx, boxed_function_type).subst(tcx, &substs); + let function_type = + ty::mk_bare_fn(tcx, method.fty.clone()).subst(tcx, &substs); + + let function_name = tcx.map.with_path(method_id.node, |path| { + link::mangle_internal_name_by_path_and_seq(path, "unboxing_shim") + }); + let llfn = decl_internal_rust_fn(ccx, + boxed_function_type, + function_name.as_slice()); + + let block_arena = TypedArena::new(); + let empty_param_substs = param_substs::empty(); + let return_type = ty::ty_fn_ret(boxed_function_type); + let fcx = new_fn_ctxt(ccx, + llfn, + -1, + false, + return_type, + &empty_param_substs, + None, + &block_arena); + init_function(&fcx, false, return_type); + + // Create the substituted versions of the self type. + let mut bcx = fcx.entry_bcx.borrow().clone().unwrap(); + let arg_scope = fcx.push_custom_cleanup_scope(); + let arg_scope_id = cleanup::CustomScope(arg_scope); + let boxed_arg_types = ty::ty_fn_args(boxed_function_type); + let boxed_self_type = *boxed_arg_types.get(0); + let arg_types = ty::ty_fn_args(function_type); + let self_type = *arg_types.get(0); + let boxed_self_kind = arg_kind(&fcx, boxed_self_type); + + // Create a datum for self. + let llboxedself = unsafe { + llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(0) as u32) + }; + let llboxedself = Datum::new(llboxedself, + boxed_self_type, + boxed_self_kind); + let boxed_self = + unpack_datum!(bcx, + llboxedself.to_lvalue_datum_in_scope(bcx, + "boxedself", + arg_scope_id)); + + // This `Load` is needed because lvalue data are always by-ref. + let llboxedself = Load(bcx, boxed_self.val); + + let llself = if type_is_immediate(ccx, self_type) { + let llboxedself = Load(bcx, llboxedself); + immediate_rvalue(llboxedself, self_type) + } else { + let llself = rvalue_scratch_datum(bcx, self_type, "self"); + memcpy_ty(bcx, llself.val, llboxedself, self_type); + llself + }; + + // Make sure we don't free the box twice! + boxed_self.kind.post_store(bcx, boxed_self.val, boxed_self_type); + + // Schedule a cleanup to free the box. + fcx.schedule_free_value(arg_scope_id, + llboxedself, + cleanup::HeapExchange, + self_type); + + // Now call the function. + let mut llshimmedargs = vec!(llself.val); + for i in range(1, arg_types.len()) { + llshimmedargs.push(unsafe { + llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as u32) + }); + } + bcx = trans_call_inner(bcx, + None, + function_type, + |bcx, _| { + Callee { + bcx: bcx, + data: Fn(llshimmedfn), + } + }, + ArgVals(llshimmedargs.as_slice()), + match fcx.llretptr.get() { + None => None, + Some(llretptr) => Some(expr::SaveIn(llretptr)), + }).bcx; + + bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope); + finish_fn(&fcx, bcx); + + llfn +} pub fn trans_fn_ref_with_vtables( bcx: &Block, // diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index a1923022e7b..b1577a6abfe 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -471,7 +471,7 @@ impl<'a> Block<'a> { } pub fn to_str(&self) -> String { - let blk: *Block = self; + let blk: *const Block = self; format!("[block {}]", blk) } } @@ -568,7 +568,7 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> Va } let sc = llvm::LLVMConstStringInContext(cx.llcx, - s.get().as_ptr() as *c_char, + s.get().as_ptr() as *const c_char, s.get().len() as c_uint, !null_terminated as Bool); @@ -636,7 +636,7 @@ pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef { pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef { unsafe { - let ptr = bytes.as_ptr() as *c_char; + let ptr = bytes.as_ptr() as *const c_char; return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True); } } diff --git a/src/librustc/middle/trans/context.rs b/src/librustc/middle/trans/context.rs index 68c6f1752bd..6387ec791ba 100644 --- a/src/librustc/middle/trans/context.rs +++ b/src/librustc/middle/trans/context.rs @@ -221,8 +221,8 @@ impl CrateContext { llvm_insns: RefCell::new(HashMap::new()), fn_stats: RefCell::new(Vec::new()), }, - int_type: Type::from_ref(ptr::null()), - opaque_vec_type: Type::from_ref(ptr::null()), + int_type: Type::from_ref(ptr::mut_null()), + opaque_vec_type: Type::from_ref(ptr::mut_null()), builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)), uses_gc: false, dbg_cx: dbg_cx, diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index e7895a1bb9a..400babb39f8 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -805,7 +805,7 @@ pub fn create_global_var_metadata(cx: &CrateContext, type_metadata, is_local_to_unit, global, - ptr::null()); + ptr::mut_null()); } }) }); @@ -980,7 +980,7 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) { } }; - if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::null() { + if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::mut_null() { cx.sess().span_bug(span, "debuginfo::create_argument_metadata() - \ Referenced variable location is not an alloca!"); } @@ -1221,7 +1221,7 @@ pub fn create_function_debug_context(cx: &CrateContext, cx.sess().opts.optimize != config::No, llfn, template_parameters, - ptr::null()) + ptr::mut_null()) } }) }); @@ -1257,7 +1257,7 @@ pub fn create_function_debug_context(cx: &CrateContext, // Return type -- llvm::DIBuilder wants this at index 0 match fn_decl.output.node { ast::TyNil => { - signature.push(ptr::null()); + signature.push(ptr::mut_null()); } _ => { assert_type_for_node_id(cx, fn_ast_id, error_span); @@ -1328,7 +1328,7 @@ pub fn create_function_debug_context(cx: &CrateContext, file_metadata, name, actual_self_type_metadata, - ptr::null(), + ptr::mut_null(), 0, 0) } @@ -1361,7 +1361,7 @@ pub fn create_function_debug_context(cx: &CrateContext, file_metadata, name, actual_type_metadata, - ptr::null(), + ptr::mut_null(), 0, 0) } @@ -1433,24 +1433,23 @@ fn compile_unit_metadata(cx: &CrateContext) { let producer = format!("rustc version {}", (option_env!("CFG_VERSION")).expect("CFG_VERSION")); - compile_unit_name.with_ref(|compile_unit_name| { - work_dir.as_vec().with_c_str(|work_dir| { - producer.with_c_str(|producer| { - "".with_c_str(|flags| { - "".with_c_str(|split_name| { - unsafe { - llvm::LLVMDIBuilderCreateCompileUnit( - debug_context(cx).builder, - DW_LANG_RUST, - compile_unit_name, - work_dir, - producer, - cx.sess().opts.optimize != config::No, - flags, - 0, - split_name); - } - }) + let compile_unit_name = compile_unit_name.as_ptr(); + work_dir.as_vec().with_c_str(|work_dir| { + producer.with_c_str(|producer| { + "".with_c_str(|flags| { + "".with_c_str(|split_name| { + unsafe { + llvm::LLVMDIBuilderCreateCompileUnit( + debug_context(cx).builder, + DW_LANG_RUST, + compile_unit_name, + work_dir, + producer, + cx.sess().opts.optimize != config::No, + flags, + 0, + split_name); + } }) }) }) @@ -2374,7 +2373,7 @@ fn prepare_enum_metadata(cx: &CrateContext, bytes_to_bits(enum_type_size), bytes_to_bits(enum_type_align), 0, // Flags - ptr::null(), + ptr::mut_null(), 0, // RuntimeLang unique_type_id_str) } @@ -2554,10 +2553,10 @@ fn create_struct_stub(cx: &CrateContext, bytes_to_bits(struct_size), bytes_to_bits(struct_align), 0, - ptr::null(), + ptr::mut_null(), empty_array, 0, - ptr::null(), + ptr::mut_null(), unique_type_id) }) }) @@ -2855,7 +2854,7 @@ fn subroutine_type_metadata(cx: &CrateContext, // return type signature_metadata.push(match ty::get(signature.output).sty { - ty::ty_nil => ptr::null(), + ty::ty_nil => ptr::mut_null(), _ => type_metadata(cx, signature.output, span) }); @@ -3153,7 +3152,8 @@ fn set_debug_location(cx: &CrateContext, debug_location: DebugLocation) { KnownLocation { scope, line, .. } => { let col = 0u; // Always set the column to zero like Clang and GCC debug!("setting debug location to {} {}", line, col); - let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32), scope, ptr::null()]; + let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32), + scope, ptr::mut_null()]; unsafe { metadata_node = llvm::LLVMMDNodeInContext(debug_context(cx).llcontext, elements.as_ptr(), @@ -3162,7 +3162,7 @@ fn set_debug_location(cx: &CrateContext, debug_location: DebugLocation) { } UnknownLocation => { debug!("clearing debug location "); - metadata_node = ptr::null(); + metadata_node = ptr::mut_null(); } }; @@ -3771,7 +3771,7 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTree // create and insert let parent_scope = match parent_node { Some(ref node) => node.scope, - None => ptr::null() + None => ptr::mut_null() }; let namespace_name = token::get_name(name); let scope = namespace_name.get().with_c_str(|namespace_name| { @@ -3781,7 +3781,7 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTree parent_scope, namespace_name, // cannot reconstruct file ... - ptr::null(), + ptr::mut_null(), // ... or line information, but that's not so important. 0) } diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 2a01e165f3c..b10190b23c7 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -277,7 +277,7 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, auto_ref(bcx, datum, expr) } - fn auto_borrow_obj<'a>(bcx: &'a Block<'a>, + fn auto_borrow_obj<'a>(mut bcx: &'a Block<'a>, expr: &ast::Expr, source_datum: Datum<Expr>) -> DatumBlock<'a, Expr> { @@ -285,7 +285,11 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, let target_obj_ty = expr_ty_adjusted(bcx, expr); debug!("auto_borrow_obj(target={})", target_obj_ty.repr(tcx)); - let mut datum = source_datum.to_expr_datum(); + // Arrange cleanup, if not already done. This is needed in + // case we are auto-borrowing a Box<Trait> to &Trait + let datum = unpack_datum!( + bcx, source_datum.to_lvalue_datum(bcx, "autoborrowobj", expr.id)); + let mut datum = datum.to_expr_datum(); datum.ty = target_obj_ty; DatumBlock::new(bcx, datum) } diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index fcd6c7e293e..488dc6d99e3 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -957,7 +957,11 @@ pub fn lltype_for_foreign_fn(ccx: &CrateContext, ty: ty::t) -> Type { fn add_argument_attributes(tys: &ForeignTypes, llfn: ValueRef) { - let mut i = if tys.fn_ty.ret_ty.is_indirect() { 1 } else { 0 }; + let mut i = if tys.fn_ty.ret_ty.is_indirect() { + 1i + } else { + 0i + }; match tys.fn_ty.ret_ty.attr { Some(attr) => unsafe { diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index 85660cd2eb5..e1d43c52400 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -492,14 +492,24 @@ fn emit_vtable_methods(bcx: &Block, m.repr(tcx), substs.repr(tcx)); if m.generics.has_type_params(subst::FnSpace) || - ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) - { + ty::type_has_self(ty::mk_bare_fn(tcx, m.fty.clone())) { debug!("(making impl vtable) method has self or type params: {}", token::get_ident(ident)); C_null(Type::nil(ccx).ptr_to()) } else { - trans_fn_ref_with_vtables(bcx, m_id, ExprId(0), - substs.clone(), vtables.clone()) + let mut fn_ref = trans_fn_ref_with_vtables(bcx, + m_id, + 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()); + } + fn_ref } }).collect() } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 01e3af8a3d7..79630be7c5e 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -158,7 +158,7 @@ pub struct creader_cache_key { pub type creader_cache = RefCell<HashMap<creader_cache_key, t>>; pub struct intern_key { - sty: *sty, + sty: *const sty, } // NB: Do not replace this with #[deriving(PartialEq)]. The automatically-derived @@ -409,7 +409,7 @@ enum t_opaque {} #[allow(raw_pointer_deriving)] #[deriving(Clone, PartialEq, Eq, Hash)] -pub struct t { inner: *t_opaque } +pub struct t { inner: *const t_opaque } impl fmt::Show for t { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -1216,7 +1216,7 @@ pub fn mk_t(cx: &ctxt, st: sty) -> t { flags: flags, }; - let sty_ptr = &t.sty as *sty; + let sty_ptr = &t.sty as *const sty; let key = intern_key { sty: sty_ptr, @@ -1227,7 +1227,7 @@ pub fn mk_t(cx: &ctxt, st: sty) -> t { cx.next_id.set(cx.next_id.get() + 1); unsafe { - mem::transmute::<*sty, t>(sty_ptr) + mem::transmute::<*const sty, t>(sty_ptr) } } @@ -1533,7 +1533,7 @@ pub fn type_is_self(ty: t) -> bool { } } -fn type_is_slice(ty:t) -> bool { +fn type_is_slice(ty: t) -> bool { match get(ty).sty { ty_rptr(_, mt) => match get(mt.ty).sty { ty_vec(_, None) | ty_str => true, @@ -1543,6 +1543,18 @@ fn type_is_slice(ty:t) -> bool { } } +pub fn type_is_vec(ty: t) -> bool { + match get(ty).sty { + ty_vec(..) => true, + ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) | + ty_box(t) | ty_uniq(t) => match get(t).sty { + ty_vec(_, None) => true, + _ => false + }, + _ => false + } +} + pub fn type_is_structural(ty: t) -> bool { match get(ty).sty { ty_struct(..) | ty_tup(_) | ty_enum(..) | ty_closure(_) | @@ -1560,7 +1572,7 @@ pub fn type_is_simd(cx: &ctxt, ty: t) -> bool { pub fn sequence_element_type(cx: &ctxt, ty: t) -> t { match get(ty).sty { - ty_vec(mt, Some(_)) => mt.ty, + ty_vec(mt, _) => mt.ty, ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) | ty_box(t) | ty_uniq(t) => match get(t).sty { ty_vec(mt, None) => mt.ty, @@ -2556,6 +2568,21 @@ pub fn index(t: t) -> Option<mt> { ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) | ty_box(t) | ty_uniq(t) => match get(t).sty { ty_vec(mt, None) => Some(mt), + _ => None, + }, + _ => None + } +} + +// Returns the type of elements contained within an 'array-like' type. +// This is exactly the same as the above, except it supports strings, +// which can't actually be indexed. +pub fn array_element_ty(t: t) -> Option<mt> { + match get(t).sty { + ty_vec(mt, Some(_)) => Some(mt), + ty_ptr(mt{ty: t, ..}) | ty_rptr(_, mt{ty: t, ..}) | + ty_box(t) | ty_uniq(t) => match get(t).sty { + ty_vec(mt, None) => Some(mt), ty_str => Some(mt {ty: mk_u8(), mutbl: ast::MutImmutable}), _ => None, }, diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index 67437da44c5..60ce9508dc4 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -318,6 +318,9 @@ pub fn check_struct_pat_fields(pcx: &pat_ctxt, for field in fields.iter() { match field_map.find_mut(&field.ident.name) { Some(&(_, true)) => { + // Check the pattern anyway, so that attempts to look + // up its type won't fail + check_pat(pcx, &*field.pat, ty::mk_err()); tcx.sess.span_err(span, format!("field `{}` bound twice in pattern", token::get_ident(field.ident)).as_slice()); diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 4270ff1e795..c3b2756bdbf 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -271,7 +271,9 @@ fn construct_transformed_self_ty_for_object( tcx.sess.span_bug(span, "static method for object type receiver"); } ast::SelfValue => { - ty::mk_err() // error reported in `enforce_object_limitations()` + let tr = ty::mk_trait(tcx, trait_def_id, obj_substs, + ty::empty_builtin_bounds()); + ty::mk_uniq(tcx, tr) } ast::SelfRegion(..) | ast::SelfUniq => { let transformed_self_ty = *method_ty.fty.sig.inputs.get(0); @@ -1225,14 +1227,7 @@ impl<'a> LookupContext<'a> { through an object"); } - ast::SelfValue => { // reason (a) above - self.tcx().sess.span_err( - self.span, - "cannot call a method with a by-value receiver \ - through an object"); - } - - ast::SelfRegion(..) | ast::SelfUniq => {} + ast::SelfValue | ast::SelfRegion(..) | ast::SelfUniq => {} } // reason (a) above @@ -1302,7 +1297,26 @@ impl<'a> LookupContext<'a> { } SelfValue => { - rcvr_matches_ty(self.fcx, rcvr_ty, candidate) + debug!("(is relevant?) explicit self is by-value"); + match ty::get(rcvr_ty).sty { + ty::ty_uniq(typ) => { + match ty::get(typ).sty { + ty::ty_trait(box ty::TyTrait { + def_id: self_did, + .. + }) => { + rcvr_matches_object(self_did, candidate) || + rcvr_matches_ty(self.fcx, + rcvr_ty, + candidate) + } + _ => { + rcvr_matches_ty(self.fcx, rcvr_ty, candidate) + } + } + } + _ => rcvr_matches_ty(self.fcx, rcvr_ty, candidate) + } } SelfRegion(_, m) => { diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 0b35eab5679..5e675242688 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1146,24 +1146,9 @@ fn check_cast(fcx: &FnCtxt, .span_err(span, "cannot cast as `bool`, compare with zero instead"); } else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) { - fn is_vec(t: ty::t) -> bool { - match ty::get(t).sty { - ty::ty_vec(..) => true, - ty::ty_ptr(ty::mt{ty: t, ..}) | - ty::ty_rptr(_, ty::mt{ty: t, ..}) | - ty::ty_box(t) | - ty::ty_uniq(t) => { - match ty::get(t).sty { - ty::ty_vec(_, None) => true, - _ => false, - } - } - _ => false - } - } fn types_compatible(fcx: &FnCtxt, sp: Span, t1: ty::t, t2: ty::t) -> bool { - if !is_vec(t1) { + if !ty::type_is_vec(t1) { // If the type being casted from is not a vector, this special // case does not apply. return false @@ -1262,7 +1247,7 @@ impl<'a> RegionScope for infer::InferCtxt<'a> { impl<'a> FnCtxt<'a> { pub fn tag(&self) -> String { - format!("{}", self as *FnCtxt) + format!("{}", self as *const FnCtxt) } pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> ty::t { @@ -2779,10 +2764,30 @@ fn check_expr_with_unifier(fcx: &FnCtxt, fcx.write_ty(id, enum_type); } + type ExprCheckerWithTy = fn(&FnCtxt, &ast::Expr, ty::t); + + fn check_fn_for_vec_elements_expected(fcx: &FnCtxt, + expected: Expectation) + -> (ExprCheckerWithTy, ty::t) { + let tcx = fcx.ccx.tcx; + let (coerce, t) = match expected { + // If we're given an expected type, we can try to coerce to it + ExpectHasType(t) if ty::type_is_vec(t) => (true, ty::sequence_element_type(tcx, t)), + // Otherwise we just leave the type to be resolved later + _ => (false, fcx.infcx().next_ty_var()) + }; + if coerce { + (check_expr_coercable_to_type, t) + } else { + (check_expr_has_type, t) + } + } + let tcx = fcx.ccx.tcx; let id = expr.id; match expr.node { ast::ExprVstore(ev, vst) => { + let (check, t) = check_fn_for_vec_elements_expected(fcx, expected); let typ = match ev.node { ast::ExprVec(ref args) => { let mutability = match vst { @@ -2791,9 +2796,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt, }; let mut any_error = false; let mut any_bot = false; - let t: ty::t = fcx.infcx().next_ty_var(); for e in args.iter() { - check_expr_has_type(fcx, &**e, t); + check(fcx, &**e, t); let arg_t = fcx.expr_ty(&**e); if ty::type_is_error(arg_t) { any_error = true; @@ -2821,8 +2825,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, ast::ExprVstoreMutSlice => ast::MutMutable, _ => ast::MutImmutable, }; - let t = fcx.infcx().next_ty_var(); - check_expr_has_type(fcx, &**element, t); + check(fcx, &**element, t); let arg_t = fcx.expr_ty(&**element); if ty::type_is_error(arg_t) { ty::mk_err() @@ -3211,9 +3214,9 @@ fn check_expr_with_unifier(fcx: &FnCtxt, check_cast(fcx, &**e, &**t, id, expr.span); } ast::ExprVec(ref args) => { - let t: ty::t = fcx.infcx().next_ty_var(); + let (check, t) = check_fn_for_vec_elements_expected(fcx, expected); for e in args.iter() { - check_expr_has_type(fcx, &**e, t); + check(fcx, &**e, t); } let typ = ty::mk_vec(tcx, ty::mt {ty: t, mutbl: ast::MutImmutable}, Some(args.len())); @@ -3222,8 +3225,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt, ast::ExprRepeat(ref element, ref count_expr) => { check_expr_has_type(fcx, &**count_expr, ty::mk_uint()); let count = ty::eval_repeat_count(fcx, &**count_expr); - let t: ty::t = fcx.infcx().next_ty_var(); - check_expr_has_type(fcx, &**element, t); + let (check, t) = check_fn_for_vec_elements_expected(fcx, expected); + check(fcx, &**element, t); let element_ty = fcx.expr_ty(&**element); if ty::type_is_error(element_ty) { fcx.write_error(id); @@ -3805,7 +3808,15 @@ pub fn check_enum_variants(ccx: &CrateCtxt, let inh = blank_inherited_fields(ccx); let fcx = blank_fn_ctxt(ccx, &inh, rty, e.id); - let declty = ty::mk_int_var(ccx.tcx, fcx.infcx().next_int_var_id()); + let declty = match hint { + attr::ReprAny | attr::ReprExtern => ty::mk_int(), + attr::ReprInt(_, attr::SignedInt(ity)) => { + ty::mk_mach_int(ity) + } + attr::ReprInt(_, attr::UnsignedInt(ity)) => { + ty::mk_mach_uint(ity) + } + }; check_const_with_ty(&fcx, e.span, &*e, declty); // check_expr (from check_const pass) doesn't guarantee // that the expression is in a form that eval_const_expr can diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index 7612add9b05..33e0d0331be 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -352,17 +352,15 @@ fn search_for_vtable(vcx: &VtableContext, // the next impl. // // FIXME: document a bit more what this means - // - // FIXME(#5781) this should be mk_eqty not mk_subty let TypeAndSubsts { substs: substs, ty: for_ty } = impl_self_ty(vcx, span, impl_did); - match infer::mk_subty(vcx.infcx, - false, - infer::RelateSelfType(span), - ty, - for_ty) { + match infer::mk_eqty(vcx.infcx, + false, + infer::RelateSelfType(span), + ty, + for_ty) { Err(_) => continue, Ok(()) => () } diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 844a37d366e..f374f1dc267 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -84,16 +84,13 @@ pub trait Combine { fn tys(&self, a: ty::t, b: ty::t) -> cres<ty::t>; fn tps(&self, - space: subst::ParamSpace, + _: subst::ParamSpace, as_: &[ty::t], bs: &[ty::t]) - -> cres<Vec<ty::t>> - { - // FIXME(#5781) -- In general, we treat variance a bit wrong - // here. For historical reasons, we treat Self as - // contravariant and other tps as invariant. Both are wrong: - // Self may or may not be contravariant, and other tps do not - // need to be invariant. + -> cres<Vec<ty::t>> { + // FIXME -- In general, we treat variance a bit wrong + // here. For historical reasons, we treat tps and Self + // as invariant. This is overly conservative. if as_.len() != bs.len() { return Err(ty::terr_ty_param_size(expected_found(self, @@ -101,24 +98,11 @@ pub trait Combine { bs.len()))); } - match space { - subst::SelfSpace => { - result::fold(as_ - .iter() - .zip(bs.iter()) - .map(|(a, b)| self.contratys(*a, *b)), - Vec::new(), - |mut v, a| { v.push(a); v }) - } - - subst::TypeSpace | subst::FnSpace => { - try!(result::fold_(as_ - .iter() - .zip(bs.iter()) - .map(|(a, b)| eq_tys(self, *a, *b)))); - Ok(Vec::from_slice(as_)) - } - } + try!(result::fold_(as_ + .iter() + .zip(bs.iter()) + .map(|(a, b)| eq_tys(self, *a, *b)))); + Ok(Vec::from_slice(as_)) } fn substs(&self, diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index 197a2370eff..bc02297b5b1 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -247,9 +247,13 @@ pub enum fixup_err { pub fn fixup_err_to_str(f: fixup_err) -> String { match f { - unresolved_int_ty(_) => "unconstrained integral type".to_string(), + unresolved_int_ty(_) => { + "cannot determine the type of this integer; add a suffix to \ + specify the type explicitly".to_string() + } unresolved_float_ty(_) => { - "unconstrained floating point type".to_string() + "cannot determine the type of this number; add a suffix to specify \ + the type explicitly".to_string() } unresolved_ty(_) => "unconstrained type".to_string(), cyclic_ty(_) => "cyclic type of infinite size".to_string(), diff --git a/src/librustc/middle/typeck/infer/resolve.rs b/src/librustc/middle/typeck/infer/resolve.rs index ed6ea6c9677..adfbe9de2d5 100644 --- a/src/librustc/middle/typeck/infer/resolve.rs +++ b/src/librustc/middle/typeck/infer/resolve.rs @@ -52,14 +52,12 @@ use middle::ty::{type_is_bot, IntType, UintType}; use middle::ty; use middle::ty_fold; use middle::typeck::infer::{Bounds, cyclic_ty, fixup_err, fres, InferCtxt}; -use middle::typeck::infer::unresolved_ty; -use middle::typeck::infer::unify::Root; +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 syntax::ast; - pub static resolve_nested_tvar: uint = 0b0000000001; pub static resolve_rvar: uint = 0b0000000010; pub static resolve_ivar: uint = 0b0000000100; @@ -83,21 +81,18 @@ pub struct ResolveState<'a> { err: Option<fixup_err>, v_seen: Vec<TyVid> , type_depth: uint, - span: Option<Span>, } pub fn resolver<'a>(infcx: &'a InferCtxt, modes: uint, - span: Option<Span>) - -> ResolveState<'a> -{ + _: Option<Span>) + -> ResolveState<'a> { ResolveState { infcx: infcx, modes: modes, err: None, v_seen: Vec::new(), type_depth: 0, - span: span } } @@ -258,24 +253,10 @@ impl<'a> ResolveState<'a> { Some(UintType(t)) => ty::mk_mach_uint(t), None => { if self.should(force_ivar) { - // As a last resort, default to int and emit an error. - let ty = ty::mk_int(); - table.borrow_mut().set( - tcx, node.key, Root(Some(IntType(ast::TyI)), node.rank)); - - match self.span { - Some(sp) => { - self.infcx.tcx.sess.span_err( - sp, - "cannot determine the type of this integer; add \ - a suffix to specify the type explicitly"); - } - None => { } - } - ty - } else { - ty::mk_int_var(self.infcx.tcx, vid) + // As a last resort, emit an error. + self.err = Some(unresolved_int_ty(vid)); } + ty::mk_int_var(self.infcx.tcx, vid) } } } @@ -292,24 +273,10 @@ impl<'a> ResolveState<'a> { Some(t) => ty::mk_mach_float(t), None => { if self.should(force_fvar) { - // As a last resort, default to f64 and emit an error. - let ty = ty::mk_f64(); - table.borrow_mut().set( - tcx, node.key, Root(Some(ast::TyF64), node.rank)); - - match self.span { - Some(sp) => { - self.infcx.tcx.sess.span_err( - sp, - "cannot determine the type of this number; add \ - a suffix to specify the type explicitly"); - } - None => { } - } - ty - } else { - ty::mk_float_var(self.infcx.tcx, vid) + // As a last resort, emit an error. + self.err = Some(unresolved_float_ty(vid)); } + ty::mk_float_var(self.infcx.tcx, vid) } } } diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index 3731990e61f..0a60a5ce0e9 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -78,8 +78,8 @@ receiver position from being called via an object.) #### Trait variance and vtable resolution But traits aren't only used with objects. They're also used when -deciding whether a given impl satisfies a given trait bound (or should -be -- FIXME #5781). To set the scene here, imagine I had a function: +deciding whether a given impl satisfies a given trait bound. To set the +scene here, imagine I had a function: fn convertAll<A,T:ConvertTo<A>>(v: &[T]) { ... diff --git a/src/librustc/plugin/load.rs b/src/librustc/plugin/load.rs index 7d74b8c7296..79d0690653f 100644 --- a/src/librustc/plugin/load.rs +++ b/src/librustc/plugin/load.rs @@ -129,7 +129,7 @@ impl<'a> PluginLoader<'a> { let registrar = match lib.symbol(symbol.as_slice()) { Ok(registrar) => { - mem::transmute::<*u8,PluginRegistrarFun>(registrar) + mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros Err(err) => self.sess.span_fatal(vi.span, err.as_slice()) diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 1de6ff8f03b..fa353652fe1 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -355,7 +355,12 @@ pub fn ty_to_str(cx: &ctxt, typ: t) -> 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_ptr(ref tm) => format!("*{}", mt_to_str(cx, tm)), + ty_ptr(ref tm) => { + format!("*{} {}", match tm.mutbl { + ast::MutMutable => "mut", + ast::MutImmutable => "const", + }, ty_to_str(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()); diff --git a/src/librustc/util/sha2.rs b/src/librustc/util/sha2.rs index e9891533ac8..bfd3deb0f2d 100644 --- a/src/librustc/util/sha2.rs +++ b/src/librustc/util/sha2.rs @@ -34,7 +34,7 @@ fn read_u32v_be(dst: &mut[u32], input: &[u8]) { assert!(dst.len() * 4 == input.len()); unsafe { let mut x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; - let mut y = input.unsafe_ref(0) as *_ as *u32; + let mut y = input.unsafe_ref(0) as *const _ as *const u32; for _ in range(0, dst.len()) { *x = to_be32(*y); x = x.offset(1); diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index d243c61ddaf..2d498e7f302 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -18,6 +18,7 @@ use rustc::metadata::csearch; use rustc::metadata::decoder; use rustc::middle::def; use rustc::middle::ty; +use rustc::middle::stability; use core; use doctree; @@ -102,6 +103,7 @@ fn try_inline_def(cx: &core::DocContext, attrs: load_attrs(tcx, did), inner: inner, visibility: Some(ast::Public), + stability: stability::lookup(tcx, did).clean(), def_id: did, }); Some(ret) @@ -317,6 +319,7 @@ fn build_impl(cx: &core::DocContext, name: None, attrs: attrs, visibility: Some(ast::Inherited), + stability: stability::lookup(tcx, did).clean(), def_id: did, }) } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index d7bbb439dbb..87151708812 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -29,6 +29,7 @@ use rustc::middle::def; use rustc::middle::subst; use rustc::middle::subst::VecPerParamSpace; use rustc::middle::ty; +use rustc::middle::stability; use std::rc::Rc; use std::u32; @@ -44,6 +45,17 @@ pub static SCHEMA_VERSION: &'static str = "0.8.3"; mod inline; +// load the current DocContext from TLD +fn get_cx() -> Gc<core::DocContext> { + *super::ctxtkey.get().unwrap() +} + +// extract the stability index for a node from TLD, if possible +fn get_stability(def_id: ast::DefId) -> Option<Stability> { + get_cx().tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)) + .map(|stab| stab.clean()) +} + pub trait Clean<T> { fn clean(&self) -> T; } @@ -97,7 +109,7 @@ pub struct Crate { impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> { fn clean(&self) -> Crate { - let cx = super::ctxtkey.get().unwrap(); + let cx = get_cx(); let mut externs = Vec::new(); cx.sess().cstore.iter_crate_data(|n, meta| { @@ -158,6 +170,7 @@ impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> { name: Some(prim.to_url_str().to_string()), attrs: Vec::new(), visibility: None, + stability: None, def_id: ast_util::local_def(prim.to_node_id()), inner: PrimitiveItem(prim), }; @@ -193,25 +206,18 @@ pub struct ExternalCrate { impl Clean<ExternalCrate> for cstore::crate_metadata { fn clean(&self) -> ExternalCrate { let mut primitives = Vec::new(); - let cx = super::ctxtkey.get().unwrap(); - match cx.maybe_typed { - core::Typed(ref tcx) => { - csearch::each_top_level_item_of_crate(&tcx.sess.cstore, - self.cnum, - |def, _, _| { - let did = match def { - decoder::DlDef(def::DefMod(did)) => did, - _ => return - }; - let attrs = inline::load_attrs(tcx, did); - match Primitive::find(attrs.as_slice()) { - Some(prim) => primitives.push(prim), - None => {} - } - }); - } - core::NotTyped(..) => {} - } + get_cx().tcx_opt().map(|tcx| { + csearch::each_top_level_item_of_crate(&tcx.sess.cstore, + self.cnum, + |def, _, _| { + let did = match def { + decoder::DlDef(def::DefMod(did)) => did, + _ => return + }; + let attrs = inline::load_attrs(tcx, did); + Primitive::find(attrs.as_slice()).map(|prim| primitives.push(prim)); + }) + }); ExternalCrate { name: self.name.to_string(), attrs: decoder::get_crate_attributes(self.data()).clean(), @@ -233,6 +239,7 @@ pub struct Item { pub inner: ItemEnum, pub visibility: Option<Visibility>, pub def_id: ast::DefId, + pub stability: Option<Stability>, } impl Item { @@ -380,6 +387,7 @@ impl Clean<Item> for doctree::Module { attrs: self.attrs.clean(), source: where.clean(), visibility: self.vis.clean(), + stability: self.stab.clean(), def_id: ast_util::local_def(self.id), inner: ModuleItem(Module { is_crate: self.is_crate, @@ -465,9 +473,8 @@ impl Clean<TyParam> for ast::TyParam { impl Clean<TyParam> for ty::TypeParameterDef { fn clean(&self) -> TyParam { - let cx = super::ctxtkey.get().unwrap(); - cx.external_typarams.borrow_mut().get_mut_ref().insert(self.def_id, - self.ident.clean()); + get_cx().external_typarams.borrow_mut().get_mut_ref() + .insert(self.def_id, self.ident.clean()); TyParam { name: self.ident.clean(), did: self.def_id, @@ -515,7 +522,7 @@ fn external_path(name: &str, substs: &subst::Substs) -> Path { impl Clean<TyParamBound> for ty::BuiltinBound { fn clean(&self) -> TyParamBound { - let cx = super::ctxtkey.get().unwrap(); + let cx = get_cx(); let tcx = match cx.maybe_typed { core::Typed(ref tcx) => tcx, core::NotTyped(_) => return RegionBound, @@ -550,7 +557,7 @@ impl Clean<TyParamBound> for ty::BuiltinBound { impl Clean<TyParamBound> for ty::TraitRef { fn clean(&self) -> TyParamBound { - let cx = super::ctxtkey.get().unwrap(); + let cx = get_cx(); let tcx = match cx.maybe_typed { core::Typed(ref tcx) => tcx, core::NotTyped(_) => return RegionBound, @@ -709,8 +716,9 @@ impl Clean<Item> for ast::Method { name: Some(self.ident.clean()), attrs: self.attrs.clean().move_iter().collect(), source: self.span.clean(), - def_id: ast_util::local_def(self.id.clone()), + def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: get_stability(ast_util::local_def(self.id)), inner: MethodItem(Method { generics: self.generics.clean(), self_: self.explicit_self.node.clean(), @@ -749,6 +757,7 @@ impl Clean<Item> for ast::TypeMethod { source: self.span.clean(), def_id: ast_util::local_def(self.id), visibility: None, + stability: get_stability(ast_util::local_def(self.id)), inner: TyMethodItem(TyMethod { fn_style: self.fn_style.clone(), decl: decl, @@ -792,6 +801,7 @@ impl Clean<Item> for doctree::Function { attrs: self.attrs.clean(), source: self.where.clean(), visibility: self.vis.clean(), + stability: self.stab.clean(), def_id: ast_util::local_def(self.id), inner: FunctionItem(Function { decl: self.decl.clean(), @@ -854,14 +864,10 @@ impl Clean<FnDecl> for ast::FnDecl { impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) { fn clean(&self) -> FnDecl { - let cx = super::ctxtkey.get().unwrap(); - let tcx = match cx.maybe_typed { - core::Typed(ref tcx) => tcx, - core::NotTyped(_) => unreachable!(), - }; + let cx = get_cx(); let (did, sig) = *self; let mut names = if did.node != 0 { - csearch::get_method_arg_names(&tcx.sess.cstore, did).move_iter() + csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).move_iter() } else { Vec::new().move_iter() }.peekable(); @@ -932,6 +938,7 @@ impl Clean<Item> for doctree::Trait { source: self.where.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: TraitItem(Trait { methods: self.methods.clean(), generics: self.generics.clean(), @@ -985,11 +992,7 @@ impl Clean<TraitMethod> for ast::TraitMethod { impl Clean<Item> for ty::Method { fn clean(&self) -> Item { - let cx = super::ctxtkey.get().unwrap(); - let tcx = match cx.maybe_typed { - core::Typed(ref tcx) => tcx, - core::NotTyped(_) => unreachable!(), - }; + let cx = get_cx(); let (self_, sig) = match self.explicit_self { ast::SelfStatic => (ast::SelfStatic.clean(), self.fty.sig.clone()), s => { @@ -1015,8 +1018,9 @@ impl Clean<Item> for ty::Method { Item { name: Some(self.ident.clean()), visibility: Some(ast::Inherited), + stability: get_stability(self.def_id), def_id: self.def_id, - attrs: inline::load_attrs(tcx, self.def_id), + attrs: inline::load_attrs(cx.tcx(), self.def_id), source: Span::empty(), inner: TyMethodItem(TyMethod { fn_style: self.fty.fn_style, @@ -1261,12 +1265,7 @@ impl Clean<Type> for ty::t { ty::ty_struct(did, ref substs) | ty::ty_enum(did, ref substs) | ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => { - let cx = super::ctxtkey.get().unwrap(); - let tcx = match cx.maybe_typed { - core::Typed(ref tycx) => tycx, - core::NotTyped(_) => unreachable!(), - }; - let fqn = csearch::get_item_path(tcx, did); + let fqn = csearch::get_item_path(get_cx().tcx(), did); let fqn: Vec<String> = fqn.move_iter().map(|i| { i.to_str() }).collect(); @@ -1277,8 +1276,8 @@ impl Clean<Type> for ty::t { }; let path = external_path(fqn.last().unwrap().to_str().as_slice(), substs); - cx.external_paths.borrow_mut().get_mut_ref().insert(did, - (fqn, kind)); + get_cx().external_paths.borrow_mut().get_mut_ref() + .insert(did, (fqn, kind)); ResolvedPath { path: path, typarams: None, @@ -1318,6 +1317,7 @@ impl Clean<Item> for ast::StructField { attrs: self.node.attrs.clean().move_iter().collect(), source: self.span.clean(), visibility: Some(vis), + stability: get_stability(ast_util::local_def(self.node.id)), def_id: ast_util::local_def(self.node.id), inner: StructFieldItem(TypedStructField(self.node.ty.clean())), } @@ -1332,17 +1332,14 @@ impl Clean<Item> for ty::field_ty { } else { Some(self.name) }; - let cx = super::ctxtkey.get().unwrap(); - let tcx = match cx.maybe_typed { - core::Typed(ref tycx) => tycx, - core::NotTyped(_) => unreachable!(), - }; - let ty = ty::lookup_item_type(tcx, self.id); + let cx = get_cx(); + let ty = ty::lookup_item_type(cx.tcx(), self.id); Item { name: name.clean(), - attrs: inline::load_attrs(tcx, self.id), + attrs: inline::load_attrs(cx.tcx(), self.id), source: Span::empty(), visibility: Some(self.vis), + stability: get_stability(self.id), def_id: self.id, inner: StructFieldItem(TypedStructField(ty.ty.clean())), } @@ -1373,6 +1370,7 @@ impl Clean<Item> for doctree::Struct { source: self.where.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: StructItem(Struct { struct_type: self.struct_type, generics: self.generics.clean(), @@ -1418,6 +1416,7 @@ impl Clean<Item> for doctree::Enum { source: self.where.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: EnumItem(Enum { variants: self.variants.clean(), generics: self.generics.clean(), @@ -1439,6 +1438,7 @@ impl Clean<Item> for doctree::Variant { attrs: self.attrs.clean(), source: self.where.clean(), visibility: self.vis.clean(), + stability: self.stab.clean(), def_id: ast_util::local_def(self.id), inner: VariantItem(Variant { kind: self.kind.clean(), @@ -1450,11 +1450,7 @@ impl Clean<Item> for doctree::Variant { impl Clean<Item> for ty::VariantInfo { fn clean(&self) -> Item { // use syntax::parse::token::special_idents::unnamed_field; - let cx = super::ctxtkey.get().unwrap(); - let tcx = match cx.maybe_typed { - core::Typed(ref tycx) => tycx, - core::NotTyped(_) => fail!("tcx not present"), - }; + let cx = get_cx(); let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) { None | Some([]) if self.args.len() == 0 => CLikeVariant, None | Some([]) => { @@ -1470,6 +1466,7 @@ impl Clean<Item> for ty::VariantInfo { name: Some(name.clean()), attrs: Vec::new(), visibility: Some(ast::Public), + stability: get_stability(self.id), // FIXME: this is not accurate, we need an id for // the specific field but we're using the id // for the whole variant. Nothing currently @@ -1485,11 +1482,12 @@ impl Clean<Item> for ty::VariantInfo { }; Item { name: Some(self.name.clean()), - attrs: inline::load_attrs(tcx, self.id), + attrs: inline::load_attrs(cx.tcx(), self.id), source: Span::empty(), visibility: Some(ast::Public), def_id: self.id, inner: VariantItem(Variant { kind: kind }), + stability: None, } } } @@ -1626,6 +1624,7 @@ impl Clean<Item> for doctree::Typedef { source: self.where.clean(), def_id: ast_util::local_def(self.id.clone()), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: TypedefItem(Typedef { type_: self.ty.clean(), generics: self.gen.clean(), @@ -1675,6 +1674,7 @@ impl Clean<Item> for doctree::Static { source: self.where.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: StaticItem(Static { type_: self.type_.clean(), mutability: self.mutability.clean(), @@ -1720,6 +1720,7 @@ impl Clean<Item> for doctree::Impl { source: self.where.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: self.stab.clean(), inner: ImplItem(Impl { generics: self.generics.clean(), trait_: self.trait_.clean(), @@ -1754,6 +1755,7 @@ impl Clean<Vec<Item>> for ast::ViewItem { source: self.span.clean(), def_id: ast_util::local_def(0), visibility: self.vis.clean(), + stability: None, inner: ViewItemItem(ViewItem { inner: node.clean() }), } }; @@ -1895,6 +1897,7 @@ impl Clean<Item> for ast::ForeignItem { source: self.span.clean(), def_id: ast_util::local_def(self.id), visibility: self.vis.clean(), + stability: None, inner: inner, } } @@ -1977,7 +1980,7 @@ fn name_from_pat(p: &ast::Pat) -> String { /// Given a Type, resolve it using the def_map fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>, id: ast::NodeId) -> Type { - let cx = super::ctxtkey.get().unwrap(); + let cx = get_cx(); let tycx = match cx.maybe_typed { core::Typed(ref tycx) => tycx, // If we're extracting tests, this return value doesn't matter. @@ -2012,7 +2015,7 @@ fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>, def::DefTyParamBinder(i) => return TyParamBinder(i), _ => {} }; - let did = register_def(&**cx, def); + let did = register_def(&*cx, def); ResolvedPath { path: path, typarams: tpbs, did: did } } @@ -2051,13 +2054,9 @@ fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource { } fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> { - let cx = super::ctxtkey.get().unwrap(); - match cx.maybe_typed { - core::Typed(ref tcx) => { - tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def)) - } - core::NotTyped(_) => None - } + get_cx().tcx_opt().and_then(|tcx| { + tcx.def_map.borrow().find(&id).map(|&def| register_def(&*get_cx(), def)) + }) } #[deriving(Clone, Encodable, Decodable)] @@ -2072,6 +2071,7 @@ impl Clean<Item> for doctree::Macro { attrs: self.attrs.clean(), source: self.where.clean(), visibility: ast::Public.clean(), + stability: self.stab.clean(), def_id: ast_util::local_def(self.id), inner: MacroItem(Macro { source: self.where.to_src(), @@ -2079,3 +2079,19 @@ impl Clean<Item> for doctree::Macro { } } } + +#[deriving(Clone, Encodable, Decodable)] +pub struct Stability { + pub level: attr::StabilityLevel, + pub text: String +} + +impl Clean<Stability> for attr::Stability { + fn clean(&self) -> Stability { + Stability { + level: self.level, + text: self.text.as_ref().map_or("".to_string(), + |interned| interned.get().to_string()), + } + } +} diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index ba0161da7e6..245b2d162a7 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -10,7 +10,7 @@ use rustc; use rustc::{driver, middle}; -use rustc::middle::privacy; +use rustc::middle::{privacy, ty}; use rustc::lint; use syntax::ast; @@ -26,6 +26,7 @@ use visit_ast::RustdocVisitor; use clean; use clean::Clean; +/// Are we generating documentation (`Typed`) or tests (`NotTyped`)? pub enum MaybeTyped { Typed(middle::ty::ctxt), NotTyped(driver::session::Session) @@ -52,6 +53,18 @@ impl DocContext { NotTyped(ref sess) => sess } } + + pub fn tcx_opt<'a>(&'a self) -> Option<&'a ty::ctxt> { + match self.maybe_typed { + Typed(ref tcx) => Some(tcx), + NotTyped(_) => None + } + } + + pub fn tcx<'a>(&'a self) -> &'a ty::ctxt { + let tcx_opt = self.tcx_opt(); + tcx_opt.expect("tcx not present") + } } pub struct CrateAnalysis { diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index b8a2a6195b7..313f1c81c79 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -14,6 +14,7 @@ use syntax; use syntax::codemap::Span; use syntax::ast; +use syntax::attr; use syntax::ast::{Ident, NodeId}; use std::gc::Gc; @@ -32,6 +33,7 @@ pub struct Module { pub statics: Vec<Static>, pub traits: Vec<Trait>, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub impls: Vec<Impl>, pub foreigns: Vec<ast::ForeignMod>, pub view_items: Vec<ast::ViewItem>, @@ -45,6 +47,7 @@ impl Module { name : name, id: 0, vis: ast::Inherited, + stab: None, where_outer: syntax::codemap::DUMMY_SP, where_inner: syntax::codemap::DUMMY_SP, attrs : Vec::new(), @@ -83,6 +86,7 @@ pub enum TypeBound { pub struct Struct { pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub id: NodeId, pub struct_type: StructType, pub name: Ident, @@ -94,6 +98,7 @@ pub struct Struct { pub struct Enum { pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub variants: Vec<Variant>, pub generics: ast::Generics, pub attrs: Vec<ast::Attribute>, @@ -108,6 +113,7 @@ pub struct Variant { pub kind: ast::VariantKind, pub id: ast::NodeId, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub where: Span, } @@ -117,6 +123,7 @@ pub struct Function { pub id: NodeId, pub name: Ident, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub fn_style: ast::FnStyle, pub where: Span, pub generics: ast::Generics, @@ -130,6 +137,7 @@ pub struct Typedef { pub attrs: Vec<ast::Attribute>, pub where: Span, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, } pub struct Static { @@ -139,6 +147,7 @@ pub struct Static { pub name: Ident, pub attrs: Vec<ast::Attribute>, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub id: ast::NodeId, pub where: Span, } @@ -152,6 +161,7 @@ pub struct Trait { pub id: ast::NodeId, pub where: Span, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, } pub struct Impl { @@ -162,6 +172,7 @@ pub struct Impl { pub attrs: Vec<ast::Attribute>, pub where: Span, pub vis: ast::Visibility, + pub stab: Option<attr::Stability>, pub id: ast::NodeId, } @@ -170,6 +181,7 @@ pub struct Macro { pub id: ast::NodeId, pub attrs: Vec<ast::Attribute>, pub where: Span, + pub stab: Option<attr::Stability>, } pub fn struct_type_from_def(sd: &ast::StructDef) -> StructType { diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs new file mode 100644 index 00000000000..0931f132c02 --- /dev/null +++ b/src/librustdoc/externalfiles.rs @@ -0,0 +1,70 @@ +// 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. + +use std::{io, str}; + +#[deriving(Clone)] +pub struct ExternalHtml{ + pub in_header: String, + pub before_content: String, + pub after_content: String +} + +impl ExternalHtml { + pub fn load(in_header: &[String], before_content: &[String], after_content: &[String]) + -> Option<ExternalHtml> { + match (load_external_files(in_header), + load_external_files(before_content), + load_external_files(after_content)) { + (Some(ih), Some(bc), Some(ac)) => Some(ExternalHtml { + in_header: ih, + before_content: bc, + after_content: ac + }), + _ => None + } + } +} + +pub fn load_string(input: &Path) -> io::IoResult<Option<String>> { + let mut f = try!(io::File::open(input)); + let d = try!(f.read_to_end()); + Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string())) +} + +macro_rules! load_or_return { + ($input: expr, $cant_read: expr, $not_utf8: expr) => { + { + let input = Path::new($input); + match ::externalfiles::load_string(&input) { + Err(e) => { + let _ = writeln!(&mut io::stderr(), + "error reading `{}`: {}", input.display(), e); + return $cant_read; + } + Ok(None) => { + let _ = writeln!(&mut io::stderr(), + "error reading `{}`: not UTF-8", input.display()); + return $not_utf8; + } + Ok(Some(s)) => s + } + } + } +} + +pub fn load_external_files(names: &[String]) -> Option<String> { + let mut out = String::new(); + for name in names.iter() { + out.push_str(load_or_return!(name.as_slice(), None, None).as_slice()); + out.push_char('\n'); + } + Some(out) +} diff --git a/src/librustdoc/flock.rs b/src/librustdoc/flock.rs index 800e7f065f1..f07c0163676 100644 --- a/src/librustdoc/flock.rs +++ b/src/librustdoc/flock.rs @@ -104,7 +104,7 @@ mod imp { l_sysid: 0, }; let ret = unsafe { - libc::fcntl(fd, os::F_SETLKW, &flock as *os::flock) + libc::fcntl(fd, os::F_SETLKW, &flock as *const os::flock) }; if ret == -1 { unsafe { libc::close(fd); } @@ -125,7 +125,7 @@ mod imp { l_sysid: 0, }; unsafe { - libc::fcntl(self.fd, os::F_SETLK, &flock as *os::flock); + libc::fcntl(self.fd, os::F_SETLK, &flock as *const os::flock); libc::close(self.fd); } } @@ -162,7 +162,8 @@ mod imp { impl Lock { pub fn new(p: &Path) -> Lock { - let p_16 = p.as_str().unwrap().to_utf16().append_one(0); + let p_16: Vec<u16> = p.as_str().unwrap().utf16_units().collect(); + let p_16 = p_16.append_one(0); let handle = unsafe { libc::CreateFileW(p_16.as_ptr(), libc::FILE_GENERIC_READ | diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index 77b12aec97b..60853f450ab 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -19,7 +19,7 @@ pub trait DocFolder { /// don't override! fn fold_item_recur(&mut self, item: Item) -> Option<Item> { - let Item { attrs, name, source, visibility, def_id, inner } = item; + let Item { attrs, name, source, visibility, def_id, inner, stability } = item; let inner = inner; let inner = match inner { StructItem(mut i) => { @@ -83,7 +83,7 @@ pub trait DocFolder { }; Some(Item { attrs: attrs, name: name, source: source, inner: inner, - visibility: visibility, def_id: def_id }) + visibility: visibility, stability: stability, def_id: def_id }) } fn fold_mod(&mut self, m: Module) -> Module { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 1173f6eb5b8..9677b9004cd 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -37,6 +37,10 @@ pub struct FnStyleSpace(pub ast::FnStyle); pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl); /// Similar to VisSpace, but used for mutability pub struct MutableSpace(pub clean::Mutability); +/// Wrapper struct for properly emitting the stability level. +pub struct Stability<'a>(pub &'a Option<clean::Stability>); +/// Wrapper struct for emitting the stability level concisely. +pub struct ConciseStability<'a>(pub &'a Option<clean::Stability>); impl VisSpace { pub fn get(&self) -> Option<ast::Visibility> { @@ -185,7 +189,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool, let mut generics = String::new(); let last = path.segments.last().unwrap(); if last.lifetimes.len() > 0 || last.types.len() > 0 { - let mut counter = 0; + let mut counter = 0u; generics.push_str("<"); for lifetime in last.lifetimes.iter() { if counter > 0 { generics.push_str(", "); } @@ -596,3 +600,34 @@ impl fmt::Show for MutableSpace { } } } + +impl<'a> fmt::Show for Stability<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let Stability(stab) = *self; + match *stab { + Some(ref stability) => { + write!(f, "<a class='stability {lvl}' title='{reason}'>{lvl}</a>", + lvl = stability.level.to_str(), + reason = stability.text) + } + None => Ok(()) + } + } +} + +impl<'a> fmt::Show for ConciseStability<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let ConciseStability(stab) = *self; + match *stab { + Some(ref stability) => { + write!(f, "<a class='stability {lvl}' title='{lvl}{colon}{reason}'></a>", + lvl = stability.level.to_str(), + colon = if stability.text.len() > 0 { ": " } else { "" }, + reason = stability.text) + } + None => { + write!(f, "<a class='stability Unmarked' title='No stability level'></a>") + } + } + } +} diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index 61a2d3c5d9c..aa298d07780 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -11,10 +11,13 @@ use std::fmt; use std::io; +use externalfiles::ExternalHtml; + #[deriving(Clone)] pub struct Layout { pub logo: String, pub favicon: String, + pub external_html: ExternalHtml, pub krate: String, pub playground_url: String, } @@ -44,6 +47,7 @@ r##"<!DOCTYPE html> <link rel="stylesheet" type="text/css" href="{root_path}main.css"> {favicon} + {in_header} </head> <body> <!--[if lte IE 8]> @@ -53,6 +57,8 @@ r##"<!DOCTYPE html> </div> <![endif]--> + {before_content} + <section class="sidebar"> {logo} {sidebar} @@ -105,6 +111,8 @@ r##"<!DOCTYPE html> </div> </div> + {after_content} + <script> window.rootPath = "{root_path}"; window.currentCrate = "{krate}"; @@ -133,6 +141,9 @@ r##"<!DOCTYPE html> } else { format!(r#"<link rel="shortcut icon" href="{}">"#, layout.favicon) }, + in_header = layout.external_html.in_header, + before_content = layout.external_html.before_content, + after_content = layout.external_html.after_content, sidebar = *sidebar, krate = layout.krate, play_url = layout.playground_url, diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index cfd004c0c83..de4bbeb6e30 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -66,13 +66,13 @@ type hoedown_document = libc::c_void; // this is opaque to us struct hoedown_renderer { opaque: *mut hoedown_html_renderer_state, - blockcode: Option<extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, - *hoedown_buffer, *mut libc::c_void)>, - blockquote: Option<extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, + blockcode: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer, + *const hoedown_buffer, *mut libc::c_void)>, + blockquote: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer, *mut libc::c_void)>, - blockhtml: Option<extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, + blockhtml: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer, *mut libc::c_void)>, - header: Option<extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, + header: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer, libc::c_int, *mut libc::c_void)>, other: [libc::size_t, ..28], } @@ -81,7 +81,8 @@ struct hoedown_html_renderer_state { opaque: *mut libc::c_void, toc_data: html_toc_data, flags: libc::c_uint, - link_attributes: Option<extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, + link_attributes: Option<extern "C" fn(*mut hoedown_buffer, + *const hoedown_buffer, *mut libc::c_void)>, } @@ -93,13 +94,13 @@ struct html_toc_data { } struct MyOpaque { - dfltblk: extern "C" fn(*mut hoedown_buffer, *hoedown_buffer, - *hoedown_buffer, *mut libc::c_void), + dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer, + *const hoedown_buffer, *mut libc::c_void), toc_builder: Option<TocBuilder>, } struct hoedown_buffer { - data: *u8, + data: *const u8, size: libc::size_t, asize: libc::size_t, unit: libc::size_t, @@ -118,12 +119,12 @@ extern { max_nesting: libc::size_t) -> *mut hoedown_document; fn hoedown_document_render(doc: *mut hoedown_document, ob: *mut hoedown_buffer, - document: *u8, + document: *const u8, doc_size: libc::size_t); fn hoedown_document_free(md: *mut hoedown_document); fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer; - fn hoedown_buffer_puts(b: *mut hoedown_buffer, c: *libc::c_char); + fn hoedown_buffer_puts(b: *mut hoedown_buffer, c: *const libc::c_char); fn hoedown_buffer_free(b: *mut hoedown_buffer); } @@ -147,13 +148,13 @@ local_data_key!(test_idx: Cell<uint>) local_data_key!(pub playground_krate: Option<String>) pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { - extern fn block(ob: *mut hoedown_buffer, text: *hoedown_buffer, - lang: *hoedown_buffer, opaque: *mut libc::c_void) { + extern fn block(ob: *mut hoedown_buffer, text: *const hoedown_buffer, + lang: *const hoedown_buffer, opaque: *mut libc::c_void) { unsafe { if text.is_null() { return } let opaque = opaque as *mut hoedown_html_renderer_state; - let my_opaque: &MyOpaque = &*((*opaque).opaque as *MyOpaque); + let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque); slice::raw::buf_as_slice((*text).data, (*text).size as uint, |text| { let origtext = str::from_utf8(text).unwrap(); debug!("docblock: ==============\n{}\n=======", text); @@ -205,15 +206,13 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { s.push_str(highlight::highlight(text.as_slice(), None, id) .as_slice()); let output = s.to_c_str(); - output.with_ref(|r| { - hoedown_buffer_puts(ob, r) - }) + hoedown_buffer_puts(ob, output.as_ptr()); } }) } } - extern fn header(ob: *mut hoedown_buffer, text: *hoedown_buffer, + extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer, level: libc::c_int, opaque: *mut libc::c_void) { // hoedown does this, we may as well too "\n".with_c_str(|p| unsafe { hoedown_buffer_puts(ob, p) }); @@ -304,8 +303,10 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { } pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) { - extern fn block(_ob: *mut hoedown_buffer, text: *hoedown_buffer, - lang: *hoedown_buffer, opaque: *mut libc::c_void) { + extern fn block(_ob: *mut hoedown_buffer, + text: *const hoedown_buffer, + lang: *const hoedown_buffer, + opaque: *mut libc::c_void) { unsafe { if text.is_null() { return } let block_info = if lang.is_null() { @@ -333,7 +334,8 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) { } } - extern fn header(_ob: *mut hoedown_buffer, text: *hoedown_buffer, + extern fn header(_ob: *mut hoedown_buffer, + text: *const hoedown_buffer, level: libc::c_int, opaque: *mut libc::c_void) { unsafe { let opaque = opaque as *mut hoedown_html_renderer_state; diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index aacb13156b7..917eab4eeb9 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -41,17 +41,18 @@ use std::str; use std::string::String; use std::sync::Arc; +use externalfiles::ExternalHtml; + use serialize::json::ToJson; use syntax::ast; use syntax::ast_util; -use syntax::attr; -use syntax::parse::token::InternedString; use rustc::util::nodemap::NodeSet; use clean; use doctree; use fold::DocFolder; -use html::format::{VisSpace, Method, FnStyleSpace, MutableSpace}; +use html::format::{VisSpace, Method, FnStyleSpace, MutableSpace, Stability}; +use html::format::{ConciseStability}; use html::highlight; use html::item_type::{ItemType, shortty}; use html::item_type; @@ -78,7 +79,7 @@ pub struct Context { /// This changes as the context descends into the module hierarchy. pub dst: Path, /// This describes the layout of each page, and is not modified after - /// creation of the context (contains info like the favicon) + /// creation of the context (contains info like the favicon and added html). pub layout: layout::Layout, /// This map is a list of what should be displayed on the sidebar of the /// current page. The key is the section header (traits, modules, @@ -112,6 +113,15 @@ pub struct Implementor { generics: clean::Generics, trait_: clean::Type, for_: clean::Type, + stability: Option<clean::Stability>, +} + +/// Metadata about implementations for a type. +#[deriving(Clone)] +pub struct Impl { + impl_: clean::Impl, + dox: Option<String>, + stability: Option<clean::Stability>, } /// This cache is used to store information about the `clean::Crate` being @@ -135,7 +145,7 @@ pub struct Cache { /// /// The values of the map are a list of implementations and documentation /// found on that implementation. - pub impls: HashMap<ast::DefId, Vec<(clean::Impl, Option<String>)>>, + pub impls: HashMap<ast::DefId, Vec<Impl>>, /// Maintains a mapping of local crate node ids to the fully qualified name /// and "short type description" of that node. This is used when generating @@ -220,7 +230,7 @@ local_data_key!(pub cache_key: Arc<Cache>) local_data_key!(pub current_location_key: Vec<String> ) /// Generates the documentation for `crate` into the directory `dst` -pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> { +pub fn run(mut krate: clean::Crate, external_html: &ExternalHtml, dst: Path) -> io::IoResult<()> { let mut cx = Context { dst: dst, current: Vec::new(), @@ -229,12 +239,14 @@ pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> { layout: layout::Layout { logo: "".to_string(), favicon: "".to_string(), + external_html: external_html.clone(), krate: krate.name.clone(), playground_url: "".to_string(), }, include_sources: true, render_redirect_pages: false, }; + try!(mkdir(&cx.dst)); // Crawl the crate attributes looking for attributes which control how we're @@ -546,7 +558,8 @@ fn write_shared(cx: &Context, // going on). If they're in different crates then the crate defining // the trait will be interested in our implementation. if imp.def_id.krate == did.krate { continue } - try!(write!(&mut f, r#""impl{} {} for {}","#, + try!(write!(&mut f, r#""{}impl{} {} for {}","#, + ConciseStability(&imp.stability), imp.generics, imp.trait_, imp.for_)); } try!(writeln!(&mut f, r"];")); @@ -778,6 +791,7 @@ impl DocFolder for Cache { generics: i.generics.clone(), trait_: i.trait_.get_ref().clone(), for_: i.for_.clone(), + stability: item.stability.clone(), }); } Some(..) | None => {} @@ -963,7 +977,11 @@ impl DocFolder for Cache { let v = self.impls.find_or_insert_with(did, |_| { Vec::new() }); - v.push((i, dox)); + v.push(Impl { + impl_: i, + dox: dox, + stability: item.stability.clone(), + }); } None => {} } @@ -1244,19 +1262,8 @@ impl<'a> fmt::Show for Item<'a> { try!(write!(fmt, "<a class='{}' href=''>{}</a>", shortty(self.item), self.item.name.get_ref().as_slice())); - // Write stability attributes - match attr::find_stability_generic(self.item.attrs.iter()) { - Some((ref stability, _)) => { - try!(write!(fmt, - "<a class='stability {lvl}' title='{reason}'>{lvl}</a>", - lvl = stability.level.to_str(), - reason = match stability.text { - Some(ref s) => (*s).clone(), - None => InternedString::new(""), - })); - } - None => {} - } + // Write stability level + try!(write!(fmt, "{}", Stability(&self.item.stability))); // Write `src` tag // @@ -1450,10 +1457,11 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, try!(write!(w, " <tr> - <td><code>{}static {}{}: {}</code>{}</td> + <td>{}<code>{}static {}{}: {}</code>{}</td> <td class='docblock'>{} </td> </tr> ", + ConciseStability(&myitem.stability), VisSpace(myitem.visibility), MutableSpace(s.mutability), *myitem.name.get_ref(), @@ -1488,7 +1496,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, if myitem.name.is_none() { continue } try!(write!(w, " <tr> - <td><a class='{class}' href='{href}' + <td>{stab}<a class='{class}' href='{href}' title='{title}'>{}</a></td> <td class='docblock short'>{}</td> </tr> @@ -1497,7 +1505,8 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, Markdown(shorter(myitem.doc_value())), class = shortty(myitem), href = item_path(myitem), - title = full_path(cx, myitem))); + title = full_path(cx, myitem), + stab = ConciseStability(&myitem.stability))); } } } @@ -1561,9 +1570,10 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, try!(document(w, it)); fn meth(w: &mut fmt::Formatter, m: &clean::TraitMethod) -> fmt::Result { - try!(write!(w, "<h3 id='{}.{}' class='method'><code>", - shortty(m.item()), - *m.item().name.get_ref())); + try!(write!(w, "<h3 id='{}.{}' class='method'>{}<code>", + shortty(m.item()), + *m.item().name.get_ref(), + ConciseStability(&m.item().stability))); try!(render_method(w, m.item())); try!(write!(w, "</code></h3>")); try!(document(w, m.item())); @@ -1600,7 +1610,8 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, match cache.implementors.find(&it.def_id) { Some(implementors) => { for i in implementors.iter() { - try!(writeln!(w, "<li><code>impl{} {} for {}</code></li>", + try!(writeln!(w, "<li>{}<code>impl{} {} for {}</code></li>", + ConciseStability(&i.stability), i.generics, i.trait_, i.for_)); } } @@ -1673,7 +1684,8 @@ fn item_struct(w: &mut fmt::Formatter, it: &clean::Item, try!(write!(w, "<h2 class='fields'>Fields</h2>\n<table>")); for field in fields { try!(write!(w, "<tr><td id='structfield.{name}'>\ - <code>{name}</code></td><td>", + {stab}<code>{name}</code></td><td>", + stab = ConciseStability(&field.stability), name = field.name.get_ref().as_slice())); try!(document(w, field)); try!(write!(w, "</td></tr>")); @@ -1739,7 +1751,8 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item, if e.variants.len() > 0 { try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>")); for variant in e.variants.iter() { - try!(write!(w, "<tr><td id='variant.{name}'><code>{name}</code></td><td>", + try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>", + stab = ConciseStability(&variant.stability), name = variant.name.get_ref().as_slice())); try!(document(w, variant)); match variant.inner { @@ -1849,39 +1862,25 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item, fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result { match cache_key.get().unwrap().impls.find(&it.def_id) { Some(v) => { - let mut non_trait = v.iter().filter(|p| { - p.ref0().trait_.is_none() - }); - let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<String>)>>(); - let mut traits = v.iter().filter(|p| { - p.ref0().trait_.is_some() - }); - let traits = traits.collect::<Vec<&(clean::Impl, Option<String>)>>(); - + let (non_trait, traits) = v.partitioned(|i| i.impl_.trait_.is_none()); if non_trait.len() > 0 { try!(write!(w, "<h2 id='methods'>Methods</h2>")); - for &(ref i, ref dox) in non_trait.move_iter() { - try!(render_impl(w, i, dox)); + for i in non_trait.iter() { + try!(render_impl(w, i)); } } if traits.len() > 0 { try!(write!(w, "<h2 id='implementations'>Trait \ Implementations</h2>")); - let mut any_derived = false; - for & &(ref i, ref dox) in traits.iter() { - if !i.derived { - try!(render_impl(w, i, dox)); - } else { - any_derived = true; - } + let (derived, manual) = traits.partition(|i| i.impl_.derived); + for i in manual.iter() { + try!(render_impl(w, i)); } - if any_derived { + if derived.len() > 0 { try!(write!(w, "<h3 id='derived_implementations'>Derived Implementations \ </h3>")); - for &(ref i, ref dox) in traits.move_iter() { - if i.derived { - try!(render_impl(w, i, dox)); - } + for i in derived.iter() { + try!(render_impl(w, i)); } } } @@ -1891,15 +1890,16 @@ fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result { Ok(()) } -fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl, - dox: &Option<String>) -> fmt::Result { - try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics)); - match i.trait_ { +fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result { + try!(write!(w, "<h3 class='impl'>{}<code>impl{} ", + ConciseStability(&i.stability), + i.impl_.generics)); + match i.impl_.trait_ { Some(ref ty) => try!(write!(w, "{} for ", *ty)), None => {} } - try!(write!(w, "{}</code></h3>", i.for_)); - match *dox { + try!(write!(w, "{}</code></h3>", i.impl_.for_)); + match i.dox { Some(ref dox) => { try!(write!(w, "<div class='docblock'>{}</div>", Markdown(dox.as_slice()))); @@ -1909,8 +1909,9 @@ fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl, fn docmeth(w: &mut fmt::Formatter, item: &clean::Item, dox: bool) -> fmt::Result { - try!(write!(w, "<h4 id='method.{}' class='method'><code>", - *item.name.get_ref())); + try!(write!(w, "<h4 id='method.{}' class='method'>{}<code>", + *item.name.get_ref(), + ConciseStability(&item.stability))); try!(render_method(w, item)); try!(write!(w, "</code></h4>\n")); match item.doc_value() { @@ -1922,8 +1923,8 @@ fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl, } } - try!(write!(w, "<div class='methods'>")); - for meth in i.methods.iter() { + try!(write!(w, "<div class='impl-methods'>")); + for meth in i.impl_.methods.iter() { try!(docmeth(w, meth, true)); } @@ -1944,11 +1945,11 @@ fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl, // If we've implemented a trait, then also emit documentation for all // default methods which weren't overridden in the implementation block. - match i.trait_ { + match i.impl_.trait_ { Some(clean::ResolvedPath { did, .. }) => { try!({ match cache_key.get().unwrap().traits.find(&did) { - Some(t) => try!(render_default_methods(w, t, i)), + Some(t) => try!(render_default_methods(w, t, &i.impl_)), None => {} } Ok(()) diff --git a/src/librustdoc/html/static/main.css b/src/librustdoc/html/static/main.css index a88992f6c4c..97048229ac4 100644 --- a/src/librustdoc/html/static/main.css +++ b/src/librustdoc/html/static/main.css @@ -258,8 +258,9 @@ nav.sub { .content .multi-column li { width: 100%; display: inline-block; } .content .method { font-size: 1em; } -.content .methods { margin-left: 20px; } -.content .methods .docblock { margin-left: 20px; } +.content .methods .docblock { margin-left: 40px; } + +.content .impl-methods .docblock { margin-left: 40px; } nav { border-bottom: 1px solid #e0e0e0; @@ -372,20 +373,29 @@ p a:hover { text-decoration: underline; } } .stability { - border-left: 6px solid #000; + border-left: 6px solid; + padding: 3px 6px; border-radius: 3px; - font-weight: 400; - padding: 4px 10px; +} + +h1 .stability { text-transform: lowercase; + font-weight: 400; margin-left: 14px; + padding: 4px 10px; +} + +.impl-methods .stability { + margin-right: 20px; } -.stability.Deprecated { border-color: #D60027; color: #880017; } -.stability.Experimental { border-color: #EC5315; color: #a53c0e; } -.stability.Unstable { border-color: #FFD700; color: #b39800; } -.stability.Stable { border-color: #AEC516; color: #7c8b10; } +.stability.Deprecated { border-color: #A071A8; color: #82478C; } +.stability.Experimental { border-color: #D46D6A; color: #AA3C39; } +.stability.Unstable { border-color: #D4B16A; color: #AA8439; } +.stability.Stable { border-color: #54A759; color: #2D8632; } .stability.Frozen { border-color: #009431; color: #007726; } .stability.Locked { border-color: #0084B6; color: #00668c; } +.stability.Unmarked { border-color: #FFFFFF; } :target { background: #FDFFD3; } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index e11e6b41cb1..d878313ee28 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -32,6 +32,7 @@ use std::io::{File, MemWriter}; use std::str; use std::gc::Gc; use serialize::{json, Decodable, Encodable}; +use externalfiles::ExternalHtml; // reexported from `clean` so it can be easily updated with the mod itself pub use clean::SCHEMA_VERSION; @@ -39,6 +40,8 @@ pub use clean::SCHEMA_VERSION; pub mod clean; pub mod core; pub mod doctree; +#[macro_escape] +pub mod externalfiles; pub mod fold; pub mod html { pub mod highlight; @@ -113,16 +116,17 @@ pub fn opts() -> Vec<getopts::OptGroup> { "ARGS"), optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file", "FILES"), - optmulti("", "markdown-in-header", - "files to include inline in the <head> section of a rendered Markdown file", + optmulti("", "html-in-header", + "files to include inline in the <head> section of a rendered Markdown file \ + or generated documentation", "FILES"), - optmulti("", "markdown-before-content", + optmulti("", "html-before-content", "files to include inline between <body> and the content of a rendered \ - Markdown file", + Markdown file or generated documentation", "FILES"), - optmulti("", "markdown-after-content", + optmulti("", "html-after-content", "files to include inline between the content and </body> of a rendered \ - Markdown file", + Markdown file or generated documentation", "FILES"), optopt("", "markdown-playground-url", "URL to send code snippets to", "URL") @@ -179,6 +183,14 @@ pub fn main_args(args: &[String]) -> int { let output = matches.opt_str("o").map(|s| Path::new(s)); let cfgs = matches.opt_strs("cfg"); + let external_html = match ExternalHtml::load( + matches.opt_strs("html-in-header").as_slice(), + matches.opt_strs("html-before-content").as_slice(), + matches.opt_strs("html-after-content").as_slice()) { + Some(eh) => eh, + None => return 3 + }; + match (should_test, markdown_input) { (true, true) => { return markdown::test(input, libs, test_args) @@ -187,7 +199,7 @@ pub fn main_args(args: &[String]) -> int { return test::run(input, cfgs, libs, test_args) } (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")), - &matches), + &matches, &external_html), (false, false) => {} } @@ -215,7 +227,7 @@ pub fn main_args(args: &[String]) -> int { let started = time::precise_time_ns(); match matches.opt_str("w").as_ref().map(|s| s.as_slice()) { Some("html") | None => { - match html::render::run(krate, output.unwrap_or(Path::new("doc"))) { + match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) { Ok(()) => {} Err(e) => fail!("failed to generate documentation: {}", e), } @@ -396,18 +408,17 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> , // "crate": { parsed crate ... }, // "plugins": { output of plugins ... } // } - let mut json = box std::collections::TreeMap::new(); - json.insert("schema".to_string(), - json::String(SCHEMA_VERSION.to_string())); - let plugins_json = box res.move_iter() - .filter_map(|opt| { - match opt { - None => None, - Some((string, json)) => { - Some((string.to_string(), json)) - } + let mut json = std::collections::TreeMap::new(); + json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string())); + let plugins_json = res.move_iter() + .filter_map(|opt| { + match opt { + None => None, + Some((string, json)) => { + Some((string.to_string(), json)) } - }).collect(); + } + }).collect(); // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode // straight to the Rust JSON representation. @@ -417,7 +428,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> , let mut encoder = json::Encoder::new(&mut w as &mut io::Writer); krate.encode(&mut encoder).unwrap(); } - str::from_utf8(w.unwrap().as_slice()).unwrap().to_string() + str::from_utf8_owned(w.unwrap()).unwrap() }; let crate_json = match json::from_str(crate_json_str.as_slice()) { Ok(j) => j, @@ -428,6 +439,5 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> , json.insert("plugins".to_string(), json::Object(plugins_json)); let mut file = try!(File::create(&dst)); - try!(json::Object(json).to_writer(&mut file)); - Ok(()) + json::Object(json).to_writer(&mut file) } diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 76366240f1a..da271be4768 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -9,43 +9,19 @@ // except according to those terms. use std::collections::HashSet; -use std::{str, io}; +use std::io; use std::string::String; use getopts; use testing; +use externalfiles::ExternalHtml; + use html::escape::Escape; use html::markdown; use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers}; use test::Collector; -fn load_string(input: &Path) -> io::IoResult<Option<String>> { - let mut f = try!(io::File::open(input)); - let d = try!(f.read_to_end()); - Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string())) -} -macro_rules! load_or_return { - ($input: expr, $cant_read: expr, $not_utf8: expr) => { - { - let input = Path::new($input); - match load_string(&input) { - Err(e) => { - let _ = writeln!(&mut io::stderr(), - "error reading `{}`: {}", input.display(), e); - return $cant_read; - } - Ok(None) => { - let _ = writeln!(&mut io::stderr(), - "error reading `{}`: not UTF-8", input.display()); - return $not_utf8; - } - Ok(Some(s)) => s - } - } - } -} - /// Separate any lines at the start of the file that begin with `%`. fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); @@ -62,18 +38,10 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { (metadata, "") } -fn load_external_files(names: &[String]) -> Option<String> { - let mut out = String::new(); - for name in names.iter() { - out.push_str(load_or_return!(name.as_slice(), None, None).as_slice()); - out.push_char('\n'); - } - Some(out) -} - /// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). -pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { +pub fn render(input: &str, mut output: Path, matches: &getopts::Matches, + external_html: &ExternalHtml) -> int { let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_extension("html"); @@ -91,17 +59,6 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int } let playground = playground.unwrap_or("".to_string()); - let (in_header, before_content, after_content) = - match (load_external_files(matches.opt_strs("markdown-in-header") - .as_slice()), - load_external_files(matches.opt_strs("markdown-before-content") - .as_slice()), - load_external_files(matches.opt_strs("markdown-after-content") - .as_slice())) { - (Some(a), Some(b), Some(c)) => (a,b,c), - _ => return 3 - }; - let mut out = match io::File::create(&output) { Err(e) => { let _ = writeln!(&mut io::stderr(), @@ -153,10 +110,10 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int </html>"#, title = Escape(title), css = css, - in_header = in_header, - before_content = before_content, + in_header = external_html.in_header, + before_content = external_html.before_content, text = MarkdownWithToc(text), - after_content = after_content, + after_content = external_html.after_content, playground = playground, ); diff --git a/src/librustdoc/plugins.rs b/src/librustdoc/plugins.rs index e5bced8038b..9ac36665563 100644 --- a/src/librustdoc/plugins.rs +++ b/src/librustdoc/plugins.rs @@ -48,7 +48,7 @@ impl PluginManager { let lib = lib_result.unwrap(); unsafe { let plugin = lib.symbol("rustdoc_plugin_entrypoint").unwrap(); - self.callbacks.push(mem::transmute::<*u8,PluginCallback>(plugin)); + self.callbacks.push(mem::transmute::<*mut u8,PluginCallback>(plugin)); } self.dylibs.push(lib); } diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index e7fc3cedf5e..7e7f10f7178 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -140,7 +140,14 @@ fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool, let old = io::stdio::set_stderr(box w1); spawn(proc() { let mut p = io::ChanReader::new(rx); - let mut err = old.unwrap_or(box io::stderr() as Box<Writer + Send>); + let mut err = match old { + Some(old) => { + // Chop off the `Send` bound. + let old: Box<Writer> = old; + old + } + None => box io::stderr() as Box<Writer>, + }; io::util::copy(&mut p, &mut err).unwrap(); }); let emitter = diagnostic::EmitterWriter::new(box w2); diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 00fe0134f00..b7ef0956a7c 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -15,9 +15,12 @@ use syntax::abi; use syntax::ast; use syntax::ast_util; use syntax::ast_map; +use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; +use rustc::middle::stability; + use std::gc::{Gc, GC}; use core; @@ -41,6 +44,14 @@ impl<'a> RustdocVisitor<'a> { } } + fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> { + let tcx = match self.cx.maybe_typed { + core::Typed(ref tcx) => tcx, + core::NotTyped(_) => return None + }; + stability::lookup(tcx, ast_util::local_def(id)) + } + pub fn visit(&mut self, krate: &ast::Crate) { self.attrs = krate.attrs.iter().map(|x| (*x).clone()).collect(); @@ -65,6 +76,7 @@ impl<'a> RustdocVisitor<'a> { struct_type: struct_type, name: item.ident, vis: item.vis, + stab: self.stability(item.id), attrs: item.attrs.iter().map(|x| *x).collect(), generics: generics.clone(), fields: sd.fields.iter().map(|x| (*x).clone()).collect(), @@ -81,6 +93,7 @@ impl<'a> RustdocVisitor<'a> { name: x.node.name, attrs: x.node.attrs.iter().map(|x| *x).collect(), vis: x.node.vis, + stab: self.stability(x.node.id), id: x.node.id, kind: x.node.kind.clone(), where: x.span, @@ -90,6 +103,7 @@ impl<'a> RustdocVisitor<'a> { name: it.ident, variants: vars, vis: it.vis, + stab: self.stability(it.id), generics: params.clone(), attrs: it.attrs.iter().map(|x| *x).collect(), id: it.id, @@ -104,6 +118,7 @@ impl<'a> RustdocVisitor<'a> { Function { id: item.id, vis: item.vis, + stab: self.stability(item.id), attrs: item.attrs.iter().map(|x| *x).collect(), decl: fd.clone(), name: item.ident, @@ -125,6 +140,7 @@ impl<'a> RustdocVisitor<'a> { om.where_inner = m.inner; om.attrs = attrs; om.vis = vis; + om.stab = self.stability(id); om.id = id; for i in m.items.iter() { self.visit_item(&**i, &mut om); @@ -258,6 +274,7 @@ impl<'a> RustdocVisitor<'a> { attrs: item.attrs.iter().map(|x| *x).collect(), where: item.span, vis: item.vis, + stab: self.stability(item.id), }; om.typedefs.push(t); }, @@ -271,6 +288,7 @@ impl<'a> RustdocVisitor<'a> { attrs: item.attrs.iter().map(|x| *x).collect(), where: item.span, vis: item.vis, + stab: self.stability(item.id), }; om.statics.push(s); }, @@ -284,6 +302,7 @@ impl<'a> RustdocVisitor<'a> { attrs: item.attrs.iter().map(|x| *x).collect(), where: item.span, vis: item.vis, + stab: self.stability(item.id), }; om.traits.push(t); }, @@ -297,6 +316,7 @@ impl<'a> RustdocVisitor<'a> { id: item.id, where: item.span, vis: item.vis, + stab: self.stability(item.id), }; om.impls.push(i); }, @@ -309,6 +329,7 @@ impl<'a> RustdocVisitor<'a> { attrs: item.attrs.iter().map(|x| *x).collect(), name: item.ident, where: item.span, + stab: self.stability(item.id), }) } } diff --git a/src/librustrt/args.rs b/src/librustrt/args.rs index 09ae2b31f63..3c0a4aae251 100644 --- a/src/librustrt/args.rs +++ b/src/librustrt/args.rs @@ -23,7 +23,7 @@ use core::prelude::*; use collections::vec::Vec; /// One-time global initialization. -pub unsafe fn init(argc: int, argv: **u8) { imp::init(argc, argv) } +pub unsafe fn init(argc: int, argv: *const *const u8) { imp::init(argc, argv) } /// One-time global cleanup. pub unsafe fn cleanup() { imp::cleanup() } @@ -55,7 +55,7 @@ mod imp { static mut global_args_ptr: uint = 0; static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT; - pub unsafe fn init(argc: int, argv: **u8) { + pub unsafe fn init(argc: int, argv: *const *const u8) { let args = load_argc_and_argv(argc, argv); put(args); } @@ -99,7 +99,7 @@ mod imp { unsafe { mem::transmute(&global_args_ptr) } } - unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> Vec<Vec<u8>> { + unsafe fn load_argc_and_argv(argc: int, argv: *const *const u8) -> Vec<Vec<u8>> { Vec::from_fn(argc as uint, |i| { let base = *argv.offset(i as int); let mut len = 0; @@ -151,7 +151,7 @@ mod imp { use core::prelude::*; use collections::vec::Vec; - pub unsafe fn init(_argc: int, _argv: **u8) { + pub unsafe fn init(_argc: int, _argv: *const *const u8) { } pub fn cleanup() { diff --git a/src/librustrt/at_exit_imp.rs b/src/librustrt/at_exit_imp.rs index 2f1c38c5686..dcba7fb7cb6 100644 --- a/src/librustrt/at_exit_imp.rs +++ b/src/librustrt/at_exit_imp.rs @@ -43,7 +43,7 @@ pub fn push(f: proc():Send) { rtassert!(!RUNNING.load(atomics::SeqCst)); let queue = QUEUE.load(atomics::SeqCst); rtassert!(queue != 0); - (*(queue as *Queue)).lock().push(f); + (*(queue as *const Queue)).lock().push(f); } } diff --git a/src/librustrt/c_str.rs b/src/librustrt/c_str.rs index 10d1594e78e..9734ba2d751 100644 --- a/src/librustrt/c_str.rs +++ b/src/librustrt/c_str.rs @@ -42,7 +42,7 @@ An example of creating and using a C string would be: extern crate libc; extern { - fn puts(s: *libc::c_char); + fn puts(s: *const libc::c_char); } fn main() { @@ -51,11 +51,11 @@ fn main() { // Allocate the C string with an explicit local that owns the string. The // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope. let my_c_string = my_string.to_c_str(); - my_c_string.with_ref(|c_buffer| { - unsafe { puts(c_buffer); } - }); + unsafe { + puts(my_c_string.as_ptr()); + } - // Don't save off the allocation of the C string, the `c_buffer` will be + // Don't save/return the pointer to the C string, the `c_buffer` will be // deallocated when this block returns! my_string.with_c_str(|c_buffer| { unsafe { puts(c_buffer); } @@ -82,7 +82,7 @@ use libc; /// This structure wraps a `*libc::c_char`, and will automatically free the /// memory it is pointing to when it goes out of scope. pub struct CString { - buf: *libc::c_char, + buf: *const libc::c_char, owns_buffer_: bool, } @@ -97,7 +97,7 @@ impl Clone for CString { let len = self.len() + 1; let buf = unsafe { malloc_raw(len) } as *mut libc::c_char; unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); } - CString { buf: buf as *libc::c_char, owns_buffer_: true } + CString { buf: buf as *const libc::c_char, owns_buffer_: true } } } } @@ -118,19 +118,75 @@ impl PartialEq for CString { impl CString { /// Create a C String from a pointer. - pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString { + pub unsafe fn new(buf: *const libc::c_char, owns_buffer: bool) -> CString { CString { buf: buf, owns_buffer_: owns_buffer } } - /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper. + /// Return a pointer to the NUL-terminated string data. + /// + /// `.as_ptr` returns an internal pointer into the `CString`, and + /// may be invalidated when the `CString` falls out of scope (the + /// destructor will run, freeing the allocation if there is + /// one). + /// + /// ```rust + /// let foo = "some string"; + /// + /// // right + /// let x = foo.to_c_str(); + /// let p = x.as_ptr(); + /// + /// // wrong (the CString will be freed, invalidating `p`) + /// let p = foo.to_c_str().as_ptr(); + /// ``` + /// + /// # Failure + /// + /// Fails if the CString is null. + /// + /// # Example + /// + /// ```rust + /// extern crate libc; /// - /// The original object is destructed after this method is called, and if - /// the underlying pointer was previously allocated, care must be taken to - /// ensure that it is deallocated properly. - pub unsafe fn unwrap(self) -> *libc::c_char { - let mut c_str = self; - c_str.owns_buffer_ = false; - c_str.buf + /// fn main() { + /// let c_str = "foo bar".to_c_str(); + /// unsafe { + /// libc::puts(c_str.as_ptr()); + /// } + /// } + /// ``` + pub fn as_ptr(&self) -> *const libc::c_char { + if self.buf.is_null() { fail!("CString is null!"); } + + self.buf + } + + /// Return a mutable pointer to the NUL-terminated string data. + /// + /// `.as_mut_ptr` returns an internal pointer into the `CString`, and + /// may be invalidated when the `CString` falls out of scope (the + /// destructor will run, freeing the allocation if there is + /// one). + /// + /// ```rust + /// let foo = "some string"; + /// + /// // right + /// let mut x = foo.to_c_str(); + /// let p = x.as_mut_ptr(); + /// + /// // wrong (the CString will be freed, invalidating `p`) + /// let p = foo.to_c_str().as_mut_ptr(); + /// ``` + /// + /// # Failure + /// + /// Fails if the CString is null. + pub fn as_mut_ptr(&mut self) -> *mut libc::c_char { + if self.buf.is_null() { fail!("CString is null!") } + + self.buf as *mut _ } /// Calls a closure with a reference to the underlying `*libc::c_char`. @@ -138,7 +194,8 @@ impl CString { /// # Failure /// /// Fails if the CString is null. - pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T { + #[deprecated="use `.as_ptr()`"] + pub fn with_ref<T>(&self, f: |*const libc::c_char| -> T) -> T { if self.buf.is_null() { fail!("CString is null!"); } f(self.buf) } @@ -148,6 +205,7 @@ impl CString { /// # Failure /// /// Fails if the CString is null. + #[deprecated="use `.as_mut_ptr()`"] pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T { if self.buf.is_null() { fail!("CString is null!"); } f(self.buf as *mut libc::c_char) @@ -220,6 +278,22 @@ impl CString { marker: marker::ContravariantLifetime, } } + + /// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper. + /// + /// Any ownership of the buffer by the `CString` wrapper is + /// forgotten, meaning that the backing allocation of this + /// `CString` is not automatically freed if it owns the + /// allocation. In this case, a user of `.unwrap()` should ensure + /// the allocation is freed, to avoid leaking memory. + /// + /// Prefer `.as_ptr()` when just retrieving a pointer to the + /// string data, as that does not relinquish ownership. + pub unsafe fn unwrap(mut self) -> *const libc::c_char { + self.owns_buffer_ = false; + self.buf + } + } impl Drop for CString { @@ -284,14 +358,16 @@ pub trait ToCStr { /// /// Fails the task if the receiver has an interior null. #[inline] - fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { - self.to_c_str().with_ref(f) + fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T { + let c_str = self.to_c_str(); + f(c_str.as_ptr()) } /// Unsafe variant of `with_c_str()` that doesn't check for nulls. #[inline] - unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T { - self.to_c_str_unchecked().with_ref(f) + unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T { + let c_str = self.to_c_str_unchecked(); + f(c_str.as_ptr()) } } @@ -315,12 +391,12 @@ impl<'a> ToCStr for &'a str { } #[inline] - fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { + fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T { self.as_bytes().with_c_str(f) } #[inline] - unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T { + unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T { self.as_bytes().with_c_str_unchecked(f) } } @@ -337,12 +413,12 @@ impl ToCStr for String { } #[inline] - fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { + fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T { self.as_bytes().with_c_str(f) } #[inline] - unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T { + unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T { self.as_bytes().with_c_str_unchecked(f) } } @@ -353,7 +429,7 @@ static BUF_LEN: uint = 128; impl<'a> ToCStr for &'a [u8] { fn to_c_str(&self) -> CString { let mut cs = unsafe { self.to_c_str_unchecked() }; - cs.with_mut_ref(|buf| check_for_null(*self, buf)); + check_for_null(*self, cs.as_mut_ptr()); cs } @@ -364,21 +440,22 @@ impl<'a> ToCStr for &'a [u8] { ptr::copy_memory(buf, self.as_ptr(), self_len); *buf.offset(self_len as int) = 0; - CString::new(buf as *libc::c_char, true) + CString::new(buf as *const libc::c_char, true) } - fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { + fn with_c_str<T>(&self, f: |*const libc::c_char| -> T) -> T { unsafe { with_c_str(*self, true, f) } } - unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T { + unsafe fn with_c_str_unchecked<T>(&self, f: |*const libc::c_char| -> T) -> T { with_c_str(*self, false, f) } } // Unsafe function that handles possibly copying the &[u8] into a stack array. -unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T { - if v.len() < BUF_LEN { +unsafe fn with_c_str<T>(v: &[u8], checked: bool, + f: |*const libc::c_char| -> T) -> T { + let c_str = if v.len() < BUF_LEN { let mut buf: [u8, .. BUF_LEN] = mem::uninitialized(); slice::bytes::copy_memory(buf, v); buf[v.len()] = 0; @@ -388,12 +465,14 @@ unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T { check_for_null(v, buf as *mut libc::c_char); } - f(buf as *libc::c_char) + return f(buf as *const libc::c_char) } else if checked { - v.to_c_str().with_ref(f) + v.to_c_str() } else { - v.to_c_str_unchecked().with_ref(f) - } + v.to_c_str_unchecked() + }; + + f(c_str.as_ptr()) } #[inline] @@ -410,7 +489,7 @@ fn check_for_null(v: &[u8], buf: *mut libc::c_char) { /// /// Use with the `std::iter` module. pub struct CChars<'a> { - ptr: *libc::c_char, + ptr: *const libc::c_char, marker: marker::ContravariantLifetime<'a>, } @@ -434,7 +513,7 @@ impl<'a> Iterator<libc::c_char> for CChars<'a> { /// /// The specified closure is invoked with each string that /// is found, and the number of strings found is returned. -pub unsafe fn from_c_multistring(buf: *libc::c_char, +pub unsafe fn from_c_multistring(buf: *const libc::c_char, count: Option<uint>, f: |&CString|) -> uint { @@ -445,8 +524,8 @@ pub unsafe fn from_c_multistring(buf: *libc::c_char, None => (false, 0) }; while ((limited_count && ctr < limit) || !limited_count) - && *(curr_ptr as *libc::c_char) != 0 as libc::c_char { - let cstr = CString::new(curr_ptr as *libc::c_char, false); + && *(curr_ptr as *const libc::c_char) != 0 as libc::c_char { + let cstr = CString::new(curr_ptr as *const libc::c_char, false); f(&cstr); curr_ptr += cstr.len() + 1; ctr += 1; @@ -470,7 +549,7 @@ mod tests { let ptr = input.as_ptr(); let expected = ["zero", "one"]; let mut it = expected.iter(); - let result = from_c_multistring(ptr as *libc::c_char, None, |c| { + let result = from_c_multistring(ptr as *const libc::c_char, None, |c| { let cbytes = c.as_bytes_no_nul(); assert_eq!(cbytes, it.next().unwrap().as_bytes()); }); @@ -481,53 +560,51 @@ mod tests { #[test] fn test_str_to_c_str() { - "".to_c_str().with_ref(|buf| { - unsafe { - assert_eq!(*buf.offset(0), 0); - } - }); + let c_str = "".to_c_str(); + unsafe { + assert_eq!(*c_str.as_ptr().offset(0), 0); + } - "hello".to_c_str().with_ref(|buf| { - unsafe { - assert_eq!(*buf.offset(0), 'h' as libc::c_char); - assert_eq!(*buf.offset(1), 'e' as libc::c_char); - assert_eq!(*buf.offset(2), 'l' as libc::c_char); - assert_eq!(*buf.offset(3), 'l' as libc::c_char); - assert_eq!(*buf.offset(4), 'o' as libc::c_char); - assert_eq!(*buf.offset(5), 0); - } - }) + let c_str = "hello".to_c_str(); + let buf = c_str.as_ptr(); + unsafe { + assert_eq!(*buf.offset(0), 'h' as libc::c_char); + assert_eq!(*buf.offset(1), 'e' as libc::c_char); + assert_eq!(*buf.offset(2), 'l' as libc::c_char); + assert_eq!(*buf.offset(3), 'l' as libc::c_char); + assert_eq!(*buf.offset(4), 'o' as libc::c_char); + assert_eq!(*buf.offset(5), 0); + } } #[test] fn test_vec_to_c_str() { let b: &[u8] = []; - b.to_c_str().with_ref(|buf| { - unsafe { - assert_eq!(*buf.offset(0), 0); - } - }); + let c_str = b.to_c_str(); + unsafe { + assert_eq!(*c_str.as_ptr().offset(0), 0); + } - let _ = b"hello".to_c_str().with_ref(|buf| { - unsafe { - assert_eq!(*buf.offset(0), 'h' as libc::c_char); - assert_eq!(*buf.offset(1), 'e' as libc::c_char); - assert_eq!(*buf.offset(2), 'l' as libc::c_char); - assert_eq!(*buf.offset(3), 'l' as libc::c_char); - assert_eq!(*buf.offset(4), 'o' as libc::c_char); - assert_eq!(*buf.offset(5), 0); - } - }); + let c_str = b"hello".to_c_str(); + let buf = c_str.as_ptr(); + unsafe { + assert_eq!(*buf.offset(0), 'h' as libc::c_char); + assert_eq!(*buf.offset(1), 'e' as libc::c_char); + assert_eq!(*buf.offset(2), 'l' as libc::c_char); + assert_eq!(*buf.offset(3), 'l' as libc::c_char); + assert_eq!(*buf.offset(4), 'o' as libc::c_char); + assert_eq!(*buf.offset(5), 0); + } - let _ = b"foo\xFF".to_c_str().with_ref(|buf| { - unsafe { - assert_eq!(*buf.offset(0), 'f' as libc::c_char); - assert_eq!(*buf.offset(1), 'o' as libc::c_char); - assert_eq!(*buf.offset(2), 'o' as libc::c_char); - assert_eq!(*buf.offset(3), 0xff as i8); - assert_eq!(*buf.offset(4), 0); - } - }); + let c_str = b"foo\xFF".to_c_str(); + let buf = c_str.as_ptr(); + unsafe { + assert_eq!(*buf.offset(0), 'f' as libc::c_char); + assert_eq!(*buf.offset(1), 'o' as libc::c_char); + assert_eq!(*buf.offset(2), 'o' as libc::c_char); + assert_eq!(*buf.offset(3), 0xffu8 as i8); + assert_eq!(*buf.offset(4), 0); + } } #[test] @@ -544,19 +621,18 @@ mod tests { } #[test] - fn test_with_ref() { + fn test_as_ptr() { let c_str = "hello".to_c_str(); - let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) }; + let len = unsafe { libc::strlen(c_str.as_ptr()) }; assert!(!c_str.is_null()); assert!(c_str.is_not_null()); assert_eq!(len, 5); } - #[test] #[should_fail] - fn test_with_ref_empty_fail() { + fn test_as_ptr_empty_fail() { let c_str = unsafe { CString::new(ptr::null(), false) }; - c_str.with_ref(|_| ()); + c_str.as_ptr(); } #[test] @@ -583,15 +659,15 @@ mod tests { #[test] fn test_to_c_str_unchecked() { unsafe { - "he\x00llo".to_c_str_unchecked().with_ref(|buf| { - assert_eq!(*buf.offset(0), 'h' as libc::c_char); - assert_eq!(*buf.offset(1), 'e' as libc::c_char); - assert_eq!(*buf.offset(2), 0); - assert_eq!(*buf.offset(3), 'l' as libc::c_char); - assert_eq!(*buf.offset(4), 'l' as libc::c_char); - assert_eq!(*buf.offset(5), 'o' as libc::c_char); - assert_eq!(*buf.offset(6), 0); - }) + let c_string = "he\x00llo".to_c_str_unchecked(); + let buf = c_string.as_ptr(); + assert_eq!(*buf.offset(0), 'h' as libc::c_char); + assert_eq!(*buf.offset(1), 'e' as libc::c_char); + assert_eq!(*buf.offset(2), 0); + assert_eq!(*buf.offset(3), 'l' as libc::c_char); + assert_eq!(*buf.offset(4), 'l' as libc::c_char); + assert_eq!(*buf.offset(5), 'o' as libc::c_char); + assert_eq!(*buf.offset(6), 0); } } @@ -674,10 +750,10 @@ mod tests { let s = "test".to_string(); let c = s.to_c_str(); // give the closure a non-owned CString - let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } ); + let mut c_ = unsafe { CString::new(c.as_ptr(), false) }; f(&c_); // muck with the buffer for later printing - c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } ); + unsafe { *c_.as_mut_ptr() = 'X' as libc::c_char } } let mut c_: Option<CString> = None; @@ -707,7 +783,7 @@ mod bench { use std::prelude::*; #[inline] - fn check(s: &str, c_str: *libc::c_char) { + fn check(s: &str, c_str: *const libc::c_char) { let s_buf = s.as_ptr(); for i in range(0, s.len()) { unsafe { @@ -731,7 +807,7 @@ mod bench { fn bench_to_str(b: &mut Bencher, s: &str) { b.iter(|| { let c_str = s.to_c_str(); - c_str.with_ref(|c_str_buf| check(s, c_str_buf)) + check(s, c_str.as_ptr()); }) } @@ -753,7 +829,7 @@ mod bench { fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) { b.iter(|| { let c_str = unsafe { s.to_c_str_unchecked() }; - c_str.with_ref(|c_str_buf| check(s, c_str_buf)) + check(s, c_str.as_ptr()) }) } diff --git a/src/librustrt/lib.rs b/src/librustrt/lib.rs index f3aacd687e7..fabef24e06a 100644 --- a/src/librustrt/lib.rs +++ b/src/librustrt/lib.rs @@ -18,7 +18,6 @@ #![feature(macro_rules, phase, globs, thread_local, managed_boxes, asm)] #![feature(linkage, lang_items, unsafe_destructor)] -#![allow(unknown_features)] // NOTE: remove after stage0 snapshot #![no_std] #![experimental] @@ -105,7 +104,7 @@ pub static DEFAULT_ERROR_CODE: int = 101; /// Initializes global state, including frobbing /// the crate's logging flags, registering GC /// metadata, and storing the process arguments. -pub fn init(argc: int, argv: **u8) { +pub fn init(argc: int, argv: *const *const u8) { // FIXME: Derefing these pointers is not safe. // Need to propagate the unsafety to `start`. unsafe { diff --git a/src/librustrt/libunwind.rs b/src/librustrt/libunwind.rs index faddadb832d..6811a62c74f 100644 --- a/src/librustrt/libunwind.rs +++ b/src/librustrt/libunwind.rs @@ -82,7 +82,7 @@ pub enum _Unwind_Context {} pub type _Unwind_Exception_Cleanup_Fn = extern "C" fn(unwind_code: _Unwind_Reason_Code, - exception: *_Unwind_Exception); + exception: *mut _Unwind_Exception); #[cfg(target_os = "linux")] #[cfg(target_os = "freebsd")] @@ -99,14 +99,14 @@ extern "C" { // iOS on armv7 uses SjLj exceptions and requires to link // agains corresponding routine (..._SjLj_...) #[cfg(not(target_os = "ios", target_arch = "arm"))] - pub fn _Unwind_RaiseException(exception: *_Unwind_Exception) + pub fn _Unwind_RaiseException(exception: *mut _Unwind_Exception) -> _Unwind_Reason_Code; #[cfg(target_os = "ios", target_arch = "arm")] - fn _Unwind_SjLj_RaiseException(e: *_Unwind_Exception) + fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code; - pub fn _Unwind_DeleteException(exception: *_Unwind_Exception); + pub fn _Unwind_DeleteException(exception: *mut _Unwind_Exception); } // ... and now we just providing access to SjLj counterspart @@ -114,7 +114,7 @@ extern "C" { // (see also comment above regarding _Unwind_RaiseException) #[cfg(target_os = "ios", target_arch = "arm")] #[inline(always)] -pub unsafe fn _Unwind_RaiseException(exc: *_Unwind_Exception) +pub unsafe fn _Unwind_RaiseException(exc: *mut _Unwind_Exception) -> _Unwind_Reason_Code { _Unwind_SjLj_RaiseException(exc) } diff --git a/src/librustrt/local_data.rs b/src/librustrt/local_data.rs index 2e7c3ef37b9..d4c87e9fc05 100644 --- a/src/librustrt/local_data.rs +++ b/src/librustrt/local_data.rs @@ -90,7 +90,7 @@ impl<T: 'static> LocalData for T {} // n.b. If TLS is used heavily in future, this could be made more efficient with // a proper map. #[doc(hidden)] -pub type Map = Vec<Option<(*u8, TLSValue, uint)>>; +pub type Map = Vec<Option<(*const u8, TLSValue, uint)>>; type TLSValue = Box<LocalData + Send>; // Gets the map from the runtime. Lazily initialises if not done so already. @@ -116,8 +116,8 @@ unsafe fn get_local_map() -> Option<&mut Map> { } } -fn key_to_key_value<T: 'static>(key: Key<T>) -> *u8 { - key as *KeyValue<T> as *u8 +fn key_to_key_value<T: 'static>(key: Key<T>) -> *const u8 { + key as *const KeyValue<T> as *const u8 } /// An RAII immutable reference to a task-local value. @@ -236,7 +236,8 @@ impl<T: 'static> KeyValue<T> { // pointer part of the trait, (as ~T), and then use // compiler coercions to achieve a '&' pointer. let ptr = unsafe { - let data = data as *Box<LocalData + Send> as *raw::TraitObject; + let data = data as *const Box<LocalData + Send> + as *const raw::TraitObject; &mut *((*data).data as *mut T) }; Ref { _ptr: ptr, _index: pos, _nosend: marker::NoSend, _key: self } diff --git a/src/librustrt/local_heap.rs b/src/librustrt/local_heap.rs index d95a4ba49de..273505c416a 100644 --- a/src/librustrt/local_heap.rs +++ b/src/librustrt/local_heap.rs @@ -225,8 +225,8 @@ impl MemoryRegion { #[inline] fn malloc(&mut self, size: uint) -> *mut Box { let total_size = size + AllocHeader::size(); - let alloc: *AllocHeader = unsafe { - libc_heap::malloc_raw(total_size) as *AllocHeader + let alloc: *mut AllocHeader = unsafe { + libc_heap::malloc_raw(total_size) as *mut AllocHeader }; let alloc: &mut AllocHeader = unsafe { mem::transmute(alloc) }; @@ -244,14 +244,14 @@ impl MemoryRegion { unsafe { (*orig_alloc).assert_sane(); } let total_size = size + AllocHeader::size(); - let alloc: *AllocHeader = unsafe { - libc_heap::realloc_raw(orig_alloc as *mut u8, total_size) as *AllocHeader + let alloc: *mut AllocHeader = unsafe { + libc_heap::realloc_raw(orig_alloc as *mut u8, total_size) as *mut AllocHeader }; let alloc: &mut AllocHeader = unsafe { mem::transmute(alloc) }; alloc.assert_sane(); alloc.update_size(size as u32); - self.update(alloc, orig_alloc as *AllocHeader); + self.update(alloc, orig_alloc as *mut AllocHeader); return alloc.as_box(); } @@ -273,7 +273,7 @@ impl MemoryRegion { #[inline] fn release(&mut self, _alloc: &AllocHeader) {} #[inline] - fn update(&mut self, _alloc: &mut AllocHeader, _orig: *AllocHeader) {} + fn update(&mut self, _alloc: &mut AllocHeader, _orig: *mut AllocHeader) {} } impl Drop for MemoryRegion { @@ -287,17 +287,19 @@ impl Drop for MemoryRegion { #[cfg(not(test))] #[lang="malloc"] #[inline] -pub unsafe fn local_malloc_(drop_glue: fn(*mut u8), size: uint, align: uint) -> *u8 { +pub unsafe fn local_malloc_(drop_glue: fn(*mut u8), size: uint, + align: uint) -> *mut u8 { local_malloc(drop_glue, size, align) } #[inline] -pub unsafe fn local_malloc(drop_glue: fn(*mut u8), size: uint, align: uint) -> *u8 { +pub unsafe fn local_malloc(drop_glue: fn(*mut u8), size: uint, + align: uint) -> *mut u8 { // FIXME: Unsafe borrow for speed. Lame. let task: Option<*mut Task> = Local::try_unsafe_borrow(); match task { Some(task) => { - (*task).heap.alloc(drop_glue, size, align) as *u8 + (*task).heap.alloc(drop_glue, size, align) as *mut u8 } None => rtabort!("local malloc outside of task") } @@ -306,7 +308,7 @@ pub unsafe fn local_malloc(drop_glue: fn(*mut u8), size: uint, align: uint) -> * #[cfg(not(test))] #[lang="free"] #[inline] -pub unsafe fn local_free_(ptr: *u8) { +pub unsafe fn local_free_(ptr: *mut u8) { local_free(ptr) } @@ -314,7 +316,7 @@ pub unsafe fn local_free_(ptr: *u8) { // inside a landing pad may corrupt the state of the exception handler. If a // problem occurs, call exit instead. #[inline] -pub unsafe fn local_free(ptr: *u8) { +pub unsafe fn local_free(ptr: *mut u8) { // FIXME: Unsafe borrow for speed. Lame. let task_ptr: Option<*mut Task> = Local::try_unsafe_borrow(); match task_ptr { @@ -333,11 +335,11 @@ mod bench { #[bench] fn alloc_managed_small(b: &mut Bencher) { - b.iter(|| { box(GC) 10 }); + b.iter(|| { box(GC) 10i }); } #[bench] fn alloc_managed_big(b: &mut Bencher) { - b.iter(|| { box(GC) ([10, ..1000]) }); + b.iter(|| { box(GC) ([10i, ..1000]) }); } } diff --git a/src/librustrt/local_ptr.rs b/src/librustrt/local_ptr.rs index b6858be32b7..813ea0f30f3 100644 --- a/src/librustrt/local_ptr.rs +++ b/src/librustrt/local_ptr.rs @@ -35,7 +35,7 @@ pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists /// Encapsulates a borrowed value. When this value goes out of scope, the /// pointer is returned. pub struct Borrowed<T> { - val: *(), + val: *const (), } #[unsafe_destructor] @@ -54,7 +54,7 @@ impl<T> Drop for Borrowed<T> { impl<T> Deref<T> for Borrowed<T> { fn deref<'a>(&'a self) -> &'a T { - unsafe { &*(self.val as *T) } + unsafe { &*(self.val as *const T) } } } @@ -72,7 +72,7 @@ impl<T> DerefMut<T> for Borrowed<T> { /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { - let val: *() = mem::transmute(take::<T>()); + let val: *const () = mem::transmute(take::<T>()); Borrowed { val: val, } @@ -172,7 +172,7 @@ pub mod compiled { rtassert!(!ptr.is_null()); let ptr: Box<T> = mem::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` - RT_TLS_PTR = mem::transmute(0); + RT_TLS_PTR = mem::transmute(0u); ptr } @@ -189,7 +189,7 @@ pub mod compiled { } else { let ptr: Box<T> = mem::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` - RT_TLS_PTR = mem::transmute(0); + RT_TLS_PTR = mem::transmute(0u); Some(ptr) } } diff --git a/src/librustrt/mutex.rs b/src/librustrt/mutex.rs index 2bbfcf73917..6950d987d2f 100644 --- a/src/librustrt/mutex.rs +++ b/src/librustrt/mutex.rs @@ -351,8 +351,8 @@ mod imp { mod os { use libc; - pub type pthread_mutex_t = *libc::c_void; - pub type pthread_cond_t = *libc::c_void; + pub type pthread_mutex_t = *mut libc::c_void; + pub type pthread_cond_t = *mut libc::c_void; pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as pthread_mutex_t; diff --git a/src/librustrt/rtio.rs b/src/librustrt/rtio.rs index a68d453b77d..0205f2405f9 100644 --- a/src/librustrt/rtio.rs +++ b/src/librustrt/rtio.rs @@ -269,8 +269,8 @@ pub trait RtioSocket { } pub trait RtioUdpSocket : RtioSocket { - fn recvfrom(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)>; - fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()>; + fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)>; + fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()>; fn join_multicast(&mut self, multi: IpAddr) -> IoResult<()>; fn leave_multicast(&mut self, multi: IpAddr) -> IoResult<()>; diff --git a/src/librustrt/stack.rs b/src/librustrt/stack.rs index 36ddf764d5c..8e637207d22 100644 --- a/src/librustrt/stack.rs +++ b/src/librustrt/stack.rs @@ -221,9 +221,9 @@ pub unsafe fn record_sp_limit(limit: uint) { #[cfg(target_arch = "arm", not(target_os = "ios"))] #[inline(always)] unsafe fn target_record_sp_limit(limit: uint) { use libc::c_void; - return record_sp_limit(limit as *c_void); + return record_sp_limit(limit as *const c_void); extern { - fn record_sp_limit(limit: *c_void); + fn record_sp_limit(limit: *const c_void); } } @@ -305,7 +305,7 @@ pub unsafe fn get_sp_limit() -> uint { use libc::c_void; return get_sp_limit() as uint; extern { - fn get_sp_limit() -> *c_void; + fn get_sp_limit() -> *const c_void; } } diff --git a/src/librustrt/task.rs b/src/librustrt/task.rs index 6e27310f09a..891d0d5a8e3 100644 --- a/src/librustrt/task.rs +++ b/src/librustrt/task.rs @@ -560,7 +560,7 @@ mod test { #[test] fn local_heap() { - let a = box(GC) 5; + let a = box(GC) 5i; let b = a; assert!(*a == 5); assert!(*b == 5); @@ -596,14 +596,14 @@ mod test { #[test] fn comm_stream() { let (tx, rx) = channel(); - tx.send(10); + tx.send(10i); assert!(rx.recv() == 10); } #[test] fn comm_shared_chan() { let (tx, rx) = channel(); - tx.send(10); + tx.send(10i); assert!(rx.recv() == 10); } diff --git a/src/librustrt/thread.rs b/src/librustrt/thread.rs index b385f48f33a..9908e87e86a 100644 --- a/src/librustrt/thread.rs +++ b/src/librustrt/thread.rs @@ -25,7 +25,7 @@ use libc; use stack; -type StartFn = extern "C" fn(*libc::c_void) -> imp::rust_thread_return; +type StartFn = extern "C" fn(*mut libc::c_void) -> imp::rust_thread_return; /// This struct represents a native thread's state. This is used to join on an /// existing thread created in the join-able state. @@ -42,7 +42,7 @@ static DEFAULT_STACK_SIZE: uint = 1024 * 1024; // no_split_stack annotation), and then we extract the main function // and invoke it. #[no_split_stack] -extern fn thread_start(main: *libc::c_void) -> imp::rust_thread_return { +extern fn thread_start(main: *mut libc::c_void) -> imp::rust_thread_return { unsafe { stack::record_stack_bounds(0, uint::MAX); let f: Box<proc()> = mem::transmute(main); @@ -82,7 +82,7 @@ impl Thread<()> { // so. let packet = box None; let packet2: *mut Option<T> = unsafe { - *mem::transmute::<&Box<Option<T>>, **mut Option<T>>(&packet) + *mem::transmute::<&Box<Option<T>>, *const *mut Option<T>>(&packet) }; let main = proc() unsafe { *packet2 = Some(main()); }; let native = unsafe { imp::create(stack, box main) }; @@ -225,7 +225,7 @@ mod imp { use stack::RED_ZONE; pub type rust_thread = libc::pthread_t; - pub type rust_thread_return = *u8; + pub type rust_thread_return = *mut u8; pub unsafe fn create(stack: uint, p: Box<proc():Send>) -> rust_thread { let mut native: libc::pthread_t = mem::zeroed(); @@ -255,7 +255,7 @@ mod imp { }, }; - let arg: *libc::c_void = mem::transmute(p); + let arg: *mut libc::c_void = mem::transmute(p); let ret = pthread_create(&mut native, &attr, super::thread_start, arg); assert_eq!(pthread_attr_destroy(&mut attr), 0); @@ -268,7 +268,7 @@ mod imp { } pub unsafe fn join(native: rust_thread) { - assert_eq!(pthread_join(native, ptr::null()), 0); + assert_eq!(pthread_join(native, ptr::mut_null()), 0); } pub unsafe fn detach(native: rust_thread) { @@ -287,33 +287,33 @@ mod imp { // currently always the case. Note that you need to check that the symbol // is non-null before calling it! #[cfg(target_os = "linux")] - fn min_stack_size(attr: *libc::pthread_attr_t) -> libc::size_t { - type F = unsafe extern "C" fn(*libc::pthread_attr_t) -> libc::size_t; + fn min_stack_size(attr: *const libc::pthread_attr_t) -> libc::size_t { + type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t; extern { #[linkage = "extern_weak"] - static __pthread_get_minstack: *(); + static __pthread_get_minstack: *const (); } if __pthread_get_minstack.is_null() { PTHREAD_STACK_MIN } else { - unsafe { mem::transmute::<*(), F>(__pthread_get_minstack)(attr) } + unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) } } } // __pthread_get_minstack() is marked as weak but extern_weak linkage is // not supported on OS X, hence this kludge... #[cfg(not(target_os = "linux"))] - fn min_stack_size(_: *libc::pthread_attr_t) -> libc::size_t { + fn min_stack_size(_: *const libc::pthread_attr_t) -> libc::size_t { PTHREAD_STACK_MIN } extern { fn pthread_create(native: *mut libc::pthread_t, - attr: *libc::pthread_attr_t, + attr: *const libc::pthread_attr_t, f: super::StartFn, - value: *libc::c_void) -> libc::c_int; + value: *mut libc::c_void) -> libc::c_int; fn pthread_join(native: libc::pthread_t, - value: **libc::c_void) -> libc::c_int; + value: *mut *mut libc::c_void) -> libc::c_int; fn pthread_attr_init(attr: *mut libc::pthread_attr_t) -> libc::c_int; fn pthread_attr_destroy(attr: *mut libc::pthread_attr_t) -> libc::c_int; fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t, diff --git a/src/librustrt/thread_local_storage.rs b/src/librustrt/thread_local_storage.rs index 4a7be39e6b8..3b9ee31d8e5 100644 --- a/src/librustrt/thread_local_storage.rs +++ b/src/librustrt/thread_local_storage.rs @@ -50,7 +50,7 @@ type pthread_key_t = ::libc::c_uint; #[cfg(unix)] extern { - fn pthread_key_create(key: *mut pthread_key_t, dtor: *u8) -> c_int; + fn pthread_key_create(key: *mut pthread_key_t, dtor: *const u8) -> c_int; fn pthread_key_delete(key: pthread_key_t) -> c_int; fn pthread_getspecific(key: pthread_key_t) -> *mut u8; fn pthread_setspecific(key: pthread_key_t, value: *mut u8) -> c_int; @@ -100,15 +100,15 @@ mod test { use std::mem::transmute; unsafe { let mut key = 0; - let value = box 20; + let value = box 20i; create(&mut key); set(key, transmute(value)); let value: Box<int> = transmute(get(key)); - assert_eq!(value, box 20); - let value = box 30; + assert_eq!(value, box 20i); + let value = box 30i; set(key, transmute(value)); let value: Box<int> = transmute(get(key)); - assert_eq!(value, box 30); + assert_eq!(value, box 30i); } } } diff --git a/src/librustrt/unwind.rs b/src/librustrt/unwind.rs index 657d604fcad..18688cbcc64 100644 --- a/src/librustrt/unwind.rs +++ b/src/librustrt/unwind.rs @@ -136,8 +136,8 @@ impl Unwinder { /// run. pub unsafe fn try(f: ||) -> ::core::result::Result<(), Box<Any + Send>> { let closure: Closure = mem::transmute(f); - let ep = rust_try(try_fn, closure.code as *c_void, - closure.env as *c_void); + let ep = rust_try(try_fn, closure.code as *mut c_void, + closure.env as *mut c_void); return if ep.is_null() { Ok(()) } else { @@ -148,11 +148,11 @@ pub unsafe fn try(f: ||) -> ::core::result::Result<(), Box<Any + Send>> { Err(cause.unwrap()) }; - extern fn try_fn(code: *c_void, env: *c_void) { + extern fn try_fn(code: *mut c_void, env: *mut c_void) { unsafe { let closure: || = mem::transmute(Closure { - code: code as *(), - env: env as *(), + code: code as *mut (), + env: env as *mut (), }); closure(); } @@ -164,9 +164,9 @@ pub unsafe fn try(f: ||) -> ::core::result::Result<(), Box<Any + Send>> { // When f(...) returns normally, the return value is null. // When f(...) throws, the return value is a pointer to the caught // exception object. - fn rust_try(f: extern "C" fn(*c_void, *c_void), - code: *c_void, - data: *c_void) -> *uw::_Unwind_Exception; + fn rust_try(f: extern "C" fn(*mut c_void, *mut c_void), + code: *mut c_void, + data: *mut c_void) -> *mut uw::_Unwind_Exception; } } @@ -190,7 +190,7 @@ fn rust_fail(cause: Box<Any + Send>) -> ! { } extern fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code, - exception: *uw::_Unwind_Exception) { + exception: *mut uw::_Unwind_Exception) { rtdebug!("exception_cleanup()"); unsafe { let _: Box<Exception> = mem::transmute(exception); @@ -235,8 +235,8 @@ pub mod eabi { fn __gcc_personality_v0(version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context) + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context) -> uw::_Unwind_Reason_Code; } @@ -245,8 +245,8 @@ pub mod eabi { version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { unsafe { @@ -260,8 +260,8 @@ pub mod eabi { version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase @@ -290,8 +290,8 @@ pub mod eabi { fn __gcc_personality_sj0(version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context) + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context) -> uw::_Unwind_Reason_Code; } @@ -301,8 +301,8 @@ pub mod eabi { version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { unsafe { @@ -316,8 +316,8 @@ pub mod eabi { version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { if (actions as c_int & uw::_UA_SEARCH_PHASE as c_int) != 0 { // search phase @@ -343,16 +343,16 @@ pub mod eabi { extern "C" { fn __gcc_personality_v0(state: uw::_Unwind_State, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context) + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context) -> uw::_Unwind_Reason_Code; } #[lang="eh_personality"] extern "C" fn eh_personality( state: uw::_Unwind_State, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { unsafe { @@ -363,8 +363,8 @@ pub mod eabi { #[no_mangle] // referenced from rust_try.ll pub extern "C" fn rust_eh_personality_catch( state: uw::_Unwind_State, - ue_header: *uw::_Unwind_Exception, - context: *uw::_Unwind_Context + ue_header: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context ) -> uw::_Unwind_Reason_Code { if (state as c_int & uw::_US_ACTION_MASK as c_int) diff --git a/src/librustrt/util.rs b/src/librustrt/util.rs index c08652cc08c..40c3e19576e 100644 --- a/src/librustrt/util.rs +++ b/src/librustrt/util.rs @@ -38,7 +38,7 @@ impl fmt::FormatWriter for Stdio { unsafe { let Stdio(fd) = *self; libc::write(fd, - data.as_ptr() as *libc::c_void, + data.as_ptr() as *const libc::c_void, data.len() as WriteLen); } Ok(()) // yes, we're lying diff --git a/src/librustuv/addrinfo.rs b/src/librustuv/addrinfo.rs index daca3005f12..6eaab1c0961 100644 --- a/src/librustuv/addrinfo.rs +++ b/src/librustuv/addrinfo.rs @@ -11,7 +11,7 @@ use libc::c_int; use libc; use std::mem; -use std::ptr::null; +use std::ptr::{null, mut_null}; use std::rt::task::BlockedTask; use std::rt::rtio; @@ -20,7 +20,7 @@ use super::{Loop, UvError, Request, wait_until_woken_after, wakeup}; use uvll; struct Addrinfo { - handle: *libc::addrinfo, + handle: *const libc::addrinfo, } struct Ctx { @@ -40,7 +40,7 @@ impl GetAddrInfoRequest { let (_c_node, c_node_ptr) = match node { Some(n) => { let c_node = n.to_c_str(); - let c_node_ptr = c_node.with_ref(|r| r); + let c_node_ptr = c_node.as_ptr(); (Some(c_node), c_node_ptr) } None => (None, null()) @@ -49,7 +49,7 @@ impl GetAddrInfoRequest { let (_c_service, c_service_ptr) = match service { Some(s) => { let c_service = s.to_c_str(); - let c_service_ptr = c_service.with_ref(|r| r); + let c_service_ptr = c_service.as_ptr(); (Some(c_service), c_service_ptr) } None => (None, null()) @@ -62,12 +62,14 @@ impl GetAddrInfoRequest { ai_socktype: 0, ai_protocol: 0, ai_addrlen: 0, - ai_canonname: null(), - ai_addr: null(), - ai_next: null(), + ai_canonname: mut_null(), + ai_addr: mut_null(), + ai_next: mut_null(), } }); - let hint_ptr = hint.as_ref().map_or(null(), |x| x as *libc::addrinfo); + let hint_ptr = hint.as_ref().map_or(null(), |x| { + x as *const libc::addrinfo + }); let mut req = Request::new(uvll::UV_GETADDRINFO); return match unsafe { @@ -80,7 +82,7 @@ impl GetAddrInfoRequest { let mut cx = Ctx { slot: None, status: 0, addrinfo: None }; wait_until_woken_after(&mut cx.slot, loop_, || { - req.set_data(&cx); + req.set_data(&mut cx); }); match cx.status { @@ -92,9 +94,9 @@ impl GetAddrInfoRequest { }; - extern fn getaddrinfo_cb(req: *uvll::uv_getaddrinfo_t, + extern fn getaddrinfo_cb(req: *mut uvll::uv_getaddrinfo_t, status: c_int, - res: *libc::addrinfo) { + res: *const libc::addrinfo) { let req = Request::wrap(req); assert!(status != uvll::ECANCELED); let cx: &mut Ctx = unsafe { req.get_data() }; @@ -108,7 +110,7 @@ impl GetAddrInfoRequest { impl Drop for Addrinfo { fn drop(&mut self) { - unsafe { uvll::uv_freeaddrinfo(self.handle) } + unsafe { uvll::uv_freeaddrinfo(self.handle as *mut _) } } } @@ -130,7 +132,7 @@ pub fn accum_addrinfo(addr: &Addrinfo) -> Vec<rtio::AddrinfoInfo> { flags: 0, }); if (*addr).ai_next.is_not_null() { - addr = (*addr).ai_next; + addr = (*addr).ai_next as *const _; } else { break; } diff --git a/src/librustuv/async.rs b/src/librustuv/async.rs index 323bd0fbce2..97f95145b89 100644 --- a/src/librustuv/async.rs +++ b/src/librustuv/async.rs @@ -19,7 +19,7 @@ use super::{Loop, UvHandle}; // The entire point of async is to call into a loop from other threads so it // does not need to home. pub struct AsyncWatcher { - handle: *uvll::uv_async_t, + handle: *mut uvll::uv_async_t, // A flag to tell the callback to exit, set from the dtor. This is // almost never contested - only in rare races with the dtor. @@ -40,7 +40,7 @@ impl AsyncWatcher { let flag = Arc::new(Exclusive::new(false)); let payload = box Payload { callback: cb, exit_flag: flag.clone() }; unsafe { - let payload: *u8 = mem::transmute(payload); + let payload: *mut u8 = mem::transmute(payload); uvll::set_data_for_uv_handle(handle, payload); } return AsyncWatcher { handle: handle, exit_flag: flag, }; @@ -48,13 +48,13 @@ impl AsyncWatcher { } impl UvHandle<uvll::uv_async_t> for AsyncWatcher { - fn uv_handle(&self) -> *uvll::uv_async_t { self.handle } - unsafe fn from_uv_handle<'a>(_: &'a *uvll::uv_async_t) -> &'a mut AsyncWatcher { + fn uv_handle(&self) -> *mut uvll::uv_async_t { self.handle } + unsafe fn from_uv_handle<'a>(_: &'a *mut uvll::uv_async_t) -> &'a mut AsyncWatcher { fail!("async watchers can't be built from their handles"); } } -extern fn async_cb(handle: *uvll::uv_async_t) { +extern fn async_cb(handle: *mut uvll::uv_async_t) { let payload: &mut Payload = unsafe { mem::transmute(uvll::get_data_for_uv_handle(handle)) }; @@ -90,7 +90,7 @@ extern fn async_cb(handle: *uvll::uv_async_t) { } } -extern fn close_cb(handle: *uvll::uv_handle_t) { +extern fn close_cb(handle: *mut uvll::uv_handle_t) { // drop the payload let _payload: Box<Payload> = unsafe { mem::transmute(uvll::get_data_for_uv_handle(handle)) diff --git a/src/librustuv/file.rs b/src/librustuv/file.rs index 4b1343045de..76b2c22e86e 100644 --- a/src/librustuv/file.rs +++ b/src/librustuv/file.rs @@ -24,7 +24,7 @@ use uvio::UvIoFactory; use uvll; pub struct FsRequest { - req: *uvll::uv_fs_t, + req: *mut uvll::uv_fs_t, fired: bool, } @@ -41,7 +41,7 @@ impl FsRequest { { execute(|req, cb| unsafe { uvll::uv_fs_open(io.uv_loop(), - req, path.with_ref(|p| p), flags as c_int, + req, path.as_ptr(), flags as c_int, mode as c_int, cb) }).map(|req| FileWatcher::new(io, req.get_result() as c_int, @@ -51,7 +51,7 @@ impl FsRequest { pub fn unlink(loop_: &Loop, path: &CString) -> Result<(), UvError> { execute_nop(|req, cb| unsafe { - uvll::uv_fs_unlink(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_unlink(loop_.handle, req, path.as_ptr(), cb) }) } @@ -60,14 +60,14 @@ impl FsRequest { -> Result<rtio::FileStat, UvError> { execute(|req, cb| unsafe { - uvll::uv_fs_lstat(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_lstat(loop_.handle, req, path.as_ptr(), cb) }).map(|req| req.mkstat()) } pub fn stat(loop_: &Loop, path: &CString) -> Result<rtio::FileStat, UvError> { execute(|req, cb| unsafe { - uvll::uv_fs_stat(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_stat(loop_.handle, req, path.as_ptr(), cb) }).map(|req| req.mkstat()) } @@ -94,7 +94,7 @@ impl FsRequest { offset + written as i64 }; let uvbuf = uvll::uv_buf_t { - base: buf.slice_from(written as uint).as_ptr(), + base: buf.slice_from(written as uint).as_ptr() as *mut _, len: (buf.len() - written) as uvll::uv_buf_len_t, }; match execute(|req, cb| unsafe { @@ -111,11 +111,11 @@ impl FsRequest { -> Result<int, UvError> { execute(|req, cb| unsafe { - let uvbuf = uvll::uv_buf_t { - base: buf.as_ptr(), + let mut uvbuf = uvll::uv_buf_t { + base: buf.as_mut_ptr(), len: buf.len() as uvll::uv_buf_len_t, }; - uvll::uv_fs_read(loop_.handle, req, fd, &uvbuf, 1, offset, cb) + uvll::uv_fs_read(loop_.handle, req, fd, &mut uvbuf, 1, offset, cb) }).map(|req| { req.get_result() as int }) @@ -125,14 +125,14 @@ impl FsRequest { -> Result<(), UvError> { execute_nop(|req, cb| unsafe { - uvll::uv_fs_mkdir(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_mkdir(loop_.handle, req, path.as_ptr(), mode, cb) }) } pub fn rmdir(loop_: &Loop, path: &CString) -> Result<(), UvError> { execute_nop(|req, cb| unsafe { - uvll::uv_fs_rmdir(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_rmdir(loop_.handle, req, path.as_ptr(), cb) }) } @@ -143,8 +143,8 @@ impl FsRequest { execute_nop(|req, cb| unsafe { uvll::uv_fs_rename(loop_.handle, req, - path.with_ref(|p| p), - to.with_ref(|p| p), + path.as_ptr(), + to.as_ptr(), cb) }) } @@ -153,7 +153,7 @@ impl FsRequest { -> Result<(), UvError> { execute_nop(|req, cb| unsafe { - uvll::uv_fs_chmod(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_chmod(loop_.handle, req, path.as_ptr(), mode, cb) }) } @@ -163,12 +163,12 @@ impl FsRequest { { execute(|req, cb| unsafe { uvll::uv_fs_readdir(loop_.handle, - req, path.with_ref(|p| p), flags, cb) + req, path.as_ptr(), flags, cb) }).map(|req| unsafe { let mut paths = vec!(); - let path = CString::new(path.with_ref(|p| p), false); + let path = CString::new(path.as_ptr(), false); let parent = Path::new(path); - let _ = c_str::from_c_multistring(req.get_ptr() as *libc::c_char, + let _ = c_str::from_c_multistring(req.get_ptr() as *const libc::c_char, Some(req.get_result() as uint), |rel| { let p = rel.as_bytes(); @@ -181,12 +181,12 @@ impl FsRequest { pub fn readlink(loop_: &Loop, path: &CString) -> Result<CString, UvError> { execute(|req, cb| unsafe { uvll::uv_fs_readlink(loop_.handle, req, - path.with_ref(|p| p), cb) + path.as_ptr(), cb) }).map(|req| { // Be sure to clone the cstring so we get an independently owned // allocation to work with and return. unsafe { - CString::new(req.get_ptr() as *libc::c_char, false).clone() + CString::new(req.get_ptr() as *const libc::c_char, false).clone() } }) } @@ -196,7 +196,7 @@ impl FsRequest { { execute_nop(|req, cb| unsafe { uvll::uv_fs_chown(loop_.handle, - req, path.with_ref(|p| p), + req, path.as_ptr(), uid as uvll::uv_uid_t, gid as uvll::uv_gid_t, cb) @@ -216,8 +216,8 @@ impl FsRequest { { execute_nop(|req, cb| unsafe { uvll::uv_fs_link(loop_.handle, req, - src.with_ref(|p| p), - dst.with_ref(|p| p), + src.as_ptr(), + dst.as_ptr(), cb) }) } @@ -227,8 +227,8 @@ impl FsRequest { { execute_nop(|req, cb| unsafe { uvll::uv_fs_symlink(loop_.handle, req, - src.with_ref(|p| p), - dst.with_ref(|p| p), + src.as_ptr(), + dst.as_ptr(), 0, cb) }) } @@ -252,7 +252,7 @@ impl FsRequest { let atime = atime as libc::c_double / 1000.0; let mtime = mtime as libc::c_double / 1000.0; execute_nop(|req, cb| unsafe { - uvll::uv_fs_utime(loop_.handle, req, path.with_ref(|p| p), + uvll::uv_fs_utime(loop_.handle, req, path.as_ptr(), atime, mtime, cb) }) } @@ -262,12 +262,12 @@ impl FsRequest { } pub fn get_stat(&self) -> uvll::uv_stat_t { - let stat = uvll::uv_stat_t::new(); - unsafe { uvll::populate_stat(self.req, &stat); } + let mut stat = uvll::uv_stat_t::new(); + unsafe { uvll::populate_stat(self.req, &mut stat); } stat } - pub fn get_ptr(&self) -> *libc::c_void { + pub fn get_ptr(&self) -> *mut libc::c_void { unsafe { uvll::get_ptr_from_fs_req(self.req) } } @@ -310,7 +310,7 @@ impl Drop for FsRequest { } } -fn execute(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) +fn execute(f: |*mut uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) -> Result<FsRequest, UvError> { let mut req = FsRequest { @@ -323,7 +323,7 @@ fn execute(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) let mut slot = None; let loop_ = unsafe { uvll::get_loop_from_fs_req(req.req) }; wait_until_woken_after(&mut slot, &Loop::wrap(loop_), || { - unsafe { uvll::set_data_for_req(req.req, &slot) } + unsafe { uvll::set_data_for_req(req.req, &mut slot) } }); match req.get_result() { n if n < 0 => Err(UvError(n as i32)), @@ -333,7 +333,7 @@ fn execute(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) n => Err(UvError(n)) }; - extern fn fs_cb(req: *uvll::uv_fs_t) { + extern fn fs_cb(req: *mut uvll::uv_fs_t) { let slot: &mut Option<BlockedTask> = unsafe { mem::transmute(uvll::get_data_for_req(req)) }; @@ -341,7 +341,7 @@ fn execute(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) } } -fn execute_nop(f: |*uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) +fn execute_nop(f: |*mut uvll::uv_fs_t, uvll::uv_fs_cb| -> c_int) -> Result<(), UvError> { execute(f).map(|_| {}) } @@ -397,7 +397,7 @@ impl Drop for FileWatcher { self.fd, close_cb), 0); } - extern fn close_cb(req: *uvll::uv_fs_t) { + extern fn close_cb(req: *mut uvll::uv_fs_t) { unsafe { uvll::uv_fs_req_cleanup(req); uvll::free_req(req); diff --git a/src/librustuv/homing.rs b/src/librustuv/homing.rs index 644ac4e45f6..91614763ce5 100644 --- a/src/librustuv/homing.rs +++ b/src/librustuv/homing.rs @@ -197,13 +197,13 @@ mod test { let listener = UdpWatcher::bind(local_loop(), addr2); tx.send((listener.unwrap(), addr1)); let mut listener = UdpWatcher::bind(local_loop(), addr1).unwrap(); - listener.sendto([1, 2, 3, 4], addr2).ok().unwrap(); + listener.send_to([1, 2, 3, 4], addr2).ok().unwrap(); }); let task = pool.task(TaskOpts::new(), proc() { let (mut watcher, addr) = rx.recv(); let mut buf = [0, ..10]; - assert!(watcher.recvfrom(buf).ok().unwrap() == (4, addr)); + assert!(watcher.recv_from(buf).ok().unwrap() == (4, addr)); }); pool.spawn_sched().send(sched::TaskFromFriend(task)); diff --git a/src/librustuv/idle.rs b/src/librustuv/idle.rs index 43ddd2681b3..7b9a2fcf444 100644 --- a/src/librustuv/idle.rs +++ b/src/librustuv/idle.rs @@ -16,7 +16,7 @@ use super::{Loop, UvHandle}; use std::rt::rtio::{Callback, PausableIdleCallback}; pub struct IdleWatcher { - handle: *uvll::uv_idle_t, + handle: *mut uvll::uv_idle_t, idle_flag: bool, callback: Box<Callback + Send>, } @@ -39,12 +39,12 @@ impl IdleWatcher { let handle = UvHandle::alloc(None::<IdleWatcher>, uvll::UV_IDLE); unsafe { assert_eq!(uvll::uv_idle_init(loop_.handle, handle), 0); - let data: *c_void = mem::transmute(box f); + let data: *mut c_void = mem::transmute(box f); uvll::set_data_for_uv_handle(handle, data); assert_eq!(uvll::uv_idle_start(handle, onetime_cb), 0) } - extern fn onetime_cb(handle: *uvll::uv_idle_t) { + extern fn onetime_cb(handle: *mut uvll::uv_idle_t) { unsafe { let data = uvll::get_data_for_uv_handle(handle); let f: Box<proc()> = mem::transmute(data); @@ -54,7 +54,7 @@ impl IdleWatcher { } } - extern fn close_cb(handle: *uvll::uv_handle_t) { + extern fn close_cb(handle: *mut uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } } @@ -76,10 +76,10 @@ impl PausableIdleCallback for IdleWatcher { } impl UvHandle<uvll::uv_idle_t> for IdleWatcher { - fn uv_handle(&self) -> *uvll::uv_idle_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_idle_t { self.handle } } -extern fn idle_cb(handle: *uvll::uv_idle_t) { +extern fn idle_cb(handle: *mut uvll::uv_idle_t) { let idle: &mut IdleWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; idle.callback.call(); } diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index 65a311fcf5d..4afcc9078ab 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -57,7 +57,6 @@ extern crate alloc; use libc::{c_int, c_void}; use std::fmt; use std::mem; -use std::ptr::null; use std::ptr; use std::rt::local::Local; use std::rt::rtio; @@ -82,7 +81,7 @@ pub use self::tty::TtyWatcher; // threading mode than the default by reaching into the auto-generated // '__test' module. #[cfg(test)] #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, event_loop, __test::main) } @@ -122,7 +121,7 @@ pub mod stream; /// extern crate green; /// /// #[start] -/// fn start(argc: int, argv: **u8) -> int { +/// fn start(argc: int, argv: *const *const u8) -> int { /// green::start(argc, argv, rustuv::event_loop, main) /// } /// @@ -136,28 +135,28 @@ pub fn event_loop() -> Box<rtio::EventLoop + Send> { /// A type that wraps a uv handle pub trait UvHandle<T> { - fn uv_handle(&self) -> *T; + fn uv_handle(&self) -> *mut T; fn uv_loop(&self) -> Loop { Loop::wrap(unsafe { uvll::get_loop_for_uv_handle(self.uv_handle()) }) } // FIXME(#8888) dummy self - fn alloc(_: Option<Self>, ty: uvll::uv_handle_type) -> *T { + fn alloc(_: Option<Self>, ty: uvll::uv_handle_type) -> *mut T { unsafe { let handle = uvll::malloc_handle(ty); assert!(!handle.is_null()); - handle as *T + handle as *mut T } } - unsafe fn from_uv_handle<'a>(h: &'a *T) -> &'a mut Self { + unsafe fn from_uv_handle<'a>(h: &'a *mut T) -> &'a mut Self { mem::transmute(uvll::get_data_for_uv_handle(*h)) } fn install(~self) -> Box<Self> { unsafe { - let myptr = mem::transmute::<&Box<Self>, &*u8>(&self); + let myptr = mem::transmute::<&Box<Self>, &*mut u8>(&self); uvll::set_data_for_uv_handle(self.uv_handle(), *myptr); } self @@ -166,13 +165,13 @@ pub trait UvHandle<T> { fn close_async_(&mut self) { // we used malloc to allocate all handles, so we must always have at // least a callback to free all the handles we allocated. - extern fn close_cb(handle: *uvll::uv_handle_t) { + extern fn close_cb(handle: *mut uvll::uv_handle_t) { unsafe { uvll::free_handle(handle) } } unsafe { - uvll::set_data_for_uv_handle(self.uv_handle(), null::<()>()); - uvll::uv_close(self.uv_handle() as *uvll::uv_handle_t, close_cb) + uvll::set_data_for_uv_handle(self.uv_handle(), ptr::mut_null::<()>()); + uvll::uv_close(self.uv_handle() as *mut uvll::uv_handle_t, close_cb) } } @@ -180,19 +179,20 @@ pub trait UvHandle<T> { let mut slot = None; unsafe { - uvll::uv_close(self.uv_handle() as *uvll::uv_handle_t, close_cb); - uvll::set_data_for_uv_handle(self.uv_handle(), ptr::null::<()>()); + uvll::uv_close(self.uv_handle() as *mut uvll::uv_handle_t, close_cb); + uvll::set_data_for_uv_handle(self.uv_handle(), + ptr::mut_null::<()>()); wait_until_woken_after(&mut slot, &self.uv_loop(), || { - uvll::set_data_for_uv_handle(self.uv_handle(), &slot); + uvll::set_data_for_uv_handle(self.uv_handle(), &mut slot); }) } - extern fn close_cb(handle: *uvll::uv_handle_t) { + extern fn close_cb(handle: *mut uvll::uv_handle_t) { unsafe { let data = uvll::get_data_for_uv_handle(handle); uvll::free_handle(handle); - if data == ptr::null() { return } + if data == ptr::mut_null() { return } let slot: &mut Option<BlockedTask> = mem::transmute(data); wakeup(slot); } @@ -265,7 +265,7 @@ fn wakeup(slot: &mut Option<BlockedTask>) { } pub struct Request { - pub handle: *uvll::uv_req_t, + pub handle: *mut uvll::uv_req_t, defused: bool, } @@ -273,22 +273,22 @@ impl Request { pub fn new(ty: uvll::uv_req_type) -> Request { unsafe { let handle = uvll::malloc_req(ty); - uvll::set_data_for_req(handle, null::<()>()); + uvll::set_data_for_req(handle, ptr::mut_null::<()>()); Request::wrap(handle) } } - pub fn wrap(handle: *uvll::uv_req_t) -> Request { + pub fn wrap(handle: *mut uvll::uv_req_t) -> Request { Request { handle: handle, defused: false } } - pub fn set_data<T>(&self, t: *T) { + pub fn set_data<T>(&self, t: *mut T) { unsafe { uvll::set_data_for_req(self.handle, t) } } pub unsafe fn get_data<T>(&self) -> &'static mut T { let data = uvll::get_data_for_req(self.handle); - assert!(data != null()); + assert!(data != ptr::mut_null()); mem::transmute(data) } @@ -317,18 +317,18 @@ impl Drop for Request { /// with dtors may not be destructured, but tuple structs can, /// but the results are not correct. pub struct Loop { - handle: *uvll::uv_loop_t + handle: *mut uvll::uv_loop_t } impl Loop { pub fn new() -> Loop { let handle = unsafe { uvll::loop_new() }; assert!(handle.is_not_null()); - unsafe { uvll::set_data_for_uv_loop(handle, 0 as *c_void) } + unsafe { uvll::set_data_for_uv_loop(handle, 0 as *mut c_void) } Loop::wrap(handle) } - pub fn wrap(handle: *uvll::uv_loop_t) -> Loop { Loop { handle: handle } } + pub fn wrap(handle: *mut uvll::uv_loop_t) -> Loop { Loop { handle: handle } } pub fn run(&mut self) { assert_eq!(unsafe { uvll::uv_run(self.handle, uvll::RUN_DEFAULT) }, 0); @@ -343,7 +343,7 @@ impl Loop { fn modify_blockers(&self, amt: uint) { unsafe { let cur = uvll::get_data_for_uv_loop(self.handle) as uint; - uvll::set_data_for_uv_loop(self.handle, (cur + amt) as *c_void) + uvll::set_data_for_uv_loop(self.handle, (cur + amt) as *mut c_void) } } @@ -449,7 +449,7 @@ pub type Buf = uvll::uv_buf_t; pub fn empty_buf() -> Buf { uvll::uv_buf_t { - base: null(), + base: ptr::mut_null(), len: 0, } } @@ -457,7 +457,7 @@ pub fn empty_buf() -> Buf { /// Borrow a slice to a Buf pub fn slice_to_uv_buf(v: &[u8]) -> Buf { let data = v.as_ptr(); - uvll::uv_buf_t { base: data, len: v.len() as uvll::uv_buf_len_t } + uvll::uv_buf_t { base: data as *mut u8, len: v.len() as uvll::uv_buf_len_t } } // This function is full of lies! @@ -516,7 +516,7 @@ mod test { assert_eq!(buf.len, 20); unsafe { - let base = transmute::<*u8, *mut u8>(buf.base); + let base = transmute::<*mut u8, *mut u8>(buf.base); (*base) = 1; (*base.offset(1)) = 2; } diff --git a/src/librustuv/net.rs b/src/librustuv/net.rs index 82693acb1e9..ddcaeccbc19 100644 --- a/src/librustuv/net.rs +++ b/src/librustuv/net.rs @@ -125,7 +125,7 @@ enum SocketNameKind { } fn socket_name(sk: SocketNameKind, - handle: *c_void) -> Result<rtio::SocketAddr, IoError> { + handle: *mut c_void) -> Result<rtio::SocketAddr, IoError> { let getsockname = match sk { TcpPeer => uvll::uv_tcp_getpeername, Tcp => uvll::uv_tcp_getsockname, @@ -150,7 +150,7 @@ fn socket_name(sk: SocketNameKind, //////////////////////////////////////////////////////////////////////////////// pub struct TcpWatcher { - handle: *uvll::uv_tcp_t, + handle: *mut uvll::uv_tcp_t, stream: StreamWatcher, home: HomeHandle, refcount: Refcount, @@ -165,7 +165,7 @@ pub struct TcpWatcher { pub struct TcpListener { home: HomeHandle, - handle: *uvll::uv_pipe_t, + handle: *mut uvll::uv_pipe_t, outgoing: Sender<Result<Box<rtio::RtioTcpStream + Send>, IoError>>, incoming: Receiver<Result<Box<rtio::RtioTcpStream + Send>, IoError>>, } @@ -191,7 +191,7 @@ impl TcpWatcher { TcpWatcher { home: home, handle: handle, - stream: StreamWatcher::new(handle), + stream: StreamWatcher::new(handle, true), refcount: Refcount::new(), read_access: AccessTimeout::new(), write_access: AccessTimeout::new(), @@ -204,7 +204,7 @@ impl TcpWatcher { let tcp = TcpWatcher::new(io); let cx = ConnectCtx { status: -1, task: None, timer: None }; let (addr, _len) = addr_to_sockaddr(address); - let addr_p = &addr as *_ as *libc::sockaddr; + let addr_p = &addr as *const _ as *const libc::sockaddr; cx.connect(tcp, timeout, io, |req, tcp, cb| { unsafe { uvll::uv_tcp_connect(req.handle, tcp.handle, addr_p, cb) } }) @@ -278,7 +278,7 @@ impl rtio::RtioTcpStream for TcpWatcher { fn clone(&self) -> Box<rtio::RtioTcpStream + Send> { box TcpWatcher { handle: self.handle, - stream: StreamWatcher::new(self.handle), + stream: StreamWatcher::new(self.handle, false), home: self.home.clone(), refcount: self.refcount.clone(), read_access: self.read_access.clone(), @@ -311,7 +311,7 @@ impl rtio::RtioTcpStream for TcpWatcher { let _m = self.fire_homing_missile(); let loop_ = self.uv_loop(); self.read_access.set_timeout(ms, &self.home, &loop_, cancel_read, - &self.stream as *_ as uint); + &self.stream as *const _ as uint); fn cancel_read(stream: uint) -> Option<BlockedTask> { let stream: &mut StreamWatcher = unsafe { mem::transmute(stream) }; @@ -323,7 +323,7 @@ impl rtio::RtioTcpStream for TcpWatcher { let _m = self.fire_homing_missile(); let loop_ = self.uv_loop(); self.write_access.set_timeout(ms, &self.home, &loop_, cancel_write, - &self.stream as *_ as uint); + &self.stream as *const _ as uint); fn cancel_write(stream: uint) -> Option<BlockedTask> { let stream: &mut StreamWatcher = unsafe { mem::transmute(stream) }; @@ -333,7 +333,7 @@ impl rtio::RtioTcpStream for TcpWatcher { } impl UvHandle<uvll::uv_tcp_t> for TcpWatcher { - fn uv_handle(&self) -> *uvll::uv_tcp_t { self.stream.handle } + fn uv_handle(&self) -> *mut uvll::uv_tcp_t { self.stream.handle } } impl Drop for TcpWatcher { @@ -363,8 +363,8 @@ impl TcpListener { }; let (addr, _len) = addr_to_sockaddr(address); let res = unsafe { - let addr_p = &addr as *libc::sockaddr_storage; - uvll::uv_tcp_bind(l.handle, addr_p as *libc::sockaddr) + let addr_p = &addr as *const libc::sockaddr_storage; + uvll::uv_tcp_bind(l.handle, addr_p as *const libc::sockaddr) }; return match res { 0 => Ok(l.install()), @@ -378,7 +378,7 @@ impl HomingIO for TcpListener { } impl UvHandle<uvll::uv_tcp_t> for TcpListener { - fn uv_handle(&self) -> *uvll::uv_tcp_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_tcp_t { self.handle } } impl rtio::RtioSocket for TcpListener { @@ -405,7 +405,7 @@ impl rtio::RtioTcpListener for TcpListener { } } -extern fn listen_cb(server: *uvll::uv_stream_t, status: c_int) { +extern fn listen_cb(server: *mut uvll::uv_stream_t, status: c_int) { assert!(status != uvll::ECANCELED); let tcp: &mut TcpListener = unsafe { UvHandle::from_uv_handle(&server) }; let msg = match status { @@ -475,7 +475,7 @@ impl rtio::RtioTcpAcceptor for TcpAcceptor { //////////////////////////////////////////////////////////////////////////////// pub struct UdpWatcher { - handle: *uvll::uv_udp_t, + handle: *mut uvll::uv_udp_t, home: HomeHandle, // See above for what these fields are @@ -514,8 +514,8 @@ impl UdpWatcher { }, 0); let (addr, _len) = addr_to_sockaddr(address); let result = unsafe { - let addr_p = &addr as *libc::sockaddr_storage; - uvll::uv_udp_bind(udp.handle, addr_p as *libc::sockaddr, 0u32) + let addr_p = &addr as *const libc::sockaddr_storage; + uvll::uv_udp_bind(udp.handle, addr_p as *const libc::sockaddr, 0u32) }; return match result { 0 => Ok(udp), @@ -525,7 +525,7 @@ impl UdpWatcher { } impl UvHandle<uvll::uv_udp_t> for UdpWatcher { - fn uv_handle(&self) -> *uvll::uv_udp_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_udp_t { self.handle } } impl HomingIO for UdpWatcher { @@ -540,7 +540,7 @@ impl rtio::RtioSocket for UdpWatcher { } impl rtio::RtioUdpSocket for UdpWatcher { - fn recvfrom(&mut self, buf: &mut [u8]) + fn recv_from(&mut self, buf: &mut [u8]) -> Result<(uint, rtio::SocketAddr), IoError> { let loop_ = self.uv_loop(); @@ -558,7 +558,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { }; let handle = self.handle; wait_until_woken_after(&mut cx.task, &loop_, || { - unsafe { uvll::set_data_for_uv_handle(handle, &cx) } + unsafe { uvll::set_data_for_uv_handle(handle, &mut cx) } }); match cx.result.take_unwrap() { (n, _) if n < 0 => @@ -569,7 +569,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { n => Err(uv_error_to_io_error(UvError(n))) }; - extern fn alloc_cb(handle: *uvll::uv_udp_t, + extern fn alloc_cb(handle: *mut uvll::uv_udp_t, _suggested_size: size_t, buf: *mut Buf) { unsafe { @@ -579,8 +579,9 @@ impl rtio::RtioUdpSocket for UdpWatcher { } } - extern fn recv_cb(handle: *uvll::uv_udp_t, nread: ssize_t, buf: *Buf, - addr: *libc::sockaddr, _flags: c_uint) { + extern fn recv_cb(handle: *mut uvll::uv_udp_t, nread: ssize_t, + buf: *const Buf, + addr: *const libc::sockaddr, _flags: c_uint) { assert!(nread != uvll::ECANCELED as ssize_t); let cx = unsafe { &mut *(uvll::get_data_for_uv_handle(handle) as *mut UdpRecvCtx) @@ -606,14 +607,14 @@ impl rtio::RtioUdpSocket for UdpWatcher { } } - fn sendto(&mut self, buf: &[u8], dst: rtio::SocketAddr) -> Result<(), IoError> { + fn send_to(&mut self, buf: &[u8], dst: rtio::SocketAddr) -> Result<(), IoError> { let m = self.fire_homing_missile(); let loop_ = self.uv_loop(); let guard = try!(self.write_access.grant(m)); let mut req = Request::new(uvll::UV_UDP_SEND); let (addr, _len) = addr_to_sockaddr(dst); - let addr_p = &addr as *_ as *libc::sockaddr; + let addr_p = &addr as *const _ as *const libc::sockaddr; // see comments in StreamWatcher::write for why we may allocate a buffer // here. @@ -633,7 +634,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { result: uvll::ECANCELED, data: data, udp: self as *mut _ }; wait_until_woken_after(&mut self.blocked_sender, &loop_, || { - req.set_data(&cx); + req.set_data(&mut cx); }); if cx.result != uvll::ECANCELED { @@ -642,13 +643,13 @@ impl rtio::RtioUdpSocket for UdpWatcher { n => Err(uv_error_to_io_error(UvError(n))) } } - let new_cx = box UdpSendCtx { + let mut new_cx = box UdpSendCtx { result: 0, udp: 0 as *mut UdpWatcher, data: cx.data.take(), }; unsafe { - req.set_data(&*new_cx); + req.set_data(&mut *new_cx); mem::forget(new_cx); } Err(uv_error_to_io_error(UvError(cx.result))) @@ -658,7 +659,7 @@ impl rtio::RtioUdpSocket for UdpWatcher { // This function is the same as stream::write_cb, but adapted for udp // instead of streams. - extern fn send_cb(req: *uvll::uv_udp_send_t, status: c_int) { + extern fn send_cb(req: *mut uvll::uv_udp_send_t, status: c_int) { let req = Request::wrap(req); let cx: &mut UdpSendCtx = unsafe { req.get_data() }; cx.result = status; @@ -766,12 +767,12 @@ impl rtio::RtioUdpSocket for UdpWatcher { fn cancel_read(stream: uint) -> Option<BlockedTask> { // This method is quite similar to StreamWatcher::cancel_read, see // there for more information - let handle = stream as *uvll::uv_udp_t; + let handle = stream as *mut uvll::uv_udp_t; assert_eq!(unsafe { uvll::uv_udp_recv_stop(handle) }, 0); let data = unsafe { let data = uvll::get_data_for_uv_handle(handle); if data.is_null() { return None } - uvll::set_data_for_uv_handle(handle, 0 as *int); + uvll::set_data_for_uv_handle(handle, 0 as *mut int); &mut *(data as *mut UdpRecvCtx) }; data.result = Some((uvll::ECANCELED as ssize_t, None)); @@ -806,7 +807,7 @@ impl Drop for UdpWatcher { // Shutdown helper //////////////////////////////////////////////////////////////////////////////// -pub fn shutdown(handle: *uvll::uv_stream_t, loop_: &Loop) -> Result<(), IoError> { +pub fn shutdown(handle: *mut uvll::uv_stream_t, loop_: &Loop) -> Result<(), IoError> { struct Ctx { slot: Option<BlockedTask>, status: c_int, @@ -819,7 +820,7 @@ pub fn shutdown(handle: *uvll::uv_stream_t, loop_: &Loop) -> Result<(), IoError> let mut cx = Ctx { slot: None, status: 0 }; wait_until_woken_after(&mut cx.slot, loop_, || { - req.set_data(&cx); + req.set_data(&mut cx); }); status_to_io_result(cx.status) @@ -827,7 +828,7 @@ pub fn shutdown(handle: *uvll::uv_stream_t, loop_: &Loop) -> Result<(), IoError> n => Err(uv_error_to_io_error(UvError(n))) }; - extern fn shutdown_cb(req: *uvll::uv_shutdown_t, status: libc::c_int) { + extern fn shutdown_cb(req: *mut uvll::uv_shutdown_t, status: libc::c_int) { let req = Request::wrap(req); assert!(status != uvll::ECANCELED); let cx: &mut Ctx = unsafe { req.get_data() }; @@ -959,7 +960,7 @@ mod test { Ok(mut w) => { tx.send(()); let mut buf = [0u8, ..10]; - match w.recvfrom(buf) { + match w.recv_from(buf) { Ok((10, addr)) => assert!(addr == client), e => fail!("{:?}", e), } @@ -975,7 +976,7 @@ mod test { let mut w = match UdpWatcher::bind(local_loop(), client) { Ok(w) => w, Err(e) => fail!("{:?}", e) }; - match w.sendto([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], server) { + match w.send_to([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], server) { Ok(()) => {}, Err(e) => fail!("{:?}", e) } } @@ -991,7 +992,7 @@ mod test { Ok(mut w) => { tx.send(()); let mut buf = [0u8, ..10]; - match w.recvfrom(buf) { + match w.recv_from(buf) { Ok((10, addr)) => assert!(addr == client), e => fail!("{:?}", e), } @@ -1007,7 +1008,7 @@ mod test { let mut w = match UdpWatcher::bind(local_loop(), client) { Ok(w) => w, Err(e) => fail!("{:?}", e) }; - match w.sendto([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], server) { + match w.send_to([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], server) { Ok(()) => {}, Err(e) => fail!("{:?}", e) } } @@ -1056,16 +1057,16 @@ mod test { spawn(proc() { let mut client = UdpWatcher::bind(local_loop(), client_addr).unwrap(); rx.recv(); - assert!(client.sendto([1], server_addr).is_ok()); - assert!(client.sendto([2], server_addr).is_ok()); + assert!(client.send_to([1], server_addr).is_ok()); + assert!(client.send_to([2], server_addr).is_ok()); }); let mut server = UdpWatcher::bind(local_loop(), server_addr).unwrap(); tx.send(()); let mut buf1 = [0]; let mut buf2 = [0]; - let (nread1, src1) = server.recvfrom(buf1).ok().unwrap(); - let (nread2, src2) = server.recvfrom(buf2).ok().unwrap(); + let (nread1, src1) = server.recv_from(buf1).ok().unwrap(); + let (nread2, src2) = server.recv_from(buf2).ok().unwrap(); assert_eq!(nread1, 1); assert_eq!(nread2, 1); assert!(src1 == client_addr); @@ -1097,10 +1098,10 @@ mod test { let mut buf = [1]; while buf[0] == 1 { // send more data - assert!(server_out.sendto(msg, client_in_addr).is_ok()); + assert!(server_out.send_to(msg, client_in_addr).is_ok()); total_bytes_sent += msg.len(); // check if the client has received enough - let res = server_in.recvfrom(buf); + let res = server_in.recv_from(buf); assert!(res.is_ok()); let (nread, src) = res.ok().unwrap(); assert_eq!(nread, 1); @@ -1119,9 +1120,9 @@ mod test { let mut buf = [0, .. 2048]; while total_bytes_recv < MAX { // ask for more - assert!(client_out.sendto([1], server_in_addr).is_ok()); + assert!(client_out.send_to([1], server_in_addr).is_ok()); // wait for data - let res = client_in.recvfrom(buf); + let res = client_in.recv_from(buf); assert!(res.is_ok()); let (nread, src) = res.ok().unwrap(); assert!(src == server_out_addr); @@ -1131,7 +1132,7 @@ mod test { } } // tell the server we're done - assert!(client_out.sendto([0], server_in_addr).is_ok()); + assert!(client_out.send_to([0], server_in_addr).is_ok()); } #[test] @@ -1159,7 +1160,7 @@ mod test { let expected = 32; let mut current = 0; - let mut reads = 0; + let mut reads = 0u; while current < expected { let nread = stream.read(buf).ok().unwrap(); diff --git a/src/librustuv/pipe.rs b/src/librustuv/pipe.rs index 2ac9bfd202b..1c53814ac24 100644 --- a/src/librustuv/pipe.rs +++ b/src/librustuv/pipe.rs @@ -37,7 +37,7 @@ pub struct PipeWatcher { pub struct PipeListener { home: HomeHandle, - pipe: *uvll::uv_pipe_t, + pipe: *mut uvll::uv_pipe_t, outgoing: Sender<IoResult<Box<rtio::RtioPipe + Send>>>, incoming: Receiver<IoResult<Box<rtio::RtioPipe + Send>>>, } @@ -67,7 +67,7 @@ impl PipeWatcher { handle }; PipeWatcher { - stream: StreamWatcher::new(handle), + stream: StreamWatcher::new(handle, true), home: home, defused: false, refcount: Refcount::new(), @@ -94,17 +94,17 @@ impl PipeWatcher { cx.connect(pipe, timeout, io, |req, pipe, cb| { unsafe { uvll::uv_pipe_connect(req.handle, pipe.handle(), - name.with_ref(|p| p), cb) + name.as_ptr(), cb) } 0 }) } - pub fn handle(&self) -> *uvll::uv_pipe_t { self.stream.handle } + pub fn handle(&self) -> *mut uvll::uv_pipe_t { self.stream.handle } // Unwraps the underlying uv pipe. This cancels destruction of the pipe and // allows the pipe to get moved elsewhere - fn unwrap(mut self) -> *uvll::uv_pipe_t { + fn unwrap(mut self) -> *mut uvll::uv_pipe_t { self.defused = true; return self.stream.handle; } @@ -131,7 +131,7 @@ impl rtio::RtioPipe for PipeWatcher { fn clone(&self) -> Box<rtio::RtioPipe + Send> { box PipeWatcher { - stream: StreamWatcher::new(self.stream.handle), + stream: StreamWatcher::new(self.stream.handle, false), defused: false, home: self.home.clone(), refcount: self.refcount.clone(), @@ -181,7 +181,7 @@ impl rtio::RtioPipe for PipeWatcher { let _m = self.fire_homing_missile(); let loop_ = self.uv_loop(); self.read_access.set_timeout(ms, &self.home, &loop_, cancel_read, - &self.stream as *_ as uint); + &self.stream as *const _ as uint); fn cancel_read(stream: uint) -> Option<BlockedTask> { let stream: &mut StreamWatcher = unsafe { mem::transmute(stream) }; @@ -193,7 +193,7 @@ impl rtio::RtioPipe for PipeWatcher { let _m = self.fire_homing_missile(); let loop_ = self.uv_loop(); self.write_access.set_timeout(ms, &self.home, &loop_, cancel_write, - &self.stream as *_ as uint); + &self.stream as *const _ as uint); fn cancel_write(stream: uint) -> Option<BlockedTask> { let stream: &mut StreamWatcher = unsafe { mem::transmute(stream) }; @@ -207,7 +207,7 @@ impl HomingIO for PipeWatcher { } impl UvHandle<uvll::uv_pipe_t> for PipeWatcher { - fn uv_handle(&self) -> *uvll::uv_pipe_t { self.stream.handle } + fn uv_handle(&self) -> *mut uvll::uv_pipe_t { self.stream.handle } } impl Drop for PipeWatcher { @@ -227,7 +227,7 @@ impl PipeListener { { let pipe = PipeWatcher::new(io, false); match unsafe { - uvll::uv_pipe_bind(pipe.handle(), name.with_ref(|p| p)) + uvll::uv_pipe_bind(pipe.handle(), name.as_ptr()) } { 0 => { // If successful, unwrap the PipeWatcher because we control how @@ -269,10 +269,10 @@ impl HomingIO for PipeListener { } impl UvHandle<uvll::uv_pipe_t> for PipeListener { - fn uv_handle(&self) -> *uvll::uv_pipe_t { self.pipe } + fn uv_handle(&self) -> *mut uvll::uv_pipe_t { self.pipe } } -extern fn listen_cb(server: *uvll::uv_stream_t, status: libc::c_int) { +extern fn listen_cb(server: *mut uvll::uv_stream_t, status: libc::c_int) { assert!(status != uvll::ECANCELED); let pipe: &mut PipeListener = unsafe { UvHandle::from_uv_handle(&server) }; diff --git a/src/librustuv/process.rs b/src/librustuv/process.rs index aa87582da26..61325d0ce94 100644 --- a/src/librustuv/process.rs +++ b/src/librustuv/process.rs @@ -25,7 +25,7 @@ use uvio::UvIoFactory; use uvll; pub struct Process { - handle: *uvll::uv_process_t, + handle: *mut uvll::uv_process_t, home: HomeHandle, /// Task to wake up (may be null) for when the process exits @@ -60,8 +60,8 @@ impl Process { let mut ret_io = Vec::with_capacity(io.len()); unsafe { stdio.set_len(io.len()); - for (slot, other) in stdio.iter().zip(io.iter()) { - let io = set_stdio(slot as *uvll::uv_stdio_container_t, other, + for (slot, other) in stdio.mut_iter().zip(io.iter()) { + let io = set_stdio(slot as *mut uvll::uv_stdio_container_t, other, io_loop); ret_io.push(io); } @@ -79,18 +79,18 @@ impl Process { if cfg.detach { flags |= uvll::PROCESS_DETACHED; } - let options = uvll::uv_process_options_t { + let mut options = uvll::uv_process_options_t { exit_cb: on_exit, file: unsafe { *argv }, args: argv, env: envp, cwd: match cfg.cwd { - Some(cwd) => cwd.with_ref(|p| p), + Some(cwd) => cwd.as_ptr(), None => ptr::null(), }, flags: flags as libc::c_uint, stdio_count: stdio.len() as libc::c_int, - stdio: stdio.as_ptr(), + stdio: stdio.as_mut_ptr(), uid: cfg.uid.unwrap_or(0) as uvll::uv_uid_t, gid: cfg.gid.unwrap_or(0) as uvll::uv_gid_t, }; @@ -105,7 +105,7 @@ impl Process { timeout_state: NoTimeout, }; match unsafe { - uvll::uv_spawn(io_loop.uv_loop(), handle, &options) + uvll::uv_spawn(io_loop.uv_loop(), handle, &mut options) } { 0 => Ok(process.install()), err => Err(UvError(err)), @@ -129,7 +129,7 @@ impl Process { } } -extern fn on_exit(handle: *uvll::uv_process_t, +extern fn on_exit(handle: *mut uvll::uv_process_t, exit_status: i64, term_signal: libc::c_int) { let p: &mut Process = unsafe { UvHandle::from_uv_handle(&handle) }; @@ -144,7 +144,7 @@ extern fn on_exit(handle: *uvll::uv_process_t, wakeup(&mut p.to_wake); } -unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, +unsafe fn set_stdio(dst: *mut uvll::uv_stdio_container_t, io: &rtio::StdioContainer, io_loop: &mut UvIoFactory) -> Option<PipeWatcher> { match *io { @@ -174,16 +174,17 @@ unsafe fn set_stdio(dst: *uvll::uv_stdio_container_t, } /// Converts the program and arguments to the argv array expected by libuv. -fn with_argv<T>(prog: &CString, args: &[CString], cb: |**libc::c_char| -> T) -> T { - let mut ptrs: Vec<*libc::c_char> = Vec::with_capacity(args.len()+1); +fn with_argv<T>(prog: &CString, args: &[CString], + cb: |*const *const libc::c_char| -> T) -> T { + let mut ptrs: Vec<*const libc::c_char> = Vec::with_capacity(args.len()+1); // Convert the CStrings into an array of pointers. Note: the // lifetime of the various CStrings involved is guaranteed to be // larger than the lifetime of our invocation of cb, but this is // technically unsafe as the callback could leak these pointers // out of our scope. - ptrs.push(prog.with_ref(|buf| buf)); - ptrs.extend(args.iter().map(|tmp| tmp.with_ref(|buf| buf))); + ptrs.push(prog.as_ptr()); + ptrs.extend(args.iter().map(|tmp| tmp.as_ptr())); // Add a terminating null pointer (required by libc). ptrs.push(ptr::null()); @@ -192,7 +193,8 @@ fn with_argv<T>(prog: &CString, args: &[CString], cb: |**libc::c_char| -> T) -> } /// Converts the environment to the env array expected by libuv -fn with_env<T>(env: Option<&[(CString, CString)]>, cb: |**libc::c_char| -> T) -> T { +fn with_env<T>(env: Option<&[(CString, CString)]>, + cb: |*const *const libc::c_char| -> T) -> T { // We can pass a char** for envp, which is a null-terminated array // of "k=v\0" strings. Since we must create these strings locally, // yet expose a raw pointer to them, we create a temporary vector @@ -210,9 +212,9 @@ fn with_env<T>(env: Option<&[(CString, CString)]>, cb: |**libc::c_char| -> T) -> } // As with `with_argv`, this is unsafe, since cb could leak the pointers. - let mut ptrs: Vec<*libc::c_char> = + let mut ptrs: Vec<*const libc::c_char> = tmps.iter() - .map(|tmp| tmp.as_ptr() as *libc::c_char) + .map(|tmp| tmp.as_ptr() as *const libc::c_char) .collect(); ptrs.push(ptr::null()); @@ -227,7 +229,7 @@ impl HomingIO for Process { } impl UvHandle<uvll::uv_process_t> for Process { - fn uv_handle(&self) -> *uvll::uv_process_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_process_t { self.handle } } impl rtio::RtioProcess for Process { @@ -290,7 +292,7 @@ impl rtio::RtioProcess for Process { }); let mut timer = box TimerWatcher::new_home(&loop_, self.home().clone()); unsafe { - timer.set_data(self as *mut _ as *Process); + timer.set_data(self as *mut _); } self.timer = Some(timer); } @@ -300,7 +302,7 @@ impl rtio::RtioProcess for Process { timer.start(timer_cb, ms, 0); self.timeout_state = TimeoutPending; - extern fn timer_cb(timer: *uvll::uv_timer_t) { + extern fn timer_cb(timer: *mut uvll::uv_timer_t) { let p: &mut Process = unsafe { &mut *(uvll::get_data_for_uv_handle(timer) as *mut Process) }; diff --git a/src/librustuv/queue.rs b/src/librustuv/queue.rs index a3694bfe9c2..baaf1150ce0 100644 --- a/src/librustuv/queue.rs +++ b/src/librustuv/queue.rs @@ -38,7 +38,7 @@ enum Message { } struct State { - handle: *uvll::uv_async_t, + handle: *mut uvll::uv_async_t, lock: NativeMutex, // see comments in async_cb for why this is needed queue: mpsc::Queue<Message>, } @@ -55,7 +55,7 @@ pub struct Queue { queue: Arc<State>, } -extern fn async_cb(handle: *uvll::uv_async_t) { +extern fn async_cb(handle: *mut uvll::uv_async_t) { let pool: &mut QueuePool = unsafe { mem::transmute(uvll::get_data_for_uv_handle(handle)) }; @@ -114,7 +114,7 @@ impl QueuePool { lock: unsafe {NativeMutex::new()}, queue: mpsc::Queue::new(), }); - let q = box QueuePool { + let mut q = box QueuePool { refcnt: 0, queue: state, }; @@ -122,7 +122,7 @@ impl QueuePool { unsafe { assert_eq!(uvll::uv_async_init(loop_.handle, handle, async_cb), 0); uvll::uv_unref(handle); - let data = &*q as *QueuePool as *c_void; + let data = &mut *q as *mut QueuePool as *mut c_void; uvll::set_data_for_uv_handle(handle, data); } @@ -139,7 +139,7 @@ impl QueuePool { Queue { queue: self.queue.clone() } } - pub fn handle(&self) -> *uvll::uv_async_t { self.queue.handle } + pub fn handle(&self) -> *mut uvll::uv_async_t { self.queue.handle } } impl Queue { @@ -176,7 +176,7 @@ impl Drop for Queue { impl Drop for State { fn drop(&mut self) { unsafe { - uvll::uv_close(self.handle, mem::transmute(0)); + uvll::uv_close(self.handle, mem::transmute(0u)); // Note that this does *not* free the handle, that is the // responsibility of the caller because the uv loop must be closed // before we deallocate this uv handle. diff --git a/src/librustuv/signal.rs b/src/librustuv/signal.rs index b478738ec8e..49ef4e9a24b 100644 --- a/src/librustuv/signal.rs +++ b/src/librustuv/signal.rs @@ -17,7 +17,7 @@ use uvll; use uvio::UvIoFactory; pub struct SignalWatcher { - handle: *uvll::uv_signal_t, + handle: *mut uvll::uv_signal_t, home: HomeHandle, cb: Box<Callback + Send>, @@ -45,7 +45,7 @@ impl SignalWatcher { } } -extern fn signal_cb(handle: *uvll::uv_signal_t, _signum: c_int) { +extern fn signal_cb(handle: *mut uvll::uv_signal_t, _signum: c_int) { let s: &mut SignalWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; let _ = s.cb.call(); } @@ -55,7 +55,7 @@ impl HomingIO for SignalWatcher { } impl UvHandle<uvll::uv_signal_t> for SignalWatcher { - fn uv_handle(&self) -> *uvll::uv_signal_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_signal_t { self.handle } } impl RtioSignal for SignalWatcher {} diff --git a/src/librustuv/stream.rs b/src/librustuv/stream.rs index 74294497762..f6b9226588c 100644 --- a/src/librustuv/stream.rs +++ b/src/librustuv/stream.rs @@ -23,7 +23,7 @@ use uvll; // uv_stream_t instance, and all I/O operations assume that it's already located // on the appropriate scheduler. pub struct StreamWatcher { - pub handle: *uvll::uv_stream_t, + pub handle: *mut uvll::uv_stream_t, // Cache the last used uv_write_t so we don't have to allocate a new one on // every call to uv_write(). Ideally this would be a stack-allocated @@ -59,8 +59,11 @@ impl StreamWatcher { // will be manipulated on each of the methods called on this watcher. // Wrappers should ensure to always reset the field to an appropriate value // if they rely on the field to perform an action. - pub fn new(stream: *uvll::uv_stream_t) -> StreamWatcher { - unsafe { uvll::set_data_for_uv_handle(stream, 0 as *int) } + pub fn new(stream: *mut uvll::uv_stream_t, + init: bool) -> StreamWatcher { + if init { + unsafe { uvll::set_data_for_uv_handle(stream, 0 as *mut int) } + } StreamWatcher { handle: stream, last_write_req: None, @@ -85,7 +88,7 @@ impl StreamWatcher { // we must be ready for this to happen (by setting the data in the uv // handle). In theory this otherwise doesn't need to happen until after // the read is succesfully started. - unsafe { uvll::set_data_for_uv_handle(self.handle, &rcx) } + unsafe { uvll::set_data_for_uv_handle(self.handle, &mut rcx) } // Send off the read request, but don't block until we're sure that the // read request is queued. @@ -103,7 +106,7 @@ impl StreamWatcher { n => Err(UvError(n)) }; // Make sure a read cancellation sees that there's no pending read - unsafe { uvll::set_data_for_uv_handle(self.handle, 0 as *int) } + unsafe { uvll::set_data_for_uv_handle(self.handle, 0 as *mut int) } return ret; } @@ -115,7 +118,7 @@ impl StreamWatcher { let data = unsafe { let data = uvll::get_data_for_uv_handle(self.handle); if data.is_null() { return None } - uvll::set_data_for_uv_handle(self.handle, 0 as *int); + uvll::set_data_for_uv_handle(self.handle, 0 as *mut int); &mut *(data as *mut ReadContext) }; data.result = reason; @@ -133,7 +136,7 @@ impl StreamWatcher { let mut req = match self.last_write_req.take() { Some(req) => req, None => Request::new(uvll::UV_WRITE), }; - req.set_data(ptr::null::<()>()); + req.set_data(ptr::mut_null::<()>()); // And here's where timeouts get a little interesting. Currently, libuv // does not support canceling an in-flight write request. Consequently, @@ -180,7 +183,7 @@ impl StreamWatcher { let loop_ = unsafe { uvll::get_loop_for_uv_handle(self.handle) }; wait_until_woken_after(&mut self.blocked_writer, &Loop::wrap(loop_), || { - req.set_data(&wcx); + req.set_data(&mut wcx); }); if wcx.result != uvll::ECANCELED { @@ -205,13 +208,13 @@ impl StreamWatcher { // Note that we don't cache this write request back in the // stream watcher because we no longer have ownership of it, and // we never will. - let new_wcx = box WriteContext { + let mut new_wcx = box WriteContext { result: 0, stream: 0 as *mut StreamWatcher, data: wcx.data.take(), }; unsafe { - req.set_data(&*new_wcx); + req.set_data(&mut *new_wcx); mem::forget(new_wcx); } Err(UvError(wcx.result)) @@ -228,7 +231,7 @@ impl StreamWatcher { // This allocation callback expects to be invoked once and only once. It will // unwrap the buffer in the ReadContext stored in the stream and return it. This // will fail if it is called more than once. -extern fn alloc_cb(stream: *uvll::uv_stream_t, _hint: size_t, buf: *mut Buf) { +extern fn alloc_cb(stream: *mut uvll::uv_stream_t, _hint: size_t, buf: *mut Buf) { uvdebug!("alloc_cb"); unsafe { let rcx: &mut ReadContext = @@ -239,7 +242,8 @@ extern fn alloc_cb(stream: *uvll::uv_stream_t, _hint: size_t, buf: *mut Buf) { // When a stream has read some data, we will always forcibly stop reading and // return all the data read (even if it didn't fill the whole buffer). -extern fn read_cb(handle: *uvll::uv_stream_t, nread: ssize_t, _buf: *Buf) { +extern fn read_cb(handle: *mut uvll::uv_stream_t, nread: ssize_t, + _buf: *const Buf) { uvdebug!("read_cb {}", nread); assert!(nread != uvll::ECANCELED as ssize_t); let rcx: &mut ReadContext = unsafe { @@ -258,7 +262,7 @@ extern fn read_cb(handle: *uvll::uv_stream_t, nread: ssize_t, _buf: *Buf) { // Unlike reading, the WriteContext is stored in the uv_write_t request. Like // reading, however, all this does is wake up the blocked task after squirreling // away the error code as a result. -extern fn write_cb(req: *uvll::uv_write_t, status: c_int) { +extern fn write_cb(req: *mut uvll::uv_write_t, status: c_int) { let mut req = Request::wrap(req); // Remember to not free the request because it is re-used between writes on // the same stream. diff --git a/src/librustuv/timeout.rs b/src/librustuv/timeout.rs index 1c191d476ed..1caaf5e0fc7 100644 --- a/src/librustuv/timeout.rs +++ b/src/librustuv/timeout.rs @@ -119,13 +119,13 @@ impl AccessTimeout { // to fire when the timeout runs out. if self.timer.is_none() { let mut timer = box TimerWatcher::new_home(loop_, home.clone()); - let cx = box TimerContext { + let mut cx = box TimerContext { timeout: self as *mut _, callback: cb, payload: data, }; unsafe { - timer.set_data(&*cx); + timer.set_data(&mut *cx); mem::forget(cx); } self.timer = Some(timer); @@ -142,9 +142,9 @@ impl AccessTimeout { timer.start(timer_cb, ms, 0); self.state = TimeoutPending(NoWaiter); - extern fn timer_cb(timer: *uvll::uv_timer_t) { + extern fn timer_cb(timer: *mut uvll::uv_timer_t) { let cx: &TimerContext = unsafe { - &*(uvll::get_data_for_uv_handle(timer) as *TimerContext) + &*(uvll::get_data_for_uv_handle(timer) as *const TimerContext) }; let me = unsafe { &mut *cx.timeout }; @@ -240,7 +240,7 @@ impl ConnectCtx { None => {} } wait_until_woken_after(&mut self.task, &io.loop_, || { - let data = &self as *_; + let data = &self as *const _ as *mut ConnectCtx; match self.timer { Some(ref mut timer) => unsafe { timer.set_data(data) }, None => {} @@ -249,7 +249,7 @@ impl ConnectCtx { }); // Make sure an erroneously fired callback doesn't have access // to the context any more. - req.set_data(0 as *int); + req.set_data(0 as *mut int); // If we failed because of a timeout, drop the TcpWatcher as // soon as possible because it's data is now set to null and we @@ -262,7 +262,7 @@ impl ConnectCtx { n => Err(UvError(n)) }; - extern fn timer_cb(handle: *uvll::uv_timer_t) { + extern fn timer_cb(handle: *mut uvll::uv_timer_t) { // Don't close the corresponding tcp request, just wake up the task // and let RAII take care of the pending watcher. let cx: &mut ConnectCtx = unsafe { @@ -272,7 +272,7 @@ impl ConnectCtx { wakeup(&mut cx.task); } - extern fn connect_cb(req: *uvll::uv_connect_t, status: c_int) { + extern fn connect_cb(req: *mut uvll::uv_connect_t, status: c_int) { // This callback can be invoked with ECANCELED if the watcher is // closed by the timeout callback. In that case we just want to free // the request and be along our merry way. @@ -367,7 +367,7 @@ impl AcceptTimeout { }); let mut timer = TimerWatcher::new_home(&loop_, t.home().clone()); unsafe { - timer.set_data(self as *mut _ as *AcceptTimeout); + timer.set_data(self as *mut _); } self.timer = Some(timer); } @@ -381,7 +381,7 @@ impl AcceptTimeout { self.timeout_tx = Some(tx); self.timeout_rx = Some(rx); - extern fn timer_cb(timer: *uvll::uv_timer_t) { + extern fn timer_cb(timer: *mut uvll::uv_timer_t) { let acceptor: &mut AcceptTimeout = unsafe { &mut *(uvll::get_data_for_uv_handle(timer) as *mut AcceptTimeout) }; diff --git a/src/librustuv/timer.rs b/src/librustuv/timer.rs index 34cd2e489a0..9d0a56b3c85 100644 --- a/src/librustuv/timer.rs +++ b/src/librustuv/timer.rs @@ -18,7 +18,7 @@ use uvio::UvIoFactory; use uvll; pub struct TimerWatcher { - pub handle: *uvll::uv_timer_t, + pub handle: *mut uvll::uv_timer_t, home: HomeHandle, action: Option<NextAction>, blocker: Option<BlockedTask>, @@ -60,7 +60,7 @@ impl TimerWatcher { assert_eq!(unsafe { uvll::uv_timer_stop(self.handle) }, 0) } - pub unsafe fn set_data<T>(&mut self, data: *T) { + pub unsafe fn set_data<T>(&mut self, data: *mut T) { uvll::set_data_for_uv_handle(self.handle, data); } } @@ -70,7 +70,7 @@ impl HomingIO for TimerWatcher { } impl UvHandle<uvll::uv_timer_t> for TimerWatcher { - fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle } + fn uv_handle(&self) -> *mut uvll::uv_timer_t { self.handle } } impl RtioTimer for TimerWatcher { @@ -128,7 +128,7 @@ impl RtioTimer for TimerWatcher { } } -extern fn timer_cb(handle: *uvll::uv_timer_t) { +extern fn timer_cb(handle: *mut uvll::uv_timer_t) { let _f = ForbidSwitch::new("timer callback can't switch"); let timer: &mut TimerWatcher = unsafe { UvHandle::from_uv_handle(&handle) }; diff --git a/src/librustuv/tty.rs b/src/librustuv/tty.rs index 828a3d0c63b..70b17db8dcf 100644 --- a/src/librustuv/tty.rs +++ b/src/librustuv/tty.rs @@ -19,7 +19,7 @@ use uvio::UvIoFactory; use uvll; pub struct TtyWatcher{ - tty: *uvll::uv_tty_t, + tty: *mut uvll::uv_tty_t, stream: StreamWatcher, home: HomeHandle, fd: libc::c_int, @@ -56,7 +56,7 @@ impl TtyWatcher { let handle = UvHandle::alloc(None::<TtyWatcher>, uvll::UV_TTY); let mut watcher = TtyWatcher { tty: handle, - stream: StreamWatcher::new(handle), + stream: StreamWatcher::new(handle, true), home: io.make_handle(), fd: fd, }; @@ -70,7 +70,7 @@ impl TtyWatcher { // handle, so our only cleanup is to free the handle itself if cfg!(windows) { unsafe { uvll::free_handle(handle); } - watcher.tty = ptr::null(); + watcher.tty = ptr::mut_null(); } Err(UvError(n)) } @@ -102,8 +102,8 @@ impl RtioTTY for TtyWatcher { fn get_winsize(&mut self) -> IoResult<(int, int)> { let mut width: libc::c_int = 0; let mut height: libc::c_int = 0; - let widthptr: *libc::c_int = &width; - let heightptr: *libc::c_int = &width; + let widthptr: *mut libc::c_int = &mut width; + let heightptr: *mut libc::c_int = &mut width; let _m = self.fire_homing_missile(); match unsafe { uvll::uv_tty_get_winsize(self.tty, @@ -119,7 +119,7 @@ impl RtioTTY for TtyWatcher { } impl UvHandle<uvll::uv_tty_t> for TtyWatcher { - fn uv_handle(&self) -> *uvll::uv_tty_t { self.tty } + fn uv_handle(&self) -> *mut uvll::uv_tty_t { self.tty } } impl HomingIO for TtyWatcher { diff --git a/src/librustuv/uvio.rs b/src/librustuv/uvio.rs index 8c9d29ee914..61e52a3abd1 100644 --- a/src/librustuv/uvio.rs +++ b/src/librustuv/uvio.rs @@ -126,7 +126,7 @@ pub struct UvIoFactory { } impl UvIoFactory { - pub fn uv_loop<'a>(&mut self) -> *uvll::uv_loop_t { self.loop_.handle } + pub fn uv_loop<'a>(&mut self) -> *mut uvll::uv_loop_t { self.loop_.handle } pub fn make_handle(&mut self) -> HomeHandle { // It's understood by the homing code that the "local id" is just the diff --git a/src/librustuv/uvll.rs b/src/librustuv/uvll.rs index a6193dd9379..863536a4111 100644 --- a/src/librustuv/uvll.rs +++ b/src/librustuv/uvll.rs @@ -103,7 +103,7 @@ pub type uv_buf_len_t = libc::c_ulong; // see libuv/include/uv-unix.h #[cfg(unix)] pub struct uv_buf_t { - pub base: *u8, + pub base: *mut u8, pub len: uv_buf_len_t, } @@ -111,7 +111,7 @@ pub struct uv_buf_t { #[cfg(windows)] pub struct uv_buf_t { pub len: uv_buf_len_t, - pub base: *u8, + pub base: *mut u8, } #[repr(C)] @@ -123,13 +123,13 @@ pub enum uv_run_mode { pub struct uv_process_options_t { pub exit_cb: uv_exit_cb, - pub file: *libc::c_char, - pub args: **libc::c_char, - pub env: **libc::c_char, - pub cwd: *libc::c_char, + pub file: *const libc::c_char, + pub args: *const *const libc::c_char, + pub env: *const *const libc::c_char, + pub cwd: *const libc::c_char, pub flags: libc::c_uint, pub stdio_count: libc::c_int, - pub stdio: *uv_stdio_container_t, + pub stdio: *mut uv_stdio_container_t, pub uid: uv_uid_t, pub gid: uv_gid_t, } @@ -139,7 +139,7 @@ pub struct uv_process_options_t { #[repr(C)] pub struct uv_stdio_container_t { flags: libc::c_int, - stream: *uv_stream_t, + stream: *mut uv_stream_t, } pub type uv_handle_t = c_void; @@ -216,41 +216,41 @@ impl uv_stat_t { } } -pub type uv_idle_cb = extern "C" fn(handle: *uv_idle_t); -pub type uv_alloc_cb = extern "C" fn(stream: *uv_stream_t, +pub type uv_idle_cb = extern "C" fn(handle: *mut uv_idle_t); +pub type uv_alloc_cb = extern "C" fn(stream: *mut uv_stream_t, suggested_size: size_t, buf: *mut uv_buf_t); -pub type uv_read_cb = extern "C" fn(stream: *uv_stream_t, +pub type uv_read_cb = extern "C" fn(stream: *mut uv_stream_t, nread: ssize_t, - buf: *uv_buf_t); -pub type uv_udp_send_cb = extern "C" fn(req: *uv_udp_send_t, + buf: *const uv_buf_t); +pub type uv_udp_send_cb = extern "C" fn(req: *mut uv_udp_send_t, status: c_int); -pub type uv_udp_recv_cb = extern "C" fn(handle: *uv_udp_t, +pub type uv_udp_recv_cb = extern "C" fn(handle: *mut uv_udp_t, nread: ssize_t, - buf: *uv_buf_t, - addr: *sockaddr, + buf: *const uv_buf_t, + addr: *const sockaddr, flags: c_uint); -pub type uv_close_cb = extern "C" fn(handle: *uv_handle_t); -pub type uv_walk_cb = extern "C" fn(handle: *uv_handle_t, - arg: *c_void); -pub type uv_async_cb = extern "C" fn(handle: *uv_async_t); -pub type uv_connect_cb = extern "C" fn(handle: *uv_connect_t, +pub type uv_close_cb = extern "C" fn(handle: *mut uv_handle_t); +pub type uv_walk_cb = extern "C" fn(handle: *mut uv_handle_t, + arg: *mut c_void); +pub type uv_async_cb = extern "C" fn(handle: *mut uv_async_t); +pub type uv_connect_cb = extern "C" fn(handle: *mut uv_connect_t, status: c_int); -pub type uv_connection_cb = extern "C" fn(handle: *uv_connection_t, +pub type uv_connection_cb = extern "C" fn(handle: *mut uv_connection_t, status: c_int); -pub type uv_timer_cb = extern "C" fn(handle: *uv_timer_t); -pub type uv_write_cb = extern "C" fn(handle: *uv_write_t, +pub type uv_timer_cb = extern "C" fn(handle: *mut uv_timer_t); +pub type uv_write_cb = extern "C" fn(handle: *mut uv_write_t, status: c_int); -pub type uv_getaddrinfo_cb = extern "C" fn(req: *uv_getaddrinfo_t, +pub type uv_getaddrinfo_cb = extern "C" fn(req: *mut uv_getaddrinfo_t, status: c_int, - res: *addrinfo); -pub type uv_exit_cb = extern "C" fn(handle: *uv_process_t, + res: *const addrinfo); +pub type uv_exit_cb = extern "C" fn(handle: *mut uv_process_t, exit_status: i64, term_signal: c_int); -pub type uv_signal_cb = extern "C" fn(handle: *uv_signal_t, +pub type uv_signal_cb = extern "C" fn(handle: *mut uv_signal_t, signum: c_int); -pub type uv_fs_cb = extern "C" fn(req: *uv_fs_t); -pub type uv_shutdown_cb = extern "C" fn(req: *uv_shutdown_t, status: c_int); +pub type uv_fs_cb = extern "C" fn(req: *mut uv_fs_t); +pub type uv_shutdown_cb = extern "C" fn(req: *mut uv_shutdown_t, status: c_int); #[cfg(unix)] pub type uv_uid_t = libc::types::os::arch::posix88::uid_t; #[cfg(unix)] pub type uv_gid_t = libc::types::os::arch::posix88::gid_t; @@ -330,23 +330,23 @@ pub enum uv_membership { UV_JOIN_GROUP } -pub unsafe fn malloc_handle(handle: uv_handle_type) -> *c_void { +pub unsafe fn malloc_handle(handle: uv_handle_type) -> *mut c_void { assert!(handle != UV_UNKNOWN_HANDLE && handle != UV_HANDLE_TYPE_MAX); let size = uv_handle_size(handle); - malloc_raw(size as uint) as *c_void + malloc_raw(size as uint) as *mut c_void } -pub unsafe fn free_handle(v: *c_void) { +pub unsafe fn free_handle(v: *mut c_void) { free(v as *mut c_void) } -pub unsafe fn malloc_req(req: uv_req_type) -> *c_void { +pub unsafe fn malloc_req(req: uv_req_type) -> *mut c_void { assert!(req != UV_UNKNOWN_REQ && req != UV_REQ_TYPE_MAX); let size = uv_req_size(req); - malloc_raw(size as uint) as *c_void + malloc_raw(size as uint) as *mut c_void } -pub unsafe fn free_req(v: *c_void) { +pub unsafe fn free_req(v: *mut c_void) { free(v as *mut c_void) } @@ -365,17 +365,17 @@ fn request_sanity_check() { } // FIXME Event loops ignore SIGPIPE by default. -pub unsafe fn loop_new() -> *c_void { +pub unsafe fn loop_new() -> *mut c_void { return rust_uv_loop_new(); } -pub unsafe fn uv_write(req: *uv_write_t, - stream: *uv_stream_t, +pub unsafe fn uv_write(req: *mut uv_write_t, + stream: *mut uv_stream_t, buf_in: &[uv_buf_t], cb: uv_write_cb) -> c_int { extern { - fn uv_write(req: *uv_write_t, stream: *uv_stream_t, - buf_in: *uv_buf_t, buf_cnt: c_int, + fn uv_write(req: *mut uv_write_t, stream: *mut uv_stream_t, + buf_in: *const uv_buf_t, buf_cnt: c_int, cb: uv_write_cb) -> c_int; } @@ -384,14 +384,15 @@ pub unsafe fn uv_write(req: *uv_write_t, return uv_write(req, stream, buf_ptr, buf_cnt, cb); } -pub unsafe fn uv_udp_send(req: *uv_udp_send_t, - handle: *uv_udp_t, +pub unsafe fn uv_udp_send(req: *mut uv_udp_send_t, + handle: *mut uv_udp_t, buf_in: &[uv_buf_t], - addr: *sockaddr, + addr: *const sockaddr, cb: uv_udp_send_cb) -> c_int { extern { - fn uv_udp_send(req: *uv_write_t, stream: *uv_stream_t, - buf_in: *uv_buf_t, buf_cnt: c_int, addr: *sockaddr, + fn uv_udp_send(req: *mut uv_write_t, stream: *mut uv_stream_t, + buf_in: *const uv_buf_t, buf_cnt: c_int, + addr: *const sockaddr, cb: uv_udp_send_cb) -> c_int; } @@ -400,76 +401,76 @@ pub unsafe fn uv_udp_send(req: *uv_udp_send_t, return uv_udp_send(req, handle, buf_ptr, buf_cnt, addr, cb); } -pub unsafe fn get_udp_handle_from_send_req(send_req: *uv_udp_send_t) -> *uv_udp_t { +pub unsafe fn get_udp_handle_from_send_req(send_req: *mut uv_udp_send_t) -> *mut uv_udp_t { return rust_uv_get_udp_handle_from_send_req(send_req); } -pub unsafe fn process_pid(p: *uv_process_t) -> c_int { +pub unsafe fn process_pid(p: *mut uv_process_t) -> c_int { return rust_uv_process_pid(p); } -pub unsafe fn set_stdio_container_flags(c: *uv_stdio_container_t, +pub unsafe fn set_stdio_container_flags(c: *mut uv_stdio_container_t, flags: libc::c_int) { rust_set_stdio_container_flags(c, flags); } -pub unsafe fn set_stdio_container_fd(c: *uv_stdio_container_t, +pub unsafe fn set_stdio_container_fd(c: *mut uv_stdio_container_t, fd: libc::c_int) { rust_set_stdio_container_fd(c, fd); } -pub unsafe fn set_stdio_container_stream(c: *uv_stdio_container_t, - stream: *uv_stream_t) { +pub unsafe fn set_stdio_container_stream(c: *mut uv_stdio_container_t, + stream: *mut uv_stream_t) { rust_set_stdio_container_stream(c, stream); } // data access helpers -pub unsafe fn get_result_from_fs_req(req: *uv_fs_t) -> ssize_t { +pub unsafe fn get_result_from_fs_req(req: *mut uv_fs_t) -> ssize_t { rust_uv_get_result_from_fs_req(req) } -pub unsafe fn get_ptr_from_fs_req(req: *uv_fs_t) -> *libc::c_void { +pub unsafe fn get_ptr_from_fs_req(req: *mut uv_fs_t) -> *mut libc::c_void { rust_uv_get_ptr_from_fs_req(req) } -pub unsafe fn get_path_from_fs_req(req: *uv_fs_t) -> *c_char { +pub unsafe fn get_path_from_fs_req(req: *mut uv_fs_t) -> *mut c_char { rust_uv_get_path_from_fs_req(req) } -pub unsafe fn get_loop_from_fs_req(req: *uv_fs_t) -> *uv_loop_t { +pub unsafe fn get_loop_from_fs_req(req: *mut uv_fs_t) -> *mut uv_loop_t { rust_uv_get_loop_from_fs_req(req) } -pub unsafe fn get_loop_from_getaddrinfo_req(req: *uv_getaddrinfo_t) -> *uv_loop_t { +pub unsafe fn get_loop_from_getaddrinfo_req(req: *mut uv_getaddrinfo_t) -> *mut uv_loop_t { rust_uv_get_loop_from_getaddrinfo_req(req) } -pub unsafe fn get_loop_for_uv_handle<T>(handle: *T) -> *c_void { - return rust_uv_get_loop_for_uv_handle(handle as *c_void); +pub unsafe fn get_loop_for_uv_handle<T>(handle: *mut T) -> *mut c_void { + return rust_uv_get_loop_for_uv_handle(handle as *mut c_void); } -pub unsafe fn get_stream_handle_from_connect_req(connect: *uv_connect_t) -> *uv_stream_t { +pub unsafe fn get_stream_handle_from_connect_req(connect: *mut uv_connect_t) -> *mut uv_stream_t { return rust_uv_get_stream_handle_from_connect_req(connect); } -pub unsafe fn get_stream_handle_from_write_req(write_req: *uv_write_t) -> *uv_stream_t { +pub unsafe fn get_stream_handle_from_write_req(write_req: *mut uv_write_t) -> *mut uv_stream_t { return rust_uv_get_stream_handle_from_write_req(write_req); } -pub unsafe fn get_data_for_uv_loop(loop_ptr: *c_void) -> *c_void { +pub unsafe fn get_data_for_uv_loop(loop_ptr: *mut c_void) -> *mut c_void { rust_uv_get_data_for_uv_loop(loop_ptr) } -pub unsafe fn set_data_for_uv_loop(loop_ptr: *c_void, data: *c_void) { +pub unsafe fn set_data_for_uv_loop(loop_ptr: *mut c_void, data: *mut c_void) { rust_uv_set_data_for_uv_loop(loop_ptr, data); } -pub unsafe fn get_data_for_uv_handle<T>(handle: *T) -> *c_void { - return rust_uv_get_data_for_uv_handle(handle as *c_void); +pub unsafe fn get_data_for_uv_handle<T>(handle: *mut T) -> *mut c_void { + return rust_uv_get_data_for_uv_handle(handle as *mut c_void); } -pub unsafe fn set_data_for_uv_handle<T, U>(handle: *T, data: *U) { - rust_uv_set_data_for_uv_handle(handle as *c_void, data as *c_void); +pub unsafe fn set_data_for_uv_handle<T, U>(handle: *mut T, data: *mut U) { + rust_uv_set_data_for_uv_handle(handle as *mut c_void, data as *mut c_void); } -pub unsafe fn get_data_for_req<T>(req: *T) -> *c_void { - return rust_uv_get_data_for_req(req as *c_void); +pub unsafe fn get_data_for_req<T>(req: *mut T) -> *mut c_void { + return rust_uv_get_data_for_req(req as *mut c_void); } -pub unsafe fn set_data_for_req<T, U>(req: *T, data: *U) { - rust_uv_set_data_for_req(req as *c_void, data as *c_void); +pub unsafe fn set_data_for_req<T, U>(req: *mut T, data: *mut U) { + rust_uv_set_data_for_req(req as *mut c_void, data as *mut c_void); } -pub unsafe fn populate_stat(req_in: *uv_fs_t, stat_out: *uv_stat_t) { +pub unsafe fn populate_stat(req_in: *mut uv_fs_t, stat_out: *mut uv_stat_t) { rust_uv_populate_uv_stat(req_in, stat_out) } pub unsafe fn guess_handle(handle: c_int) -> c_int { @@ -493,186 +494,196 @@ pub unsafe fn guess_handle(handle: c_int) -> c_int { extern {} extern { - fn rust_uv_loop_new() -> *c_void; + fn rust_uv_loop_new() -> *mut c_void; #[cfg(test)] fn rust_uv_handle_type_max() -> uintptr_t; #[cfg(test)] fn rust_uv_req_type_max() -> uintptr_t; - fn rust_uv_get_udp_handle_from_send_req(req: *uv_udp_send_t) -> *uv_udp_t; - - fn rust_uv_populate_uv_stat(req_in: *uv_fs_t, stat_out: *uv_stat_t); - fn rust_uv_get_result_from_fs_req(req: *uv_fs_t) -> ssize_t; - fn rust_uv_get_ptr_from_fs_req(req: *uv_fs_t) -> *libc::c_void; - fn rust_uv_get_path_from_fs_req(req: *uv_fs_t) -> *c_char; - fn rust_uv_get_loop_from_fs_req(req: *uv_fs_t) -> *uv_loop_t; - fn rust_uv_get_loop_from_getaddrinfo_req(req: *uv_fs_t) -> *uv_loop_t; - fn rust_uv_get_stream_handle_from_connect_req(req: *uv_connect_t) -> *uv_stream_t; - fn rust_uv_get_stream_handle_from_write_req(req: *uv_write_t) -> *uv_stream_t; - fn rust_uv_get_loop_for_uv_handle(handle: *c_void) -> *c_void; - fn rust_uv_get_data_for_uv_loop(loop_ptr: *c_void) -> *c_void; - fn rust_uv_set_data_for_uv_loop(loop_ptr: *c_void, data: *c_void); - fn rust_uv_get_data_for_uv_handle(handle: *c_void) -> *c_void; - fn rust_uv_set_data_for_uv_handle(handle: *c_void, data: *c_void); - fn rust_uv_get_data_for_req(req: *c_void) -> *c_void; - fn rust_uv_set_data_for_req(req: *c_void, data: *c_void); - fn rust_set_stdio_container_flags(c: *uv_stdio_container_t, flags: c_int); - fn rust_set_stdio_container_fd(c: *uv_stdio_container_t, fd: c_int); - fn rust_set_stdio_container_stream(c: *uv_stdio_container_t, - stream: *uv_stream_t); - fn rust_uv_process_pid(p: *uv_process_t) -> c_int; + fn rust_uv_get_udp_handle_from_send_req(req: *mut uv_udp_send_t) -> *mut uv_udp_t; + + fn rust_uv_populate_uv_stat(req_in: *mut uv_fs_t, stat_out: *mut uv_stat_t); + fn rust_uv_get_result_from_fs_req(req: *mut uv_fs_t) -> ssize_t; + fn rust_uv_get_ptr_from_fs_req(req: *mut uv_fs_t) -> *mut libc::c_void; + fn rust_uv_get_path_from_fs_req(req: *mut uv_fs_t) -> *mut c_char; + fn rust_uv_get_loop_from_fs_req(req: *mut uv_fs_t) -> *mut uv_loop_t; + fn rust_uv_get_loop_from_getaddrinfo_req(req: *mut uv_fs_t) -> *mut uv_loop_t; + fn rust_uv_get_stream_handle_from_connect_req(req: *mut uv_connect_t) -> *mut uv_stream_t; + fn rust_uv_get_stream_handle_from_write_req(req: *mut uv_write_t) -> *mut uv_stream_t; + fn rust_uv_get_loop_for_uv_handle(handle: *mut c_void) -> *mut c_void; + fn rust_uv_get_data_for_uv_loop(loop_ptr: *mut c_void) -> *mut c_void; + fn rust_uv_set_data_for_uv_loop(loop_ptr: *mut c_void, data: *mut c_void); + fn rust_uv_get_data_for_uv_handle(handle: *mut c_void) -> *mut c_void; + fn rust_uv_set_data_for_uv_handle(handle: *mut c_void, data: *mut c_void); + fn rust_uv_get_data_for_req(req: *mut c_void) -> *mut c_void; + fn rust_uv_set_data_for_req(req: *mut c_void, data: *mut c_void); + fn rust_set_stdio_container_flags(c: *mut uv_stdio_container_t, flags: c_int); + fn rust_set_stdio_container_fd(c: *mut uv_stdio_container_t, fd: c_int); + fn rust_set_stdio_container_stream(c: *mut uv_stdio_container_t, + stream: *mut uv_stream_t); + fn rust_uv_process_pid(p: *mut uv_process_t) -> c_int; fn rust_uv_guess_handle(fd: c_int) -> c_int; // generic uv functions - pub fn uv_loop_delete(l: *uv_loop_t); - pub fn uv_ref(t: *uv_handle_t); - pub fn uv_unref(t: *uv_handle_t); + pub fn uv_loop_delete(l: *mut uv_loop_t); + pub fn uv_ref(t: *mut uv_handle_t); + pub fn uv_unref(t: *mut uv_handle_t); pub fn uv_handle_size(ty: uv_handle_type) -> size_t; pub fn uv_req_size(ty: uv_req_type) -> size_t; - pub fn uv_run(l: *uv_loop_t, mode: uv_run_mode) -> c_int; - pub fn uv_close(h: *uv_handle_t, cb: uv_close_cb); - pub fn uv_walk(l: *uv_loop_t, cb: uv_walk_cb, arg: *c_void); - pub fn uv_buf_init(base: *c_char, len: c_uint) -> uv_buf_t; - pub fn uv_strerror(err: c_int) -> *c_char; - pub fn uv_err_name(err: c_int) -> *c_char; - pub fn uv_listen(s: *uv_stream_t, backlog: c_int, + pub fn uv_run(l: *mut uv_loop_t, mode: uv_run_mode) -> c_int; + pub fn uv_close(h: *mut uv_handle_t, cb: uv_close_cb); + pub fn uv_walk(l: *mut uv_loop_t, cb: uv_walk_cb, arg: *mut c_void); + pub fn uv_buf_init(base: *mut c_char, len: c_uint) -> uv_buf_t; + pub fn uv_strerror(err: c_int) -> *const c_char; + pub fn uv_err_name(err: c_int) -> *const c_char; + pub fn uv_listen(s: *mut uv_stream_t, backlog: c_int, cb: uv_connection_cb) -> c_int; - pub fn uv_accept(server: *uv_stream_t, client: *uv_stream_t) -> c_int; - pub fn uv_read_start(stream: *uv_stream_t, + pub fn uv_accept(server: *mut uv_stream_t, client: *mut uv_stream_t) -> c_int; + pub fn uv_read_start(stream: *mut uv_stream_t, on_alloc: uv_alloc_cb, on_read: uv_read_cb) -> c_int; - pub fn uv_read_stop(stream: *uv_stream_t) -> c_int; - pub fn uv_shutdown(req: *uv_shutdown_t, handle: *uv_stream_t, + pub fn uv_read_stop(stream: *mut uv_stream_t) -> c_int; + pub fn uv_shutdown(req: *mut uv_shutdown_t, handle: *mut uv_stream_t, cb: uv_shutdown_cb) -> c_int; // idle bindings - pub fn uv_idle_init(l: *uv_loop_t, i: *uv_idle_t) -> c_int; - pub fn uv_idle_start(i: *uv_idle_t, cb: uv_idle_cb) -> c_int; - pub fn uv_idle_stop(i: *uv_idle_t) -> c_int; + pub fn uv_idle_init(l: *mut uv_loop_t, i: *mut uv_idle_t) -> c_int; + pub fn uv_idle_start(i: *mut uv_idle_t, cb: uv_idle_cb) -> c_int; + pub fn uv_idle_stop(i: *mut uv_idle_t) -> c_int; // async bindings - pub fn uv_async_init(l: *uv_loop_t, a: *uv_async_t, + pub fn uv_async_init(l: *mut uv_loop_t, a: *mut uv_async_t, cb: uv_async_cb) -> c_int; - pub fn uv_async_send(a: *uv_async_t); + pub fn uv_async_send(a: *mut uv_async_t); // tcp bindings - pub fn uv_tcp_init(l: *uv_loop_t, h: *uv_tcp_t) -> c_int; - pub fn uv_tcp_connect(c: *uv_connect_t, h: *uv_tcp_t, - addr: *sockaddr, cb: uv_connect_cb) -> c_int; - pub fn uv_tcp_bind(t: *uv_tcp_t, addr: *sockaddr) -> c_int; - pub fn uv_tcp_nodelay(h: *uv_tcp_t, enable: c_int) -> c_int; - pub fn uv_tcp_keepalive(h: *uv_tcp_t, enable: c_int, + pub fn uv_tcp_init(l: *mut uv_loop_t, h: *mut uv_tcp_t) -> c_int; + pub fn uv_tcp_connect(c: *mut uv_connect_t, h: *mut uv_tcp_t, + addr: *const sockaddr, cb: uv_connect_cb) -> c_int; + pub fn uv_tcp_bind(t: *mut uv_tcp_t, addr: *const sockaddr) -> c_int; + pub fn uv_tcp_nodelay(h: *mut uv_tcp_t, enable: c_int) -> c_int; + pub fn uv_tcp_keepalive(h: *mut uv_tcp_t, enable: c_int, delay: c_uint) -> c_int; - pub fn uv_tcp_simultaneous_accepts(h: *uv_tcp_t, enable: c_int) -> c_int; - pub fn uv_tcp_getsockname(h: *uv_tcp_t, name: *mut sockaddr, + pub fn uv_tcp_simultaneous_accepts(h: *mut uv_tcp_t, enable: c_int) -> c_int; + pub fn uv_tcp_getsockname(h: *mut uv_tcp_t, name: *mut sockaddr, len: *mut c_int) -> c_int; - pub fn uv_tcp_getpeername(h: *uv_tcp_t, name: *mut sockaddr, + pub fn uv_tcp_getpeername(h: *mut uv_tcp_t, name: *mut sockaddr, len: *mut c_int) -> c_int; // udp bindings - pub fn uv_udp_init(l: *uv_loop_t, h: *uv_udp_t) -> c_int; - pub fn uv_udp_bind(h: *uv_udp_t, addr: *sockaddr, flags: c_uint) -> c_int; - pub fn uv_udp_recv_start(server: *uv_udp_t, + pub fn uv_udp_init(l: *mut uv_loop_t, h: *mut uv_udp_t) -> c_int; + pub fn uv_udp_bind(h: *mut uv_udp_t, addr: *const sockaddr, + flags: c_uint) -> c_int; + pub fn uv_udp_recv_start(server: *mut uv_udp_t, on_alloc: uv_alloc_cb, on_recv: uv_udp_recv_cb) -> c_int; - pub fn uv_udp_set_membership(handle: *uv_udp_t, multicast_addr: *c_char, - interface_addr: *c_char, + pub fn uv_udp_set_membership(handle: *mut uv_udp_t, + multicast_addr: *const c_char, + interface_addr: *const c_char, membership: uv_membership) -> c_int; - pub fn uv_udp_recv_stop(server: *uv_udp_t) -> c_int; - pub fn uv_udp_set_multicast_loop(handle: *uv_udp_t, on: c_int) -> c_int; - pub fn uv_udp_set_multicast_ttl(handle: *uv_udp_t, ttl: c_int) -> c_int; - pub fn uv_udp_set_ttl(handle: *uv_udp_t, ttl: c_int) -> c_int; - pub fn uv_udp_set_broadcast(handle: *uv_udp_t, on: c_int) -> c_int; - pub fn uv_udp_getsockname(h: *uv_udp_t, name: *mut sockaddr, + pub fn uv_udp_recv_stop(server: *mut uv_udp_t) -> c_int; + pub fn uv_udp_set_multicast_loop(handle: *mut uv_udp_t, on: c_int) -> c_int; + pub fn uv_udp_set_multicast_ttl(handle: *mut uv_udp_t, ttl: c_int) -> c_int; + pub fn uv_udp_set_ttl(handle: *mut uv_udp_t, ttl: c_int) -> c_int; + pub fn uv_udp_set_broadcast(handle: *mut uv_udp_t, on: c_int) -> c_int; + pub fn uv_udp_getsockname(h: *mut uv_udp_t, name: *mut sockaddr, len: *mut c_int) -> c_int; // timer bindings - pub fn uv_timer_init(l: *uv_loop_t, t: *uv_timer_t) -> c_int; - pub fn uv_timer_start(t: *uv_timer_t, cb: uv_timer_cb, + pub fn uv_timer_init(l: *mut uv_loop_t, t: *mut uv_timer_t) -> c_int; + pub fn uv_timer_start(t: *mut uv_timer_t, cb: uv_timer_cb, timeout: libc::uint64_t, repeat: libc::uint64_t) -> c_int; - pub fn uv_timer_stop(handle: *uv_timer_t) -> c_int; + pub fn uv_timer_stop(handle: *mut uv_timer_t) -> c_int; // fs operations - pub fn uv_fs_open(loop_ptr: *uv_loop_t, req: *uv_fs_t, path: *c_char, - flags: c_int, mode: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_unlink(loop_ptr: *uv_loop_t, req: *uv_fs_t, path: *c_char, - cb: uv_fs_cb) -> c_int; - pub fn uv_fs_write(l: *uv_loop_t, req: *uv_fs_t, fd: c_int, - bufs: *uv_buf_t, nbufs: c_uint, + pub fn uv_fs_open(loop_ptr: *mut uv_loop_t, req: *mut uv_fs_t, + path: *const c_char, flags: c_int, mode: c_int, + cb: uv_fs_cb) -> c_int; + pub fn uv_fs_unlink(loop_ptr: *mut uv_loop_t, req: *mut uv_fs_t, + path: *const c_char, cb: uv_fs_cb) -> c_int; + pub fn uv_fs_write(l: *mut uv_loop_t, req: *mut uv_fs_t, fd: c_int, + bufs: *const uv_buf_t, nbufs: c_uint, offset: i64, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_read(l: *uv_loop_t, req: *uv_fs_t, fd: c_int, - bufs: *uv_buf_t, nbufs: c_uint, + pub fn uv_fs_read(l: *mut uv_loop_t, req: *mut uv_fs_t, fd: c_int, + bufs: *mut uv_buf_t, nbufs: c_uint, offset: i64, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_close(l: *uv_loop_t, req: *uv_fs_t, fd: c_int, + pub fn uv_fs_close(l: *mut uv_loop_t, req: *mut uv_fs_t, fd: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_stat(l: *uv_loop_t, req: *uv_fs_t, path: *c_char, + pub fn uv_fs_stat(l: *mut uv_loop_t, req: *mut uv_fs_t, path: *const c_char, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_fstat(l: *uv_loop_t, req: *uv_fs_t, fd: c_int, + pub fn uv_fs_fstat(l: *mut uv_loop_t, req: *mut uv_fs_t, fd: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_mkdir(l: *uv_loop_t, req: *uv_fs_t, path: *c_char, + pub fn uv_fs_mkdir(l: *mut uv_loop_t, req: *mut uv_fs_t, path: *const c_char, mode: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_rmdir(l: *uv_loop_t, req: *uv_fs_t, path: *c_char, + pub fn uv_fs_rmdir(l: *mut uv_loop_t, req: *mut uv_fs_t, path: *const c_char, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_readdir(l: *uv_loop_t, req: *uv_fs_t, path: *c_char, - flags: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_req_cleanup(req: *uv_fs_t); - pub fn uv_fs_fsync(handle: *uv_loop_t, req: *uv_fs_t, file: c_int, + pub fn uv_fs_readdir(l: *mut uv_loop_t, req: *mut uv_fs_t, + path: *const c_char, flags: c_int, + cb: uv_fs_cb) -> c_int; + pub fn uv_fs_req_cleanup(req: *mut uv_fs_t); + pub fn uv_fs_fsync(handle: *mut uv_loop_t, req: *mut uv_fs_t, file: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_fdatasync(handle: *uv_loop_t, req: *uv_fs_t, file: c_int, + pub fn uv_fs_fdatasync(handle: *mut uv_loop_t, req: *mut uv_fs_t, file: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_ftruncate(handle: *uv_loop_t, req: *uv_fs_t, file: c_int, + pub fn uv_fs_ftruncate(handle: *mut uv_loop_t, req: *mut uv_fs_t, file: c_int, offset: i64, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_readlink(handle: *uv_loop_t, req: *uv_fs_t, file: *c_char, - cb: uv_fs_cb) -> c_int; - pub fn uv_fs_symlink(handle: *uv_loop_t, req: *uv_fs_t, src: *c_char, - dst: *c_char, flags: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_rename(handle: *uv_loop_t, req: *uv_fs_t, src: *c_char, - dst: *c_char, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_utime(handle: *uv_loop_t, req: *uv_fs_t, path: *c_char, - atime: c_double, mtime: c_double, + pub fn uv_fs_readlink(handle: *mut uv_loop_t, req: *mut uv_fs_t, + file: *const c_char, cb: uv_fs_cb) -> c_int; + pub fn uv_fs_symlink(handle: *mut uv_loop_t, req: *mut uv_fs_t, + src: *const c_char, dst: *const c_char, flags: c_int, + cb: uv_fs_cb) -> c_int; + pub fn uv_fs_rename(handle: *mut uv_loop_t, req: *mut uv_fs_t, + src: *const c_char, dst: *const c_char, + cb: uv_fs_cb) -> c_int; + pub fn uv_fs_utime(handle: *mut uv_loop_t, req: *mut uv_fs_t, + path: *const c_char, atime: c_double, mtime: c_double, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_link(handle: *uv_loop_t, req: *uv_fs_t, src: *c_char, - dst: *c_char, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_chown(handle: *uv_loop_t, req: *uv_fs_t, src: *c_char, + pub fn uv_fs_link(handle: *mut uv_loop_t, req: *mut uv_fs_t, + src: *const c_char, dst: *const c_char, + cb: uv_fs_cb) -> c_int; + pub fn uv_fs_chown(handle: *mut uv_loop_t, req: *mut uv_fs_t, src: *const c_char, uid: uv_uid_t, gid: uv_gid_t, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_chmod(handle: *uv_loop_t, req: *uv_fs_t, path: *c_char, - mode: c_int, cb: uv_fs_cb) -> c_int; - pub fn uv_fs_lstat(handle: *uv_loop_t, req: *uv_fs_t, file: *c_char, - cb: uv_fs_cb) -> c_int; + pub fn uv_fs_chmod(handle: *mut uv_loop_t, req: *mut uv_fs_t, + path: *const c_char, mode: c_int, cb: uv_fs_cb) -> c_int; + pub fn uv_fs_lstat(handle: *mut uv_loop_t, req: *mut uv_fs_t, + file: *const c_char, cb: uv_fs_cb) -> c_int; // getaddrinfo - pub fn uv_getaddrinfo(loop_: *uv_loop_t, req: *uv_getaddrinfo_t, + pub fn uv_getaddrinfo(loop_: *mut uv_loop_t, req: *mut uv_getaddrinfo_t, getaddrinfo_cb: uv_getaddrinfo_cb, - node: *c_char, service: *c_char, - hints: *addrinfo) -> c_int; - pub fn uv_freeaddrinfo(ai: *addrinfo); + node: *const c_char, service: *const c_char, + hints: *const addrinfo) -> c_int; + pub fn uv_freeaddrinfo(ai: *mut addrinfo); // process spawning - pub fn uv_spawn(loop_ptr: *uv_loop_t, outptr: *uv_process_t, - options: *uv_process_options_t) -> c_int; - pub fn uv_process_kill(p: *uv_process_t, signum: c_int) -> c_int; + pub fn uv_spawn(loop_ptr: *mut uv_loop_t, outptr: *mut uv_process_t, + options: *mut uv_process_options_t) -> c_int; + pub fn uv_process_kill(p: *mut uv_process_t, signum: c_int) -> c_int; pub fn uv_kill(pid: c_int, signum: c_int) -> c_int; // pipes - pub fn uv_pipe_init(l: *uv_loop_t, p: *uv_pipe_t, ipc: c_int) -> c_int; - pub fn uv_pipe_open(pipe: *uv_pipe_t, file: c_int) -> c_int; - pub fn uv_pipe_bind(pipe: *uv_pipe_t, name: *c_char) -> c_int; - pub fn uv_pipe_connect(req: *uv_connect_t, handle: *uv_pipe_t, - name: *c_char, cb: uv_connect_cb); + pub fn uv_pipe_init(l: *mut uv_loop_t, p: *mut uv_pipe_t, + ipc: c_int) -> c_int; + pub fn uv_pipe_open(pipe: *mut uv_pipe_t, file: c_int) -> c_int; + pub fn uv_pipe_bind(pipe: *mut uv_pipe_t, name: *const c_char) -> c_int; + pub fn uv_pipe_connect(req: *mut uv_connect_t, handle: *mut uv_pipe_t, + name: *const c_char, cb: uv_connect_cb); // tty - pub fn uv_tty_init(l: *uv_loop_t, tty: *uv_tty_t, fd: c_int, + pub fn uv_tty_init(l: *mut uv_loop_t, tty: *mut uv_tty_t, fd: c_int, readable: c_int) -> c_int; - pub fn uv_tty_set_mode(tty: *uv_tty_t, mode: c_int) -> c_int; - pub fn uv_tty_get_winsize(tty: *uv_tty_t, width: *c_int, - height: *c_int) -> c_int; + pub fn uv_tty_set_mode(tty: *mut uv_tty_t, mode: c_int) -> c_int; + pub fn uv_tty_get_winsize(tty: *mut uv_tty_t, + width: *mut c_int, + height: *mut c_int) -> c_int; // signals - pub fn uv_signal_init(loop_: *uv_loop_t, handle: *uv_signal_t) -> c_int; - pub fn uv_signal_start(h: *uv_signal_t, cb: uv_signal_cb, + pub fn uv_signal_init(loop_: *mut uv_loop_t, + handle: *mut uv_signal_t) -> c_int; + pub fn uv_signal_start(h: *mut uv_signal_t, cb: uv_signal_cb, signum: c_int) -> c_int; - pub fn uv_signal_stop(handle: *uv_signal_t) -> c_int; + pub fn uv_signal_stop(handle: *mut uv_signal_t) -> c_int; } // libuv requires other native libraries on various platforms. These are all diff --git a/src/libsemver/lib.rs b/src/libsemver/lib.rs index c36de052cb4..fc8aa8ac257 100644 --- a/src/libsemver/lib.rs +++ b/src/libsemver/lib.rs @@ -55,12 +55,12 @@ pub enum Identifier { impl cmp::PartialOrd for Identifier { #[inline] - fn lt(&self, other: &Identifier) -> bool { + fn partial_cmp(&self, other: &Identifier) -> Option<Ordering> { match (self, other) { - (&Numeric(a), &Numeric(b)) => a < b, - (&Numeric(_), _) => true, - (&AlphaNumeric(ref a), &AlphaNumeric(ref b)) => *a < *b, - (&AlphaNumeric(_), _) => false + (&Numeric(a), &Numeric(ref b)) => a.partial_cmp(b), + (&Numeric(_), _) => Some(Less), + (&AlphaNumeric(ref a), &AlphaNumeric(ref b)) => a.partial_cmp(b), + (&AlphaNumeric(_), _) => Some(Greater) } } } @@ -130,30 +130,31 @@ impl cmp::PartialEq for Version { impl cmp::PartialOrd for Version { #[inline] - fn lt(&self, other: &Version) -> bool { - - self.major < other.major || - - (self.major == other.major && - self.minor < other.minor) || - - (self.major == other.major && - self.minor == other.minor && - self.patch < other.patch) || - - (self.major == other.major && - self.minor == other.minor && - self.patch == other.patch && - // NB: semver spec says 0.0.0-pre < 0.0.0 - // but the version of ord defined for vec - // says that [] < [pre], so we alter it - // here. - (match (self.pre.len(), other.pre.len()) { - (0, 0) => false, - (0, _) => false, - (_, 0) => true, - (_, _) => self.pre < other.pre - })) + fn partial_cmp(&self, other: &Version) -> Option<Ordering> { + match self.major.partial_cmp(&other.major) { + Some(Equal) => {} + r => return r, + } + + match self.minor.partial_cmp(&other.minor) { + Some(Equal) => {} + r => return r, + } + + match self.patch.partial_cmp(&other.patch) { + Some(Equal) => {} + r => return r, + } + + // NB: semver spec says 0.0.0-pre < 0.0.0 + // but the version of ord defined for vec + // says that [] < [pre] so we alter it here + match (self.pre.len(), other.pre.len()) { + (0, 0) => Some(Equal), + (0, _) => Some(Greater), + (_, 0) => Some(Less), + (_, _) => self.pre.partial_cmp(&other.pre) + } } } diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index ee1e836112e..63cfbd6d9aa 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -208,7 +208,7 @@ impl<'a> FromBase64 for &'a str { fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> { let mut r = Vec::new(); let mut buf: u32 = 0; - let mut modulus = 0; + let mut modulus = 0i; let mut it = self.bytes().enumerate(); for (idx, byte) in it { diff --git a/src/libserialize/ebml.rs b/src/libserialize/ebml.rs index efee29212e9..dfce1eeb832 100644 --- a/src/libserialize/ebml.rs +++ b/src/libserialize/ebml.rs @@ -182,7 +182,7 @@ pub mod reader { ]; unsafe { - let ptr = data.as_ptr().offset(start as int) as *u32; + let ptr = data.as_ptr().offset(start as int) as *const u32; let val = Int::from_be(*ptr); let i = (val >> 28u) as uint; diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 2fccbc2fcaf..51fab7b1354 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -104,7 +104,7 @@ impl<'a> FromHex for &'a str { fn from_hex(&self) -> Result<Vec<u8>, FromHexError> { // This may be an overestimate if there is any whitespace let mut b = Vec::with_capacity(self.len() / 2); - let mut modulus = 0; + let mut modulus = 0i; let mut buf = 0u8; for (idx, byte) in self.bytes().enumerate() { diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 9c91bd4b7e1..832bc9c4e10 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -20,12 +20,19 @@ JSON parsing and serialization # What is JSON? JSON (JavaScript Object Notation) is a way to write data in Javascript. -Like XML it allows one to encode structured data in a text format that can be read by humans easily. -Its native compatibility with JavaScript and its simple syntax make it used widely. +Like XML, it allows to encode structured data in a text format that can be easily read by humans. +Its simple syntax and native compatibility with JavaScript have made it a widely used format. + +Data types that can be encoded are JavaScript types (see the `Json` enum for more details): + +* `Boolean`: equivalent to rust's `bool` +* `Number`: equivalent to rust's `f64` +* `String`: equivalent to rust's `String` +* `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the same +array +* `Object`: equivalent to rust's `Treemap<String, json::Json>` +* `Null` -Json data are encoded in a form of "key":"value". -Data types that can be encoded are JavaScript types : -boolean (`true` or `false`), number (`f64`), string, array, object, null. An object is a series of string keys mapping to values, in `"key": value` format. Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }). A simple JSON document encoding a person, his/her age, address and phone numbers could look like: @@ -49,105 +56,20 @@ A simple JSON document encoding a person, his/her age, address and phone numbers # Rust Type-based Encoding and Decoding -Rust provides a mechanism for low boilerplate encoding & decoding -of values to and from JSON via the serialization API. +Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via +the serialization API. To be able to encode a piece of data, it must implement the `serialize::Encodable` trait. To be able to decode a piece of data, it must implement the `serialize::Decodable` trait. -The Rust compiler provides an annotation to automatically generate -the code for these traits: `#[deriving(Decodable, Encodable)]` - -To encode using Encodable : - -```rust -use std::io; -use serialize::{json, Encodable}; +The Rust compiler provides an annotation to automatically generate the code for these traits: +`#[deriving(Decodable, Encodable)]` - #[deriving(Encodable)] - pub struct TestStruct { - data_str: String, - } - -fn main() { - let to_encode_object = TestStruct{data_str:"example of string to encode".to_string()}; - let mut m = io::MemWriter::new(); - { - let mut encoder = json::Encoder::new(&mut m as &mut Writer); - match to_encode_object.encode(&mut encoder) { - Ok(()) => (), - Err(e) => fail!("json encoding error: {}", e) - }; - } -} -``` - -Two wrapper functions are provided to encode a Encodable object -into a string (String) or buffer (vec![u8]): `str_encode(&m)` and `buffer_encode(&m)`. - -```rust -use serialize::json; -let to_encode_object = "example of string to encode".to_string(); -let encoded_str: String = json::Encoder::str_encode(&to_encode_object); -``` - -JSON API provide an enum `json::Json` and a trait `ToJson` to encode object. -The trait `ToJson` encode object into a container `json::Json` and the API provide writer -to encode them into a stream or a string ... +The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects. +The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value. +A `json::Json` value can be encoded as a string or buffer using the functions described above. +You can also use the `json::Encoder` object, which implements the `Encoder` trait. When using `ToJson` the `Encodable` trait implementation is not mandatory. -A basic `ToJson` example using a TreeMap of attribute name / attribute value: - - -```rust -use std::collections::TreeMap; -use serialize::json; -use serialize::json::ToJson; - -pub struct MyStruct { - attr1: u8, - attr2: String, -} - -impl ToJson for MyStruct { - fn to_json( &self ) -> json::Json { - let mut d = box TreeMap::new(); - d.insert("attr1".to_string(), self.attr1.to_json()); - d.insert("attr2".to_string(), self.attr2.to_json()); - json::Object(d) - } -} - -fn main() { - let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_string()}; - let tjson: json::Json = test2.to_json(); - let json_str: String = tjson.to_str().into_string(); -} -``` - -To decode a JSON string using `Decodable` trait : - -```rust -extern crate serialize; -use serialize::{json, Decodable}; - -#[deriving(Decodable)] -pub struct MyStruct { - attr1: u8, - attr2: String, -} - -fn main() { - let json_str_to_decode: String = - "{\"attr1\":1,\"attr2\":\"toto\"}".to_string(); - let json_object = json::from_str(json_str_to_decode.as_slice()); - let mut decoder = json::Decoder::new(json_object.unwrap()); - let decoded_object: MyStruct = match Decodable::decode(&mut decoder) { - Ok(v) => v, - Err(e) => fail!("Decoding error: {}", e) - }; // create the final object -} -``` - # Examples of use ## Using Autoserialization @@ -157,41 +79,37 @@ using the serialization API, using the derived serialization code. ```rust extern crate serialize; -use serialize::{json, Encodable, Decodable}; +use serialize::json; - #[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl. - pub struct TestStruct1 { +#[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl. +pub struct TestStruct1 { data_int: u8, data_str: String, data_vector: Vec<u8>, - } +} -// To serialize use the `json::str_encode` to encode an object in a string. -// It calls the generated `Encodable` impl. fn main() { - let to_encode_object = TestStruct1 + let object = TestStruct1 {data_int: 1, data_str:"toto".to_string(), data_vector:vec![2,3,4,5]}; - let encoded_str: String = json::Encoder::str_encode(&to_encode_object); - // To deserialize use the `json::from_str` and `json::Decoder` + // Serialize using `json::encode` + let encoded = json::encode(&object); - let json_object = json::from_str(encoded_str.as_slice()); - let mut decoder = json::Decoder::new(json_object.unwrap()); - let decoded1: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); // create the final object + // Deserialize using `json::decode` + let decoded: TestStruct1 = json::decode(encoded.as_slice()).unwrap(); } ``` ## Using `ToJson` -This example uses the ToJson impl to deserialize the JSON string. -Example of `ToJson` trait implementation for TestStruct1. +This example uses the `ToJson` trait to generate the JSON string. ```rust use std::collections::TreeMap; use serialize::json::ToJson; -use serialize::{json, Encodable, Decodable}; +use serialize::json; -#[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl. +#[deriving(Decodable)] pub struct TestStruct1 { data_int: u8, data_str: String, @@ -200,7 +118,7 @@ pub struct TestStruct1 { impl ToJson for TestStruct1 { fn to_json( &self ) -> json::Json { - let mut d = box TreeMap::new(); + let mut d = TreeMap::new(); d.insert("data_int".to_string(), self.data_int.to_json()); d.insert("data_str".to_string(), self.data_str.to_json()); d.insert("data_vector".to_string(), self.data_vector.to_json()); @@ -209,48 +127,38 @@ impl ToJson for TestStruct1 { } fn main() { - // Serialization using our impl of to_json - - let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_string(), - data_vector:vec![2,3,4,5]}; + // 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().into_string(); + let json_str: String = tjson.to_str(); - // Deserialize like before. - - let mut decoder = - json::Decoder::new(json::from_str(json_str.as_slice()).unwrap()); - // create the final object - let decoded2: TestStruct1 = Decodable::decode(&mut decoder).unwrap(); + // Deserialize like before + let decoded: TestStruct1 = json::decode(json_str.as_slice()).unwrap(); } ``` */ -use std::char; +use std; use std::collections::{HashMap, TreeMap}; -use std::f64; -use std::fmt; +use std::{char, f64, fmt, io, num, str}; use std::io::MemWriter; -use std::io; -use std::mem::{swap,transmute}; +use std::mem::{swap, transmute}; use std::num::{FPNaN, FPInfinite}; -use std::num; use std::str::ScalarValue; -use std::str; use std::string::String; use std::vec::Vec; use Encodable; /// Represents a json value -#[deriving(Clone, PartialEq)] +#[deriving(Clone, PartialEq, PartialOrd)] pub enum Json { Number(f64), String(String), Boolean(bool), List(List), - Object(Box<Object>), + Object(Object), Null, } @@ -318,13 +226,29 @@ pub fn error_str(error: ErrorCode) -> &'static str { } } +/// Shortcut function to decode a JSON `&str` into an object +pub fn decode<T: ::Decodable<Decoder, DecoderError>>(s: &str) -> DecodeResult<T> { + let json = match from_str(s) { + Ok(x) => x, + Err(e) => return Err(ParseError(e)) + }; + + let mut decoder = Decoder::new(json); + ::Decodable::decode(&mut decoder) +} + +/// Shortcut function to encode a `T` into a JSON `String` +pub fn encode<'a, T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String { + let buff = Encoder::buffer_encode(object); + str::from_utf8_owned(buff).unwrap() +} + impl fmt::Show for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error_str(*self).fmt(f) } } - fn io_error_to_error(io: io::IoError) -> ParserError { IoError(io.kind, io.desc) } @@ -363,41 +287,40 @@ fn spaces(n: uint) -> String { /// A structure for implementing serialization to JSON. pub struct Encoder<'a> { - wr: &'a mut io::Writer, + writer: &'a mut io::Writer, } impl<'a> Encoder<'a> { /// Creates a new JSON encoder whose output will be written to the writer /// specified. - pub fn new<'a>(wr: &'a mut io::Writer) -> Encoder<'a> { - Encoder { wr: wr } + pub fn new(writer: &'a mut io::Writer) -> Encoder<'a> { + Encoder { writer: writer } } /// Encode the specified struct into a json [u8] - pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8> { - //Serialize the object in a string using a writer + pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(object: &T) -> Vec<u8> { + //Serialize the object in a string using a writer let mut m = MemWriter::new(); // FIXME(14302) remove the transmute and unsafe block. unsafe { let mut encoder = Encoder::new(&mut m as &mut io::Writer); // MemWriter never Errs - let _ = to_encode_object.encode(transmute(&mut encoder)); + let _ = object.encode(transmute(&mut encoder)); } m.unwrap() } /// Encode the specified struct into a json str - pub fn str_encode<T:Encodable<Encoder<'a>, - io::IoError>>( - to_encode_object: &T) - -> String { - let buff = Encoder::buffer_encode(to_encode_object); - str::from_utf8(buff.as_slice()).unwrap().to_string() + /// + /// Note: this function is deprecated. Consider using `json::encode` instead. + #[deprecated = "Replaced by `json::encode`"] + pub fn str_encode<T: Encodable<Encoder<'a>, io::IoError>>(object: &T) -> String { + encode(object) } } impl<'a> ::Encoder<io::IoError> for Encoder<'a> { - fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") } + fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") } fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) } fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) } @@ -413,14 +336,14 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { fn emit_bool(&mut self, v: bool) -> EncodeResult { if v { - write!(self.wr, "true") + write!(self.writer, "true") } else { - write!(self.wr, "false") + write!(self.writer, "false") } } fn emit_f64(&mut self, v: f64) -> EncodeResult { - write!(self.wr, "{}", fmt_number_or_null(v)) + write!(self.writer, "{}", fmt_number_or_null(v)) } fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) } @@ -428,12 +351,12 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { self.emit_str(str::from_char(v).as_slice()) } fn emit_str(&mut self, v: &str) -> EncodeResult { - write!(self.wr, "{}", escape_str(v)) + write!(self.writer, "{}", escape_str(v)) } - fn emit_enum(&mut self, - _name: &str, - f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { f(self) } + fn emit_enum(&mut self, _name: &str, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { + f(self) + } fn emit_enum_variant(&mut self, name: &str, @@ -444,13 +367,13 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { // Bunny => "Bunny" // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]} if cnt == 0 { - write!(self.wr, "{}", escape_str(name)) + write!(self.writer, "{}", escape_str(name)) } else { - try!(write!(self.wr, "{{\"variant\":")); - try!(write!(self.wr, "{}", escape_str(name))); - try!(write!(self.wr, ",\"fields\":[")); + try!(write!(self.writer, "{{\"variant\":")); + try!(write!(self.writer, "{}", escape_str(name))); + try!(write!(self.writer, ",\"fields\":[")); try!(f(self)); - write!(self.wr, "]}}") + write!(self.writer, "]}}") } } @@ -458,7 +381,7 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { if idx != 0 { - try!(write!(self.wr, ",")); + try!(write!(self.writer, ",")); } f(self) } @@ -482,17 +405,17 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { _: &str, _: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - try!(write!(self.wr, "{{")); + try!(write!(self.writer, "{{")); try!(f(self)); - write!(self.wr, "}}") + write!(self.writer, "}}") } fn emit_struct_field(&mut self, name: &str, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - if idx != 0 { try!(write!(self.wr, ",")); } - try!(write!(self.wr, "{}:", escape_str(name))); + if idx != 0 { try!(write!(self.writer, ",")); } + try!(write!(self.writer, "{}:", escape_str(name))); f(self) } @@ -526,29 +449,28 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { } fn emit_seq(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - try!(write!(self.wr, "[")); + try!(write!(self.writer, "[")); try!(f(self)); - write!(self.wr, "]") + write!(self.writer, "]") } fn emit_seq_elt(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { if idx != 0 { - try!(write!(self.wr, ",")); + try!(write!(self.writer, ",")); } f(self) } fn emit_map(&mut self, _len: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - try!(write!(self.wr, "{{")); + try!(write!(self.writer, "{{")); try!(f(self)); - write!(self.wr, "}}") + write!(self.writer, "}}") } fn emit_map_elt_key(&mut self, idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - use std::str::from_utf8; - if idx != 0 { try!(write!(self.wr, ",")) } + if idx != 0 { try!(write!(self.writer, ",")) } // ref #12967, make sure to wrap a key in double quotes, // in the event that its of a type that omits them (eg numbers) let mut buf = MemWriter::new(); @@ -557,20 +479,19 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { let mut check_encoder = Encoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let buf = buf.unwrap(); - let out = from_utf8(buf.as_slice()).unwrap(); - let needs_wrapping = out.char_at(0) != '"' && - out.char_at_reverse(out.len()) != '"'; - if needs_wrapping { try!(write!(self.wr, "\"")); } + let out = str::from_utf8_owned(buf.unwrap()).unwrap(); + let out = out.as_slice(); + let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; + if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); - if needs_wrapping { try!(write!(self.wr, "\"")); } + if needs_wrapping { try!(write!(self.writer, "\"")); } Ok(()) } fn emit_map_elt_val(&mut self, _idx: uint, f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult { - try!(write!(self.wr, ":")); + try!(write!(self.writer, ":")); f(self) } } @@ -578,22 +499,19 @@ impl<'a> ::Encoder<io::IoError> for Encoder<'a> { /// Another encoder for JSON, but prints out human-readable JSON instead of /// compact data pub struct PrettyEncoder<'a> { - wr: &'a mut io::Writer, + writer: &'a mut io::Writer, indent: uint, } impl<'a> PrettyEncoder<'a> { /// Creates a new encoder whose output will be written to the specified writer - pub fn new<'a>(wr: &'a mut io::Writer) -> PrettyEncoder<'a> { - PrettyEncoder { - wr: wr, - indent: 0, - } + pub fn new<'a>(writer: &'a mut io::Writer) -> PrettyEncoder<'a> { + PrettyEncoder { writer: writer, indent: 0 } } } impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { - fn emit_nil(&mut self) -> EncodeResult { write!(self.wr, "null") } + fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") } fn emit_uint(&mut self, v: uint) -> EncodeResult { self.emit_f64(v as f64) } fn emit_u64(&mut self, v: u64) -> EncodeResult { self.emit_f64(v as f64) } @@ -609,14 +527,14 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { fn emit_bool(&mut self, v: bool) -> EncodeResult { if v { - write!(self.wr, "true") + write!(self.writer, "true") } else { - write!(self.wr, "false") + write!(self.writer, "false") } } fn emit_f64(&mut self, v: f64) -> EncodeResult { - write!(self.wr, "{}", fmt_number_or_null(v)) + write!(self.writer, "{}", fmt_number_or_null(v)) } fn emit_f32(&mut self, v: f32) -> EncodeResult { self.emit_f64(v as f64) @@ -626,7 +544,7 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { self.emit_str(str::from_char(v).as_slice()) } fn emit_str(&mut self, v: &str) -> EncodeResult { - write!(self.wr, "{}", escape_str(v)) + write!(self.writer, "{}", escape_str(v)) } fn emit_enum(&mut self, @@ -641,14 +559,14 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { cnt: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if cnt == 0 { - write!(self.wr, "{}", escape_str(name)) + write!(self.writer, "{}", escape_str(name)) } else { self.indent += 2; - try!(write!(self.wr, "[\n{}{},\n", spaces(self.indent), + try!(write!(self.writer, "[\n{}{},\n", spaces(self.indent), escape_str(name))); try!(f(self)); self.indent -= 2; - write!(self.wr, "\n{}]", spaces(self.indent)) + write!(self.writer, "\n{}]", spaces(self.indent)) } } @@ -656,9 +574,9 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { idx: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if idx != 0 { - try!(write!(self.wr, ",\n")); + try!(write!(self.writer, ",\n")); } - try!(write!(self.wr, "{}", spaces(self.indent))); + try!(write!(self.writer, "{}", spaces(self.indent))); f(self) } @@ -683,13 +601,13 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { len: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if len == 0 { - write!(self.wr, "{{}}") + write!(self.writer, "{{}}") } else { - try!(write!(self.wr, "{{")); + try!(write!(self.writer, "{{")); self.indent += 2; try!(f(self)); self.indent -= 2; - write!(self.wr, "\n{}}}", spaces(self.indent)) + write!(self.writer, "\n{}}}", spaces(self.indent)) } } @@ -698,11 +616,11 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { idx: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if idx == 0 { - try!(write!(self.wr, "\n")); + try!(write!(self.writer, "\n")); } else { - try!(write!(self.wr, ",\n")); + try!(write!(self.writer, ",\n")); } - try!(write!(self.wr, "{}{}: ", spaces(self.indent), escape_str(name))); + try!(write!(self.writer, "{}{}: ", spaces(self.indent), escape_str(name))); f(self) } @@ -741,13 +659,13 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { len: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if len == 0 { - write!(self.wr, "[]") + write!(self.writer, "[]") } else { - try!(write!(self.wr, "[")); + try!(write!(self.writer, "[")); self.indent += 2; try!(f(self)); self.indent -= 2; - write!(self.wr, "\n{}]", spaces(self.indent)) + write!(self.writer, "\n{}]", spaces(self.indent)) } } @@ -755,11 +673,11 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { idx: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if idx == 0 { - try!(write!(self.wr, "\n")); + try!(write!(self.writer, "\n")); } else { - try!(write!(self.wr, ",\n")); + try!(write!(self.writer, ",\n")); } - try!(write!(self.wr, "{}", spaces(self.indent))); + try!(write!(self.writer, "{}", spaces(self.indent))); f(self) } @@ -767,26 +685,25 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { len: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { if len == 0 { - write!(self.wr, "{{}}") + write!(self.writer, "{{}}") } else { - try!(write!(self.wr, "{{")); + try!(write!(self.writer, "{{")); self.indent += 2; try!(f(self)); self.indent -= 2; - write!(self.wr, "\n{}}}", spaces(self.indent)) + write!(self.writer, "\n{}}}", spaces(self.indent)) } } fn emit_map_elt_key(&mut self, idx: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { - use std::str::from_utf8; if idx == 0 { - try!(write!(self.wr, "\n")); + try!(write!(self.writer, "\n")); } else { - try!(write!(self.wr, ",\n")); + try!(write!(self.writer, ",\n")); } - try!(write!(self.wr, "{}", spaces(self.indent))); + try!(write!(self.writer, "{}", spaces(self.indent))); // ref #12967, make sure to wrap a key in double quotes, // in the event that its of a type that omits them (eg numbers) let mut buf = MemWriter::new(); @@ -795,20 +712,19 @@ impl<'a> ::Encoder<io::IoError> for PrettyEncoder<'a> { let mut check_encoder = PrettyEncoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let buf = buf.unwrap(); - let out = from_utf8(buf.as_slice()).unwrap(); - let needs_wrapping = out.char_at(0) != '"' && - out.char_at_reverse(out.len()) != '"'; - if needs_wrapping { try!(write!(self.wr, "\"")); } + let out = str::from_utf8_owned(buf.unwrap()).unwrap(); + let out = out.as_slice(); + let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; + if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); - if needs_wrapping { try!(write!(self.wr, "\"")); } + if needs_wrapping { try!(write!(self.writer, "\"")); } Ok(()) } fn emit_map_elt_val(&mut self, _idx: uint, f: |&mut PrettyEncoder<'a>| -> EncodeResult) -> EncodeResult { - try!(write!(self.wr, ": ")); + try!(write!(self.writer, ": ")); f(self) } } @@ -827,16 +743,16 @@ impl<E: ::Encoder<S>, S> Encodable<E, S> for Json { } impl Json { - /// Encodes a json value into an io::writer. Uses a single line. - pub fn to_writer(&self, wr: &mut io::Writer) -> EncodeResult { - let mut encoder = Encoder::new(wr); + /// Encodes a json value into an io::writer. Uses a single line. + pub fn to_writer(&self, writer: &mut io::Writer) -> EncodeResult { + let mut encoder = Encoder::new(writer); self.encode(&mut encoder) } /// Encodes a json value into an io::writer. /// Pretty-prints in a more readable format. - pub fn to_pretty_writer(&self, wr: &mut io::Writer) -> EncodeResult { - let mut encoder = PrettyEncoder::new(wr); + pub fn to_pretty_writer(&self, writer: &mut io::Writer) -> EncodeResult { + let mut encoder = PrettyEncoder::new(writer); self.encode(&mut encoder) } @@ -844,7 +760,7 @@ impl Json { pub fn to_pretty_str(&self) -> String { let mut s = MemWriter::new(); self.to_pretty_writer(&mut s as &mut io::Writer).unwrap(); - str::from_utf8(s.unwrap().as_slice()).unwrap().to_string() + str::from_utf8_owned(s.unwrap()).unwrap() } /// If the Json value is an Object, returns the value associated with the provided key. @@ -903,7 +819,7 @@ impl Json { /// Returns None otherwise. pub fn as_object<'a>(&'a self) -> Option<&'a Object> { match self { - &Object(ref map) => Some(&**map), + &Object(ref map) => Some(map), _ => None } } @@ -1038,27 +954,25 @@ enum InternalStackElement { impl Stack { pub fn new() -> Stack { - Stack { - stack: Vec::new(), - str_buffer: Vec::new(), - } + Stack { stack: Vec::new(), str_buffer: Vec::new() } } /// Returns The number of elements in the Stack. pub fn len(&self) -> uint { self.stack.len() } - /// Returns true if the stack is empty, equivalent to self.len() == 0. - pub fn is_empty(&self) -> bool { self.stack.len() == 0 } + /// Returns true if the stack is empty. + pub fn is_empty(&self) -> bool { self.stack.is_empty() } /// Provides access to the StackElement at a given index. /// lower indices are at the bottom of the stack while higher indices are /// at the top. pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> { - return match *self.stack.get(idx) { - InternalIndex(i) => { Index(i) } - InternalKey(start, size) => { - Key(str::from_utf8(self.str_buffer.slice(start as uint, (start+size) as uint)).unwrap()) - } + match *self.stack.get(idx) { + InternalIndex(i) => { Index(i) } + InternalKey(start, size) => { + Key(str::from_utf8( + self.str_buffer.slice(start as uint, start as uint + size as uint)).unwrap()) + } } } @@ -1124,9 +1038,7 @@ impl Stack { match *self.stack.last().unwrap() { InternalKey(_, sz) => { let new_size = self.str_buffer.len() - sz as uint; - unsafe { - self.str_buffer.set_len(new_size); - } + self.str_buffer.truncate(new_size); } InternalIndex(_) => {} } @@ -1146,8 +1058,8 @@ impl Stack { fn bump_index(&mut self) { let len = self.stack.len(); let idx = match *self.stack.last().unwrap() { - InternalIndex(i) => { i + 1 } - _ => { fail!(); } + InternalIndex(i) => { i + 1 } + _ => { fail!(); } }; *self.stack.get_mut(len - 1) = InternalIndex(idx); } @@ -1249,23 +1161,14 @@ impl<T: Iterator<char>> Parser<T> { neg = -1.0; } - let mut res = match self.parse_integer() { - Ok(res) => res, - Err(e) => return Err(e) - }; + let mut res = try!(self.parse_integer()); if self.ch_is('.') { - match self.parse_decimal(res) { - Ok(r) => res = r, - Err(e) => return Err(e) - } + res = try!(self.parse_decimal(res)); } if self.ch_is('e') || self.ch_is('E') { - match self.parse_exponent(res) { - Ok(r) => res = r, - Err(e) => return Err(e) - } + res = try!(self.parse_exponent(res)); } Ok(neg * res) @@ -1301,7 +1204,7 @@ impl<T: Iterator<char>> Parser<T> { Ok(res) } - fn parse_decimal(&mut self, res: f64) -> Result<f64, ParserError> { + fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> { self.bump(); // Make sure a digit follows the decimal place. @@ -1310,7 +1213,6 @@ impl<T: Iterator<char>> Parser<T> { _ => return self.error(InvalidNumber) } - let mut res = res; let mut dec = 1.0; while !self.eof() { match self.ch_or_null() { @@ -1356,7 +1258,7 @@ impl<T: Iterator<char>> Parser<T> { } } - let exp: f64 = num::pow(10u as f64, exp); + let exp = num::pow(10_f64, exp); if neg_exp { res /= exp; } else { @@ -1369,16 +1271,16 @@ impl<T: Iterator<char>> Parser<T> { fn decode_hex_escape(&mut self) -> Result<u16, ParserError> { let mut i = 0u; let mut n = 0u16; - while i < 4u && !self.eof() { + while i < 4 && !self.eof() { self.bump(); n = match self.ch_or_null() { - c @ '0' .. '9' => n * 16_u16 + ((c as u16) - ('0' as u16)), - 'a' | 'A' => n * 16_u16 + 10_u16, - 'b' | 'B' => n * 16_u16 + 11_u16, - 'c' | 'C' => n * 16_u16 + 12_u16, - 'd' | 'D' => n * 16_u16 + 13_u16, - 'e' | 'E' => n * 16_u16 + 14_u16, - 'f' | 'F' => n * 16_u16 + 15_u16, + c @ '0' .. '9' => n * 16 + ((c as u16) - ('0' as u16)), + 'a' | 'A' => n * 16 + 10, + 'b' | 'B' => n * 16 + 11, + 'c' | 'C' => n * 16 + 12, + 'd' | 'D' => n * 16 + 13, + 'e' | 'E' => n * 16 + 14, + 'f' | 'F' => n * 16 + 15, _ => return self.error(InvalidEscape) }; @@ -1386,7 +1288,7 @@ impl<T: Iterator<char>> Parser<T> { } // Error out if we didn't parse 4 digits. - if i != 4u { + if i != 4 { return self.error(InvalidEscape); } @@ -1419,9 +1321,7 @@ impl<T: Iterator<char>> Parser<T> { // Non-BMP characters are encoded as a sequence of // two hex escapes, representing UTF-16 surrogates. n1 @ 0xD800 .. 0xDBFF => { - let c1 = self.next_char(); - let c2 = self.next_char(); - match (c1, c2) { + match (self.next_char(), self.next_char()) { (Some('\\'), Some('u')) => (), _ => return self.error(UnexpectedEndOfHexEscape), } @@ -1636,37 +1536,37 @@ impl<T: Iterator<char>> Parser<T> { } } self.bump(); - return ObjectEnd; + ObjectEnd } else if self.eof() { - return self.error_event(EOFWhileParsingObject); + self.error_event(EOFWhileParsingObject) } else { - return self.error_event(InvalidSyntax); + self.error_event(InvalidSyntax) } } fn parse_value(&mut self) -> JsonEvent { if self.eof() { return self.error_event(EOFWhileParsingValue); } match self.ch_or_null() { - 'n' => { return self.parse_ident("ull", NullValue); } - 't' => { return self.parse_ident("rue", BooleanValue(true)); } - 'f' => { return self.parse_ident("alse", BooleanValue(false)); } - '0' .. '9' | '-' => return match self.parse_number() { + 'n' => { self.parse_ident("ull", NullValue) } + 't' => { self.parse_ident("rue", BooleanValue(true)) } + 'f' => { self.parse_ident("alse", BooleanValue(false)) } + '0' .. '9' | '-' => match self.parse_number() { Ok(f) => NumberValue(f), Err(e) => Error(e), }, - '"' => return match self.parse_str() { + '"' => match self.parse_str() { Ok(s) => StringValue(s), Err(e) => Error(e), }, '[' => { self.bump(); - return ListStart; + ListStart } '{' => { self.bump(); - return ObjectStart; + ObjectStart } - _ => { return self.error_event(InvalidSyntax); } + _ => { self.error_event(InvalidSyntax) } } } @@ -1694,10 +1594,7 @@ pub struct Builder<T> { impl<T: Iterator<char>> Builder<T> { /// Create a JSON Builder. pub fn new(src: T) -> Builder<T> { - Builder { - parser: Parser::new(src), - token: None, - } + Builder { parser: Parser::new(src), token: None, } } // Decode a Json value from a Parser. @@ -1710,7 +1607,7 @@ impl<T: Iterator<char>> Builder<T> { Some(Error(e)) => { return Err(e); } ref tok => { fail!("unexpected token {}", tok.clone()); } } - return result; + result } fn bump(&mut self) { @@ -1755,9 +1652,9 @@ impl<T: Iterator<char>> Builder<T> { fn build_object(&mut self) -> Result<Json, BuilderError> { self.bump(); - let mut values = box TreeMap::new(); + let mut values = TreeMap::new(); - while self.token != None { + loop { match self.token { Some(ObjectEnd) => { return Ok(Object(values)); } Some(Error(e)) => { return Err(e); } @@ -1778,16 +1675,15 @@ impl<T: Iterator<char>> Builder<T> { } } - /// Decodes a json value from an `&mut io::Reader` pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> { let contents = match rdr.read_to_end() { Ok(c) => c, Err(e) => return Err(io_error_to_error(e)) }; - let s = match str::from_utf8(contents.as_slice()) { - Some(s) => s.to_string(), - None => return Err(SyntaxError(NotUtf8, 0, 0)) + let s = match str::from_utf8_owned(contents) { + Ok(s) => s, + _ => return Err(SyntaxError(NotUtf8, 0, 0)) }; let mut builder = Builder::new(s.as_slice().chars()); builder.build() @@ -1796,7 +1692,7 @@ pub fn from_reader(rdr: &mut io::Reader) -> Result<Json, BuilderError> { /// Decodes a json value from a string pub fn from_str(s: &str) -> Result<Json, BuilderError> { let mut builder = Builder::new(s.chars()); - return builder.build(); + builder.build() } /// A structure to decode JSON to values in rust. @@ -1807,9 +1703,7 @@ pub struct Decoder { impl Decoder { /// Creates a new decoder instance for decoding the specified JSON value. pub fn new(json: Json) -> Decoder { - Decoder { - stack: vec!(json), - } + Decoder { stack: vec![json] } } } @@ -1841,8 +1735,7 @@ macro_rules! expect( impl ::Decoder<DecoderError> for Decoder { fn read_nil(&mut self) -> DecodeResult<()> { debug!("read_nil"); - try!(expect!(self.pop(), Null)); - Ok(()) + expect!(self.pop(), Null) } fn read_u64(&mut self) -> DecodeResult<u64 > { Ok(try!(self.read_f64()) as u64) } @@ -1859,28 +1752,24 @@ impl ::Decoder<DecoderError> for Decoder { fn read_bool(&mut self) -> DecodeResult<bool> { debug!("read_bool"); - Ok(try!(expect!(self.pop(), Boolean))) + expect!(self.pop(), Boolean) } fn read_f64(&mut self) -> DecodeResult<f64> { - use std::from_str::FromStr; debug!("read_f64"); match self.pop() { Number(f) => Ok(f), String(s) => { // re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc) - // is going to have a string here, as per JSON spec.. - Ok(FromStr::from_str(s.as_slice()).unwrap()) + // is going to have a string here, as per JSON spec. + Ok(std::from_str::from_str(s.as_slice()).unwrap()) }, Null => Ok(f64::NAN), - value => { - Err(ExpectedError("Number".to_string(), - format!("{}", value))) - } + value => Err(ExpectedError("Number".to_string(), format!("{}", value))) } } - fn read_f32(&mut self) -> DecodeResult<f32> { Ok(try!(self.read_f64()) as f32) } + fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) } fn read_char(&mut self) -> DecodeResult<char> { let s = try!(self.read_str()); @@ -1892,13 +1781,12 @@ impl ::Decoder<DecoderError> for Decoder { _ => () } } - Err(ExpectedError("single character string".to_string(), - format!("{}", s))) + Err(ExpectedError("single character string".to_string(), format!("{}", s))) } fn read_str(&mut self) -> DecodeResult<String> { debug!("read_str"); - Ok(try!(expect!(self.pop(), String))) + expect!(self.pop(), String) } fn read_enum<T>(&mut self, @@ -1919,8 +1807,7 @@ impl ::Decoder<DecoderError> for Decoder { let n = match o.pop(&"variant".to_string()) { Some(String(s)) => s, Some(val) => { - return Err(ExpectedError("String".to_string(), - format!("{}", val))) + return Err(ExpectedError("String".to_string(), format!("{}", val))) } None => { return Err(MissingFieldError("variant".to_string())) @@ -1929,12 +1816,11 @@ impl ::Decoder<DecoderError> for Decoder { match o.pop(&"fields".to_string()) { Some(List(l)) => { for field in l.move_iter().rev() { - self.stack.push(field.clone()); + self.stack.push(field); } }, Some(val) => { - return Err(ExpectedError("List".to_string(), - format!("{}", val))) + return Err(ExpectedError("List".to_string(), format!("{}", val))) } None => { return Err(MissingFieldError("fields".to_string())) @@ -1943,14 +1829,11 @@ impl ::Decoder<DecoderError> for Decoder { n } json => { - return Err(ExpectedError("String or Object".to_string(), - format!("{}", json))) + return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) } }; let idx = match names.iter() - .position(|n| { - str::eq_slice(*n, name.as_slice()) - }) { + .position(|n| str::eq_slice(*n, name.as_slice())) { Some(idx) => idx, None => return Err(UnknownVariantError(name)) }; @@ -2087,110 +1970,24 @@ impl ::Decoder<DecoderError> for Decoder { } } -/// Test if two json values are less than one another -impl PartialOrd for Json { - fn lt(&self, other: &Json) -> bool { - match *self { - Number(f0) => { - match *other { - Number(f1) => f0 < f1, - String(_) | Boolean(_) | List(_) | Object(_) | - Null => true - } - } - - String(ref s0) => { - match *other { - Number(_) => false, - String(ref s1) => s0 < s1, - Boolean(_) | List(_) | Object(_) | Null => true - } - } - - Boolean(b0) => { - match *other { - Number(_) | String(_) => false, - Boolean(b1) => b0 < b1, - List(_) | Object(_) | Null => true - } - } - - List(ref l0) => { - match *other { - Number(_) | String(_) | Boolean(_) => false, - List(ref l1) => (*l0) < (*l1), - Object(_) | Null => true - } - } - - Object(ref d0) => { - match *other { - Number(_) | String(_) | Boolean(_) | List(_) => false, - Object(ref d1) => d0 < d1, - Null => true - } - } - - Null => { - match *other { - Number(_) | String(_) | Boolean(_) | List(_) | - Object(_) => - false, - Null => true - } - } - } - } -} - /// A trait for converting values to JSON pub trait ToJson { /// Converts the value of `self` to an instance of JSON fn to_json(&self) -> Json; } -impl ToJson for Json { - fn to_json(&self) -> Json { (*self).clone() } -} - -impl ToJson for int { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for i8 { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for i16 { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for i32 { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for i64 { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for uint { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for u8 { - fn to_json(&self) -> Json { Number(*self as f64) } -} +macro_rules! to_json_impl( + ($($t:ty), +) => ( + $(impl ToJson for $t { + fn to_json(&self) -> Json { Number(*self as f64) } + })+ + ) +) -impl ToJson for u16 { - fn to_json(&self) -> Json { Number(*self as f64) } -} +to_json_impl!(int, i8, i16, i32, i64, uint, u8, u16, u32, u64) -impl ToJson for u32 { - fn to_json(&self) -> Json { Number(*self as f64) } -} - -impl ToJson for u64 { - fn to_json(&self) -> Json { Number(*self as f64) } +impl ToJson for Json { + fn to_json(&self) -> Json { self.clone() } } impl ToJson for f32 { @@ -2201,7 +1998,7 @@ impl ToJson for f64 { fn to_json(&self) -> Json { match self.classify() { FPNaN | FPInfinite => Null, - _ => Number(*self) + _ => Number(*self) } } } @@ -2218,59 +2015,71 @@ impl ToJson for String { fn to_json(&self) -> Json { String((*self).clone()) } } -impl<A:ToJson,B:ToJson> ToJson for (A, B) { - fn to_json(&self) -> Json { - match *self { - (ref a, ref b) => { - List(vec![a.to_json(), b.to_json()]) - } - } - } -} +macro_rules! tuple_impl { + // use variables to indicate the arity of the tuple + ($($tyvar:ident),* ) => { + // the trailing commas are for the 1 tuple + impl< + $( $tyvar : ToJson ),* + > ToJson for ( $( $tyvar ),* , ) { -impl<A:ToJson,B:ToJson,C:ToJson> ToJson for (A, B, C) { - fn to_json(&self) -> Json { - match *self { - (ref a, ref b, ref c) => { - List(vec![a.to_json(), b.to_json(), c.to_json()]) - } + #[inline] + #[allow(uppercase_variables)] + fn to_json(&self) -> Json { + match *self { + ($(ref $tyvar),*,) => List(vec![$($tyvar.to_json()),*]) + } + } } } } -impl<'a, A:ToJson> ToJson for &'a [A] { +tuple_impl!{A} +tuple_impl!{A, B} +tuple_impl!{A, B, C} +tuple_impl!{A, B, C, D} +tuple_impl!{A, B, C, D, E} +tuple_impl!{A, B, C, D, E, F} +tuple_impl!{A, B, C, D, E, F, G} +tuple_impl!{A, B, C, D, E, F, G, H} +tuple_impl!{A, B, C, D, E, F, G, H, I} +tuple_impl!{A, B, C, D, E, F, G, H, I, J} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} +tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} + +impl<'a, A: ToJson> ToJson for &'a [A] { fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) } } -impl<A:ToJson> ToJson for Vec<A> { +impl<A: ToJson> ToJson for Vec<A> { fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) } } -impl<A:ToJson> ToJson for TreeMap<String, A> { +impl<A: ToJson> ToJson for TreeMap<String, A> { fn to_json(&self) -> Json { let mut d = TreeMap::new(); for (key, value) in self.iter() { d.insert((*key).clone(), value.to_json()); } - Object(box d) + Object(d) } } -impl<A:ToJson> ToJson for HashMap<String, A> { +impl<A: ToJson> ToJson for HashMap<String, A> { fn to_json(&self) -> Json { let mut d = TreeMap::new(); for (key, value) in self.iter() { d.insert((*key).clone(), value.to_json()); } - Object(box d) + Object(d) } } impl<A:ToJson> ToJson for Option<A> { fn to_json(&self) -> Json { match *self { - None => Null, - Some(ref value) => value.to_json() + None => Null, + Some(ref value) => value.to_json() } } } @@ -2282,6 +2091,12 @@ impl fmt::Show for Json { } } +impl std::from_str::FromStr for Json { + fn from_str(s: &str) -> Option<Json> { + from_str(s).ok() + } +} + #[cfg(test)] mod tests { extern crate test; @@ -2296,9 +2111,7 @@ mod tests { InvalidSyntax, InvalidNumber, EOFWhileParsingObject, EOFWhileParsingList, EOFWhileParsingValue, EOFWhileParsingString, KeyMustBeAString, ExpectedColon, TrailingCharacters}; - use std::f32; - use std::f64; - use std::io; + use std::{f32, f64, io}; use std::collections::TreeMap; #[deriving(PartialEq, Encodable, Decodable, Show)] @@ -2320,7 +2133,7 @@ mod tests { } fn mk_object(items: &[(String, Json)]) -> Json { - let mut d = box TreeMap::new(); + let mut d = TreeMap::new(); for item in items.iter() { match *item { @@ -2332,6 +2145,12 @@ mod tests { } #[test] + fn test_from_str_trait() { + let s = "null"; + assert!(::std::from_str::from_str::<Json>(s).unwrap() == from_str(s).unwrap()); + } + + #[test] fn test_write_null() { assert_eq!(Null.to_str().into_string(), "null".to_string()); assert_eq!(Null.to_pretty_str().into_string(), "null".to_string()); @@ -2493,15 +2312,15 @@ mod tests { fn test_write_enum() { let animal = Dog; assert_eq!( - with_str_writer(|wr| { - let mut encoder = Encoder::new(wr); + with_str_writer(|writer| { + let mut encoder = Encoder::new(writer); animal.encode(&mut encoder).unwrap(); }), "\"Dog\"".to_string() ); assert_eq!( - with_str_writer(|wr| { - let mut encoder = PrettyEncoder::new(wr); + with_str_writer(|writer| { + let mut encoder = PrettyEncoder::new(writer); animal.encode(&mut encoder).unwrap(); }), "\"Dog\"".to_string() @@ -2509,15 +2328,15 @@ mod tests { let animal = Frog("Henry".to_string(), 349); assert_eq!( - with_str_writer(|wr| { - let mut encoder = Encoder::new(wr); + with_str_writer(|writer| { + let mut encoder = Encoder::new(writer); animal.encode(&mut encoder).unwrap(); }), "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}".to_string() ); assert_eq!( - with_str_writer(|wr| { - let mut encoder = PrettyEncoder::new(wr); + with_str_writer(|writer| { + let mut encoder = PrettyEncoder::new(writer); animal.encode(&mut encoder).unwrap(); }), "\ @@ -2532,15 +2351,15 @@ mod tests { #[test] fn test_write_some() { let value = Some("jodhpurs".to_string()); - let s = with_str_writer(|wr| { - let mut encoder = Encoder::new(wr); + let s = with_str_writer(|writer| { + let mut encoder = Encoder::new(writer); value.encode(&mut encoder).unwrap(); }); assert_eq!(s, "\"jodhpurs\"".to_string()); let value = Some("jodhpurs".to_string()); - let s = with_str_writer(|wr| { - let mut encoder = PrettyEncoder::new(wr); + let s = with_str_writer(|writer| { + let mut encoder = PrettyEncoder::new(writer); value.encode(&mut encoder).unwrap(); }); assert_eq!(s, "\"jodhpurs\"".to_string()); @@ -2549,14 +2368,14 @@ mod tests { #[test] fn test_write_none() { let value: Option<String> = None; - let s = with_str_writer(|wr| { - let mut encoder = Encoder::new(wr); + let s = with_str_writer(|writer| { + let mut encoder = Encoder::new(writer); value.encode(&mut encoder).unwrap(); }); assert_eq!(s, "null".to_string()); - let s = with_str_writer(|wr| { - let mut encoder = Encoder::new(wr); + let s = with_str_writer(|writer| { + let mut encoder = Encoder::new(writer); value.encode(&mut encoder).unwrap(); }); assert_eq!(s, "null".to_string()); @@ -2591,16 +2410,13 @@ mod tests { #[test] fn test_decode_identifiers() { - let mut decoder = Decoder::new(from_str("null").unwrap()); - let v: () = Decodable::decode(&mut decoder).unwrap(); + let v: () = super::decode("null").unwrap(); assert_eq!(v, ()); - let mut decoder = Decoder::new(from_str("true").unwrap()); - let v: bool = Decodable::decode(&mut decoder).unwrap(); + let v: bool = super::decode("true").unwrap(); assert_eq!(v, true); - let mut decoder = Decoder::new(from_str("false").unwrap()); - let v: bool = Decodable::decode(&mut decoder).unwrap(); + let v: bool = super::decode("false").unwrap(); assert_eq!(v, false); } @@ -2627,32 +2443,25 @@ mod tests { #[test] fn test_decode_numbers() { - let mut decoder = Decoder::new(from_str("3").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("3").unwrap(); assert_eq!(v, 3.0); - let mut decoder = Decoder::new(from_str("3.1").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("3.1").unwrap(); assert_eq!(v, 3.1); - let mut decoder = Decoder::new(from_str("-1.2").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("-1.2").unwrap(); assert_eq!(v, -1.2); - let mut decoder = Decoder::new(from_str("0.4").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("0.4").unwrap(); assert_eq!(v, 0.4); - let mut decoder = Decoder::new(from_str("0.4e5").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("0.4e5").unwrap(); assert_eq!(v, 0.4e5); - let mut decoder = Decoder::new(from_str("0.4e15").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("0.4e15").unwrap(); assert_eq!(v, 0.4e15); - let mut decoder = Decoder::new(from_str("0.4e-01").unwrap()); - let v: f64 = Decodable::decode(&mut decoder).unwrap(); + let v: f64 = super::decode("0.4e-01").unwrap(); assert_eq!(v, 0.4e-01); } @@ -2686,13 +2495,8 @@ mod tests { ("\"\\uAB12\"", "\uAB12")]; for &(i, o) in s.iter() { - let mut decoder = Decoder::new(from_str(i).unwrap()); - let v: String = Decodable::decode(&mut decoder).unwrap(); + let v: String = super::decode(i).unwrap(); assert_eq!(v.as_slice(), o); - - let mut decoder = Decoder::new(from_str(i).unwrap()); - let v: String = Decodable::decode(&mut decoder).unwrap(); - assert_eq!(v, o.to_string()); } } @@ -2719,28 +2523,19 @@ mod tests { #[test] fn test_decode_list() { - let mut decoder = Decoder::new(from_str("[]").unwrap()); - let v: Vec<()> = Decodable::decode(&mut decoder).unwrap(); + let v: Vec<()> = super::decode("[]").unwrap(); assert_eq!(v, vec![]); - let mut decoder = Decoder::new(from_str("[null]").unwrap()); - let v: Vec<()> = Decodable::decode(&mut decoder).unwrap(); + let v: Vec<()> = super::decode("[null]").unwrap(); assert_eq!(v, vec![()]); - let mut decoder = Decoder::new(from_str("[true]").unwrap()); - let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap(); - assert_eq!(v, vec![true]); - - let mut decoder = Decoder::new(from_str("[true]").unwrap()); - let v: Vec<bool> = Decodable::decode(&mut decoder).unwrap(); + let v: Vec<bool> = super::decode("[true]").unwrap(); assert_eq!(v, vec![true]); - let mut decoder = Decoder::new(from_str("[3, 1]").unwrap()); - let v: Vec<int> = Decodable::decode(&mut decoder).unwrap(); + let v: Vec<int> = super::decode("[3, 1]").unwrap(); assert_eq!(v, vec![3, 1]); - let mut decoder = Decoder::new(from_str("[[3], [1, 2]]").unwrap()); - let v: Vec<Vec<uint>> = Decodable::decode(&mut decoder).unwrap(); + let v: Vec<Vec<uint>> = super::decode("[[3], [1, 2]]").unwrap(); assert_eq!(v, vec![vec![3], vec![1, 2]]); } @@ -2806,8 +2601,8 @@ mod tests { { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] } ] }"; - let mut decoder = Decoder::new(from_str(s).unwrap()); - let v: Outer = Decodable::decode(&mut decoder).unwrap(); + + let v: Outer = super::decode(s).unwrap(); assert_eq!( v, Outer { @@ -2825,35 +2620,29 @@ mod tests { } #[test] fn test_decode_struct_with_nan() { - let encoded_str = "{\"f\":null,\"a\":[null,123]}"; - let json_object = from_str(encoded_str.as_slice()); - let mut decoder = Decoder::new(json_object.unwrap()); - let after: FloatStruct = Decodable::decode(&mut decoder).unwrap(); - assert!(after.f.is_nan()); - assert!(after.a.get(0).is_nan()); - assert_eq!(after.a.get(1), &123f64); + let s = "{\"f\":null,\"a\":[null,123]}"; + let obj: FloatStruct = super::decode(s).unwrap(); + assert!(obj.f.is_nan()); + assert!(obj.a.get(0).is_nan()); + assert_eq!(obj.a.get(1), &123f64); } #[test] fn test_decode_option() { - let mut decoder = Decoder::new(from_str("null").unwrap()); - let value: Option<String> = Decodable::decode(&mut decoder).unwrap(); + let value: Option<String> = super::decode("null").unwrap(); assert_eq!(value, None); - let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap()); - let value: Option<String> = Decodable::decode(&mut decoder).unwrap(); + let value: Option<String> = super::decode("\"jodhpurs\"").unwrap(); assert_eq!(value, Some("jodhpurs".to_string())); } #[test] fn test_decode_enum() { - let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap()); - let value: Animal = Decodable::decode(&mut decoder).unwrap(); + let value: Animal = super::decode("\"Dog\"").unwrap(); assert_eq!(value, Dog); let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"; - let mut decoder = Decoder::new(from_str(s).unwrap()); - let value: Animal = Decodable::decode(&mut decoder).unwrap(); + let value: Animal = super::decode(s).unwrap(); assert_eq!(value, Frog("Henry".to_string(), 349)); } @@ -2861,8 +2650,7 @@ mod tests { fn test_decode_map() { let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\ \"fields\":[\"Henry\", 349]}}"; - let mut decoder = Decoder::new(from_str(s).unwrap()); - let mut map: TreeMap<String, Animal> = Decodable::decode(&mut decoder).unwrap(); + let mut map: TreeMap<String, Animal> = super::decode(s).unwrap(); assert_eq!(map.pop(&"a".to_string()), Some(Dog)); assert_eq!(map.pop(&"b".to_string()), Some(Frog("Henry".to_string(), 349))); @@ -3387,7 +3175,7 @@ mod tests { let mut tree_map = TreeMap::new(); tree_map.insert("a".to_string(), Number(1.0_f64)); tree_map.insert("b".to_string(), Number(2.0_f64)); - Object(box tree_map) + Object(tree_map) }; assert_eq!(list2.to_json(), list2); @@ -3424,7 +3212,7 @@ mod tests { hash_map.insert("a".to_string(), 1i); hash_map.insert("b".to_string(), 2); assert_eq!(hash_map.to_json(), object); - assert_eq!(Some(15i).to_json(), Number(15 as f64)); + assert_eq!(Some(15i).to_json(), Number(15f64)); assert_eq!(None::<int>.to_json(), Null); } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 2730d90f05f..fae1b933210 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -10,6 +10,8 @@ //! Operations on ASCII strings and characters +#![experimental] + use collections::Collection; use fmt; use iter::Iterator; diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index 7d821983075..834d461f20b 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -105,6 +105,7 @@ //! - `insert`: inserts the specified flags in-place //! - `remove`: removes the specified flags in-place +#![experimental] #![macro_escape] #[macro_export] diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index e8a158ad230..a7d697c8665 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -33,6 +33,8 @@ //! handled correctly, i.e. that allocated memory is eventually freed //! if necessary. +#![experimental] + use collections::Collection; use kinds::Send; use mem; @@ -102,14 +104,14 @@ impl<T> CVec<T> { /// View the stored data as a slice. pub fn as_slice<'a>(&'a self) -> &'a [T] { unsafe { - mem::transmute(raw::Slice { data: self.base as *T, len: self.len }) + mem::transmute(raw::Slice { data: self.base as *const T, len: self.len }) } } /// View the stored data as a mutable slice. pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { unsafe { - mem::transmute(raw::Slice { data: self.base as *T, len: self.len }) + mem::transmute(raw::Slice { data: self.base as *const T, len: self.len }) } } diff --git a/src/libstd/collections/hashmap.rs b/src/libstd/collections/hashmap.rs index d06d4ea7177..7c01a0342ed 100644 --- a/src/libstd/collections/hashmap.rs +++ b/src/libstd/collections/hashmap.rs @@ -16,15 +16,13 @@ use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap}; use default::Default; use fmt::Show; use fmt; -use hash::{Hash, Hasher, sip}; +use hash::{Hash, Hasher, RandomSipHasher}; use iter::{Iterator, FilterMap, Chain, Repeat, Zip, Extendable}; use iter::{range, range_inclusive, FromIterator}; use iter; use mem::replace; use num; use option::{Some, None, Option}; -use rand::Rng; -use rand; use result::{Ok, Err}; mod table { @@ -361,8 +359,8 @@ mod table { *self.hashes.offset(idx) = EMPTY_BUCKET; // Drop the mutable constraint. - let keys = self.keys as *K; - let vals = self.vals as *V; + let keys = self.keys as *const K; + let vals = self.vals as *const V; let k = ptr::read(keys.offset(idx)); let v = ptr::read(vals.offset(idx)); @@ -733,7 +731,7 @@ impl DefaultResizePolicy { /// } /// ``` #[deriving(Clone)] -pub struct HashMap<K, V, H = sip::SipHasher> { +pub struct HashMap<K, V, H = RandomSipHasher> { // All hashes are keyed on these values, to prevent hash collision attacks. hasher: H, @@ -1033,18 +1031,17 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> MutableMap<K, V> for HashMap<K, V, H> } -impl<K: Hash + Eq, V> HashMap<K, V, sip::SipHasher> { +impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> { /// Create an empty HashMap. - pub fn new() -> HashMap<K, V, sip::SipHasher> { + #[inline] + pub fn new() -> HashMap<K, V, RandomSipHasher> { HashMap::with_capacity(INITIAL_CAPACITY) } /// Creates an empty hash map with the given initial capacity. - pub fn with_capacity(capacity: uint) -> HashMap<K, V, sip::SipHasher> { - let mut r = rand::task_rng(); - let r0 = r.gen(); - let r1 = r.gen(); - let hasher = sip::SipHasher::new_with_keys(r0, r1); + #[inline] + pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomSipHasher> { + let hasher = RandomSipHasher::new(); HashMap::with_capacity_and_hasher(capacity, hasher) } } @@ -1053,6 +1050,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// Creates an empty hashmap which will use the given hasher to hash keys. /// /// The creates map has the default initial capacity. + #[inline] pub fn with_hasher(hasher: H) -> HashMap<K, V, H> { HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher) } @@ -1064,6 +1062,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// is designed to allow HashMaps to be resistant to attacks that /// cause many collisions and very poor performance. Setting it /// manually using this function can expose a DoS attack vector. + #[inline] pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap<K, V, H> { let cap = num::next_power_of_two(max(INITIAL_CAPACITY, capacity)); HashMap { @@ -1489,7 +1488,7 @@ pub type SetMoveItems<K> = /// HashMap where the value is (). As with the `HashMap` type, a `HashSet` /// requires that the elements implement the `Eq` and `Hash` traits. #[deriving(Clone)] -pub struct HashSet<T, H = sip::SipHasher> { +pub struct HashSet<T, H = RandomSipHasher> { map: HashMap<T, (), H> } @@ -1529,15 +1528,17 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> { fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } } -impl<T: Hash + Eq> HashSet<T, sip::SipHasher> { +impl<T: Hash + Eq> HashSet<T, RandomSipHasher> { /// Create an empty HashSet - pub fn new() -> HashSet<T, sip::SipHasher> { + #[inline] + pub fn new() -> HashSet<T, RandomSipHasher> { HashSet::with_capacity(INITIAL_CAPACITY) } /// Create an empty HashSet with space for at least `n` elements in /// the hash table. - pub fn with_capacity(capacity: uint) -> HashSet<T, sip::SipHasher> { + #[inline] + pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> { HashSet { map: HashMap::with_capacity(capacity) } } } @@ -1547,6 +1548,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// keys. /// /// The hash set is also created with the default initial capacity. + #[inline] pub fn with_hasher(hasher: H) -> HashSet<T, H> { HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher) } @@ -1558,6 +1560,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// is designed to allow `HashSet`s to be resistant to attacks that /// cause many collisions and very poor performance. Setting it /// manually using this function can expose a DoS attack vector. + #[inline] pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> { HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) } } diff --git a/src/libstd/collections/lru_cache.rs b/src/libstd/collections/lru_cache.rs index 8ec5146c7b2..08f11581e83 100644 --- a/src/libstd/collections/lru_cache.rs +++ b/src/libstd/collections/lru_cache.rs @@ -49,7 +49,7 @@ use owned::Box; use ptr; use result::{Ok, Err}; -struct KeyRef<K> { k: *K } +struct KeyRef<K> { k: *const K } struct LruEntry<K, V> { next: *mut LruEntry<K, V>, diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index 9e5288f9541..ccef1c0fd2a 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -12,6 +12,8 @@ * Collection types. */ +#![experimental] + pub use core_collections::{Collection, Mutable, Map, MutableMap}; pub use core_collections::{Set, MutableSet, Deque}; pub use core_collections::{Bitv, BitvSet, BTree, DList, EnumSet}; diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index 79e01c8b966..728875ce260 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -33,7 +33,7 @@ use str; use string::String; use vec::Vec; -pub struct DynamicLibrary { handle: *u8} +pub struct DynamicLibrary { handle: *mut u8 } impl Drop for DynamicLibrary { fn drop(&mut self) { @@ -134,7 +134,7 @@ impl DynamicLibrary { } /// Access the value at the symbol of the dynamic library - pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*T, String> { + pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> { // This function should have a lifetime constraint of 'a on // T but that feature is still unimplemented @@ -175,7 +175,7 @@ mod test { let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe { match libm.symbol("cos") { Err(error) => fail!("Could not load function cos: {}", error), - Ok(cosine) => mem::transmute::<*u8, _>(cosine) + Ok(cosine) => mem::transmute::<*mut u8, _>(cosine) } }; @@ -218,14 +218,14 @@ pub mod dl { use str::StrAllocating; use string::String; - pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 { + pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 { filename.with_c_str(|raw_name| { - dlopen(raw_name, Lazy as libc::c_int) as *u8 + dlopen(raw_name, Lazy as libc::c_int) as *mut u8 }) } - pub unsafe fn open_internal() -> *u8 { - dlopen(ptr::null(), Lazy as libc::c_int) as *u8 + pub unsafe fn open_internal() -> *mut u8 { + dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> { @@ -239,7 +239,7 @@ pub mod dl { let result = f(); - let last_error = dlerror(); + let last_error = dlerror() as *const _; let ret = if ptr::null() == last_error { Ok(result) } else { @@ -252,11 +252,12 @@ pub mod dl { } } - pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 { - dlsym(handle as *libc::c_void, symbol) as *u8 + pub unsafe fn symbol(handle: *mut u8, + symbol: *const libc::c_char) -> *mut u8 { + dlsym(handle as *mut libc::c_void, symbol) as *mut u8 } - pub unsafe fn close(handle: *u8) { - dlclose(handle as *libc::c_void); () + pub unsafe fn close(handle: *mut u8) { + dlclose(handle as *mut libc::c_void); () } pub enum RTLD { @@ -268,36 +269,41 @@ pub mod dl { #[link_name = "dl"] extern { - fn dlopen(filename: *libc::c_char, flag: libc::c_int) -> *libc::c_void; - fn dlerror() -> *libc::c_char; - fn dlsym(handle: *libc::c_void, symbol: *libc::c_char) -> *libc::c_void; - fn dlclose(handle: *libc::c_void) -> libc::c_int; + fn dlopen(filename: *const libc::c_char, + flag: libc::c_int) -> *mut libc::c_void; + fn dlerror() -> *mut libc::c_char; + fn dlsym(handle: *mut libc::c_void, + symbol: *const libc::c_char) -> *mut libc::c_void; + fn dlclose(handle: *mut libc::c_void) -> libc::c_int; } } #[cfg(target_os = "win32")] pub mod dl { use c_str::ToCStr; + use iter::Iterator; use libc; use os; use ptr; use result::{Ok, Err, Result}; - use str::StrAllocating; + use str::StrSlice; use str; use string::String; + use vec::Vec; - pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 { + pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 { // Windows expects Unicode data let filename_cstr = filename.to_c_str(); let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap(); - let filename_str = filename_str.to_utf16().append_one(0); - LoadLibraryW(filename_str.as_ptr() as *libc::c_void) as *u8 + let filename_str: Vec<u16> = filename_str.utf16_units().collect(); + let filename_str = filename_str.append_one(0); + LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8 } - pub unsafe fn open_internal() -> *u8 { - let handle = ptr::null(); - GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &handle as **libc::c_void); - handle as *u8 + pub unsafe fn open_internal() -> *mut u8 { + let mut handle = ptr::mut_null(); + GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle); + handle as *mut u8 } pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> { @@ -315,20 +321,22 @@ pub mod dl { } } - pub unsafe fn symbol(handle: *u8, symbol: *libc::c_char) -> *u8 { - GetProcAddress(handle as *libc::c_void, symbol) as *u8 + pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 { + GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8 } - pub unsafe fn close(handle: *u8) { - FreeLibrary(handle as *libc::c_void); () + pub unsafe fn close(handle: *mut u8) { + FreeLibrary(handle as *mut libc::c_void); () } #[allow(non_snake_case_functions)] extern "system" { fn SetLastError(error: libc::size_t); - fn LoadLibraryW(name: *libc::c_void) -> *libc::c_void; - fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *u16, - handle: **libc::c_void) -> *libc::c_void; - fn GetProcAddress(handle: *libc::c_void, name: *libc::c_char) -> *libc::c_void; - fn FreeLibrary(handle: *libc::c_void); + fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void; + fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16, + handle: *mut *mut libc::c_void) + -> *mut libc::c_void; + fn GetProcAddress(handle: *mut libc::c_void, + name: *const libc::c_char) -> *mut libc::c_void; + fn FreeLibrary(handle: *mut libc::c_void); } } diff --git a/src/libstd/failure.rs b/src/libstd/failure.rs index d1552f0bd10..47ff85e2806 100644 --- a/src/libstd/failure.rs +++ b/src/libstd/failure.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![experimental] + use alloc::owned::Box; use any::{Any, AnyRefExt}; use fmt; diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index ef0c59268c3..5834e576b08 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -412,6 +412,8 @@ the `}` character is escaped with `}}`. */ +#![experimental] + use io::Writer; use io; use result::{Ok, Err}; diff --git a/src/libstd/from_str.rs b/src/libstd/from_str.rs index 642bec48b83..1ca72bca20b 100644 --- a/src/libstd/from_str.rs +++ b/src/libstd/from_str.rs @@ -10,6 +10,8 @@ //! The `FromStr` trait for types that can be created from strings +#![experimental] + use option::{Option, Some, None}; use string::String; use str::StrAllocating; diff --git a/src/libstd/gc.rs b/src/libstd/gc.rs index 0f30e7231b1..47b7426633c 100644 --- a/src/libstd/gc.rs +++ b/src/libstd/gc.rs @@ -16,6 +16,7 @@ collector is task-local so `Gc<T>` is not sendable. */ +#![experimental] #![allow(experimental)] use clone::Clone; @@ -24,6 +25,7 @@ use default::Default; use fmt; use hash; use kinds::marker; +use option::Option; use ops::Deref; use raw; @@ -33,7 +35,7 @@ use raw; task annihilation. For now, cycles need to be broken manually by using `Rc<T>` \ with a non-owning `Weak<T>` pointer. A tracing garbage collector is planned."] pub struct Gc<T> { - _ptr: *T, + _ptr: *mut T, marker: marker::NoSend, } @@ -59,6 +61,10 @@ impl<T: PartialEq + 'static> PartialEq for Gc<T> { } impl<T: PartialOrd + 'static> PartialOrd for Gc<T> { #[inline] + fn partial_cmp(&self, other: &Gc<T>) -> Option<Ordering> { + (**self).partial_cmp(&**other) + } + #[inline] fn lt(&self, other: &Gc<T>) -> bool { *(*self) < *(*other) } #[inline] fn le(&self, other: &Gc<T>) -> bool { *(*self) <= *(*other) } @@ -83,7 +89,7 @@ impl<T: Default + 'static> Default for Gc<T> { } } -impl<T: 'static> raw::Repr<*raw::Box<T>> for Gc<T> {} +impl<T: 'static> raw::Repr<*const raw::Box<T>> for Gc<T> {} impl<S: hash::Writer, T: hash::Hash<S> + 'static> hash::Hash<S> for Gc<T> { fn hash(&self, s: &mut S) { @@ -104,6 +110,13 @@ mod tests { use cell::RefCell; #[test] + fn test_managed_clone() { + let a = box(GC) 5i; + let b: Gc<int> = a.clone(); + assert!(a == b); + } + + #[test] fn test_clone() { let x = Gc::new(RefCell::new(5)); let y = x.clone(); diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs new file mode 100644 index 00000000000..2cc7e70747a --- /dev/null +++ b/src/libstd/hash.rs @@ -0,0 +1,102 @@ +// 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. + +/*! + * Generic hashing support. + * + * This module provides a generic way to compute the hash of a value. The + * simplest way to make a type hashable is to use `#[deriving(Hash)]`: + * + * # Example + * + * ```rust + * use std::hash; + * use std::hash::Hash; + * + * #[deriving(Hash)] + * struct Person { + * id: uint, + * name: String, + * phone: u64, + * } + * + * let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; + * let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; + * + * assert!(hash::hash(&person1) != hash::hash(&person2)); + * ``` + * + * If you need more control over how a value is hashed, you need to implement + * the trait `Hash`: + * + * ```rust + * use std::hash; + * use std::hash::Hash; + * use std::hash::sip::SipState; + * + * struct Person { + * id: uint, + * name: String, + * phone: u64, + * } + * + * impl Hash for Person { + * fn hash(&self, state: &mut SipState) { + * self.id.hash(state); + * self.phone.hash(state); + * } + * } + * + * let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; + * let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; + * + * assert!(hash::hash(&person1) == hash::hash(&person2)); + * ``` + */ + +pub use core_collections::hash::{Hash, Hasher, Writer, hash, sip}; + +use default::Default; +use rand::Rng; +use rand; + +/// `RandomSipHasher` computes the SipHash algorithm from a stream of bytes +/// initialized with random keys. +#[deriving(Clone)] +pub struct RandomSipHasher { + hasher: sip::SipHasher, +} + +impl RandomSipHasher { + /// Construct a new `RandomSipHasher` that is initialized with random keys. + #[inline] + pub fn new() -> RandomSipHasher { + let mut r = rand::task_rng(); + let r0 = r.gen(); + let r1 = r.gen(); + RandomSipHasher { + hasher: sip::SipHasher::new_with_keys(r0, r1), + } + } +} + +impl Hasher<sip::SipState> for RandomSipHasher { + #[inline] + fn hash<T: Hash<sip::SipState>>(&self, value: &T) -> u64 { + self.hasher.hash(value) + } +} + +impl Default for RandomSipHasher { + #[inline] + fn default() -> RandomSipHasher { + RandomSipHasher::new() + } +} diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index c03fbf302d7..cd5887b7add 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -183,7 +183,10 @@ mod test { writer.write_be_u32(42).unwrap(); let wanted = vec![0u8, 0u8, 0u8, 42u8]; - let got = task::try(proc() { rx.recv() }).unwrap(); + let got = match task::try(proc() { rx.recv() }) { + Ok(got) => got, + Err(_) => fail!(), + }; assert_eq!(wanted, got); match writer.write_u8(1) { diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index 5d9865fded3..277aca2332d 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -166,7 +166,7 @@ pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 { let ptr = data.as_ptr().offset(start as int); let out = buf.as_mut_ptr(); copy_nonoverlapping_memory(out.offset((8 - size) as int), ptr, size); - from_be64(*(out as *u64)) + from_be64(*(out as *const u64)) } } diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index d8e04f18239..e7f26c7bd91 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -1051,7 +1051,7 @@ mod test { let initial_msg = "food-is-yummy"; let overwrite_msg = "-the-bar!!"; let final_msg = "foo-the-bar!!"; - let seek_idx = 3; + let seek_idx = 3i; let mut read_mem = [0, .. 13]; let tmpdir = tmpdir(); let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt"); @@ -1206,8 +1206,8 @@ mod test { let mut cur = [0u8, .. 2]; for f in files { let stem = f.filestem_str().unwrap(); - let root = stem[0] - ('0' as u8); - let name = stem[1] - ('0' as u8); + let root = stem.as_bytes()[0] - ('0' as u8); + let name = stem.as_bytes()[1] - ('0' as u8); assert!(cur[root as uint] < name); cur[root as uint] = name; } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 8014759c88a..1d339b03af6 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -216,6 +216,7 @@ responding to errors that may occur while attempting to read the numbers. */ +#![experimental] #![deny(unused_must_use)] use char::Char; diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index b79e831ff61..baf53251fbe 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -1360,4 +1360,44 @@ mod test { rx2.recv(); }) + + iotest!(fn clone_while_reading() { + let addr = next_test_ip6(); + let listen = TcpListener::bind(addr.ip.to_str().as_slice(), addr.port); + let mut accept = listen.listen().unwrap(); + + // Enqueue a task to write to a socket + let (tx, rx) = channel(); + let (txdone, rxdone) = channel(); + let txdone2 = txdone.clone(); + spawn(proc() { + let mut tcp = TcpStream::connect(addr.ip.to_str().as_slice(), + addr.port).unwrap(); + rx.recv(); + tcp.write_u8(0).unwrap(); + txdone2.send(()); + }); + + // Spawn off a reading clone + let tcp = accept.accept().unwrap(); + let tcp2 = tcp.clone(); + let txdone3 = txdone.clone(); + spawn(proc() { + let mut tcp2 = tcp2; + tcp2.read_u8().unwrap(); + txdone3.send(()); + }); + + // Try to ensure that the reading clone is indeed reading + for _ in range(0i, 50) { + ::task::deschedule(); + } + + // clone the handle again while it's reading, then let it finish the + // read. + let _ = tcp.clone(); + tx.send(()); + rxdone.recv(); + rxdone.recv(); + }) } diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index 5f6de52f866..cd78898d46b 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -45,12 +45,12 @@ use rt::rtio; /// }; /// /// let mut buf = [0, ..10]; -/// match socket.recvfrom(buf) { +/// match socket.recv_from(buf) { /// Ok((amt, src)) => { /// // Send a reply to the socket we received data from /// let buf = buf.mut_slice_to(amt); /// buf.reverse(); -/// socket.sendto(buf, src); +/// socket.send_to(buf, src); /// } /// Err(e) => println!("couldn't receive a datagram: {}", e) /// } @@ -72,9 +72,9 @@ impl UdpSocket { /// Receives data from the socket. On success, returns the number of bytes /// read and the address from whence the data came. - pub fn recvfrom(&mut self, buf: &mut [u8]) + pub fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)> { - match self.obj.recvfrom(buf) { + match self.obj.recv_from(buf) { Ok((amt, rtio::SocketAddr { ip, port })) => { Ok((amt, SocketAddr { ip: super::from_rtio(ip), port: port })) } @@ -82,15 +82,28 @@ impl UdpSocket { } } + #[allow(missing_doc)] + #[deprecated = "renamed to `recv_from`"] + pub fn recvfrom(&mut self, buf: &mut [u8]) + -> IoResult<(uint, SocketAddr)> { + self.recv_from(buf) + } + /// Sends data on the socket to the given address. Returns nothing on /// success. - pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> { - self.obj.sendto(buf, rtio::SocketAddr { + pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> { + self.obj.send_to(buf, rtio::SocketAddr { ip: super::to_rtio(dst.ip), port: dst.port, }).map_err(IoError::from_rtio_error) } + #[allow(missing_doc)] + #[deprecated = "renamed to `send_to`"] + pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> { + self.send_to(buf, dst) + } + /// Creates a `UdpStream`, which allows use of the `Reader` and `Writer` /// traits to receive and send data from the same address. This transfers /// ownership of the socket to the stream. @@ -225,7 +238,7 @@ impl Reader for UdpStream { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { let peer = self.connected_to; self.as_socket(|sock| { - match sock.recvfrom(buf) { + match sock.recv_from(buf) { Ok((_nread, src)) if src != peer => Ok(0), Ok((nread, _src)) => Ok(nread), Err(e) => Err(e), @@ -237,7 +250,7 @@ impl Reader for UdpStream { impl Writer for UdpStream { fn write(&mut self, buf: &[u8]) -> IoResult<()> { let connected_to = self.connected_to; - self.as_socket(|sock| sock.sendto(buf, connected_to)) + self.as_socket(|sock| sock.send_to(buf, connected_to)) } } @@ -266,7 +279,7 @@ mod test { match UdpSocket::bind(client_ip) { Ok(ref mut client) => { rx1.recv(); - client.sendto([99], server_ip).unwrap() + client.send_to([99], server_ip).unwrap() } Err(..) => fail!() } @@ -277,7 +290,7 @@ mod test { Ok(ref mut server) => { tx1.send(()); let mut buf = [0]; - match server.recvfrom(buf) { + match server.recv_from(buf) { Ok((nread, src)) => { assert_eq!(nread, 1); assert_eq!(buf[0], 99); @@ -300,7 +313,7 @@ mod test { match UdpSocket::bind(client_ip) { Ok(ref mut client) => { rx.recv(); - client.sendto([99], server_ip).unwrap() + client.send_to([99], server_ip).unwrap() } Err(..) => fail!() } @@ -310,7 +323,7 @@ mod test { Ok(ref mut server) => { tx.send(()); let mut buf = [0]; - match server.recvfrom(buf) { + match server.recv_from(buf) { Ok((nread, src)) => { assert_eq!(nread, 1); assert_eq!(buf[0], 99); @@ -429,9 +442,9 @@ mod test { spawn(proc() { let mut sock2 = sock2; let mut buf = [0, 0]; - assert_eq!(sock2.recvfrom(buf), Ok((1, addr1))); + assert_eq!(sock2.recv_from(buf), Ok((1, addr1))); assert_eq!(buf[0], 1); - sock2.sendto([2], addr1).unwrap(); + sock2.send_to([2], addr1).unwrap(); }); let sock3 = sock1.clone(); @@ -441,12 +454,12 @@ mod test { spawn(proc() { let mut sock3 = sock3; rx1.recv(); - sock3.sendto([1], addr2).unwrap(); + sock3.send_to([1], addr2).unwrap(); tx2.send(()); }); tx1.send(()); let mut buf = [0, 0]; - assert_eq!(sock1.recvfrom(buf), Ok((1, addr2))); + assert_eq!(sock1.recv_from(buf), Ok((1, addr2))); rx2.recv(); }) @@ -460,9 +473,9 @@ mod test { spawn(proc() { let mut sock2 = sock2; - sock2.sendto([1], addr1).unwrap(); + sock2.send_to([1], addr1).unwrap(); rx.recv(); - sock2.sendto([2], addr1).unwrap(); + sock2.send_to([2], addr1).unwrap(); rx.recv(); }); @@ -472,12 +485,12 @@ mod test { spawn(proc() { let mut sock3 = sock3; let mut buf = [0, 0]; - sock3.recvfrom(buf).unwrap(); + sock3.recv_from(buf).unwrap(); tx2.send(()); done.send(()); }); let mut buf = [0, 0]; - sock1.recvfrom(buf).unwrap(); + sock1.recv_from(buf).unwrap(); tx1.send(()); rx.recv(); @@ -497,7 +510,7 @@ mod test { let mut buf = [0, 1]; rx.recv(); - match sock2.recvfrom(buf) { + match sock2.recv_from(buf) { Ok(..) => {} Err(e) => fail!("failed receive: {}", e), } @@ -510,13 +523,13 @@ mod test { let tx2 = tx.clone(); spawn(proc() { let mut sock3 = sock3; - match sock3.sendto([1], addr2) { + match sock3.send_to([1], addr2) { Ok(..) => { let _ = tx2.send_opt(()); } Err(..) => {} } done.send(()); }); - match sock1.sendto([2], addr2) { + match sock1.send_to([2], addr2) { Ok(..) => { let _ = tx.send_opt(()); } Err(..) => {} } @@ -526,7 +539,7 @@ mod test { serv_rx.recv(); }) - iotest!(fn recvfrom_timeout() { + iotest!(fn recv_from_timeout() { let addr1 = next_test_ip4(); let addr2 = next_test_ip4(); let mut a = UdpSocket::bind(addr1).unwrap(); @@ -535,34 +548,34 @@ mod test { let (tx2, rx2) = channel(); spawn(proc() { let mut a = UdpSocket::bind(addr2).unwrap(); - assert_eq!(a.recvfrom([0]), Ok((1, addr1))); - assert_eq!(a.sendto([0], addr1), Ok(())); + assert_eq!(a.recv_from([0]), Ok((1, addr1))); + assert_eq!(a.send_to([0], addr1), Ok(())); rx.recv(); - assert_eq!(a.sendto([0], addr1), Ok(())); + assert_eq!(a.send_to([0], addr1), Ok(())); tx2.send(()); }); // Make sure that reads time out, but writes can continue a.set_read_timeout(Some(20)); - assert_eq!(a.recvfrom([0]).err().unwrap().kind, TimedOut); - assert_eq!(a.recvfrom([0]).err().unwrap().kind, TimedOut); - assert_eq!(a.sendto([0], addr2), Ok(())); + assert_eq!(a.recv_from([0]).err().unwrap().kind, TimedOut); + assert_eq!(a.recv_from([0]).err().unwrap().kind, TimedOut); + assert_eq!(a.send_to([0], addr2), Ok(())); // Cloned handles should be able to block let mut a2 = a.clone(); - assert_eq!(a2.recvfrom([0]), Ok((1, addr2))); + assert_eq!(a2.recv_from([0]), Ok((1, addr2))); // Clearing the timeout should allow for receiving a.set_timeout(None); tx.send(()); - assert_eq!(a2.recvfrom([0]), Ok((1, addr2))); + assert_eq!(a2.recv_from([0]), Ok((1, addr2))); // Make sure the child didn't die rx2.recv(); }) - iotest!(fn sendto_timeout() { + iotest!(fn send_to_timeout() { let addr1 = next_test_ip4(); let addr2 = next_test_ip4(); let mut a = UdpSocket::bind(addr1).unwrap(); @@ -570,7 +583,7 @@ mod test { a.set_write_timeout(Some(1000)); for _ in range(0u, 100) { - match a.sendto([0, ..4*1024], addr2) { + match a.send_to([0, ..4*1024], addr2) { Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {}, Err(IoError { kind: TimedOut, .. }) => break, Err(e) => fail!("other error: {}", e), diff --git a/src/libstd/io/test.rs b/src/libstd/io/test.rs index 4d3dde46b57..26e854d9d99 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/io/test.rs @@ -155,7 +155,7 @@ mod darwin_fd_limit { oldp: *mut libc::c_void, oldlenp: *mut libc::size_t, newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int; fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int; - fn setrlimit(resource: libc::c_int, rlp: *rlimit) -> libc::c_int; + fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int; } static CTL_KERN: libc::c_int = 1; static KERN_MAXFILESPERPROC: libc::c_int = 29; diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index b1512440969..145e812ff88 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -95,6 +95,7 @@ //! and `format!`, also available to all Rust code. #![crate_id = "std#0.11.0"] +#![unstable] #![comment = "The Rust standard library"] #![license = "MIT/ASL2"] #![crate_type = "rlib"] @@ -111,7 +112,6 @@ #![no_std] #![allow(deprecated)] -#![allow(unknown_features)] // NOTE: remove after stage0 snapshot #![deny(missing_doc)] // When testing libstd, bring in libuv as the I/O backend so tests can print @@ -167,7 +167,6 @@ pub use core::option; pub use alloc::owned; pub use alloc::rc; -pub use core_collections::hash; pub use core_collections::slice; pub use core_collections::str; pub use core_collections::string; @@ -184,7 +183,7 @@ pub use core_sync::comm; // threading mode than the default by reaching into the auto-generated // '__test' module. #[cfg(test)] #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, __test::main) } @@ -237,6 +236,7 @@ pub mod to_str; /* Common data structures */ pub mod collections; +pub mod hash; /* Tasks and communication */ diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 4db15d2cbbe..8b79af8c931 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -14,6 +14,7 @@ //! library. Each macro is available for use when linking against the standard //! library. +#![experimental] #![macro_escape] /// The entry point for failure of rust tasks. diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index bbf1458da21..2b2ffb9f4e2 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -10,6 +10,7 @@ //! Operations and constants for 32-bits floats (`f32` type) +#![experimental] #![allow(missing_doc)] #![allow(unsigned_negate)] #![doc(primitive = "f32")] diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index cfa8534160b..e156d2ce553 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -10,6 +10,7 @@ //! Operations and constants for 64-bits floats (`f64` type) +#![experimental] #![allow(missing_doc)] #![doc(primitive = "f64")] diff --git a/src/libstd/num/float_macros.rs b/src/libstd/num/float_macros.rs index 3e403219a4f..519de85edde 100644 --- a/src/libstd/num/float_macros.rs +++ b/src/libstd/num/float_macros.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![experimental] #![macro_escape] #![doc(hidden)] diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 9b3c9d29cc7..a4200b55a59 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![experimental] #![macro_escape] #![doc(hidden)] diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 65056652e3f..27ee1e3ce3b 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -13,6 +13,7 @@ //! These are implemented for the primitive numeric types in `std::{u8, u16, //! u32, u64, uint, i8, i16, i32, i64, int, f32, f64}`. +#![experimental] #![allow(missing_doc)] use option::Option; diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index 19e45b292fb..7f2efe034a2 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![experimental] #![macro_escape] #![doc(hidden)] #![allow(unsigned_negate)] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index a77242638eb..6674dd532ae 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -26,6 +26,8 @@ * to write OS-ignorant code by default. */ +#![experimental] + #![allow(missing_doc)] #![allow(non_snake_case_functions)] @@ -276,7 +278,7 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> { use c_str::CString; extern { - fn rust_env_pairs() -> **c_char; + fn rust_env_pairs() -> *const *const c_char; } let environ = rust_env_pairs(); if environ as uint == 0 { @@ -351,7 +353,7 @@ pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> { if s.is_null() { None } else { - Some(Vec::from_slice(CString::new(s, + Some(Vec::from_slice(CString::new(s as *const i8, false).as_bytes_no_nul())) } }) @@ -365,7 +367,8 @@ pub fn getenv(n: &str) -> Option<String> { unsafe { with_env_lock(|| { use os::win32::{fill_utf16_buf_and_decode}; - let n = n.to_utf16().append_one(0); + let n: Vec<u16> = n.utf16_units().collect(); + let n = n.append_one(0); fill_utf16_buf_and_decode(|buf, sz| { libc::GetEnvironmentVariableW(n.as_ptr(), buf, sz) }) @@ -411,8 +414,10 @@ pub fn setenv(n: &str, v: &str) { #[cfg(windows)] fn _setenv(n: &str, v: &str) { - let n = n.to_utf16().append_one(0); - let v = v.to_utf16().append_one(0); + let n: Vec<u16> = n.utf16_units().collect(); + let n = n.append_one(0); + let v: Vec<u16> = v.utf16_units().collect(); + let v = v.append_one(0); unsafe { with_env_lock(|| { libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr()); @@ -437,7 +442,8 @@ pub fn unsetenv(n: &str) { #[cfg(windows)] fn _unsetenv(n: &str) { - let n = n.to_utf16().append_one(0); + let n: Vec<u16> = n.utf16_units().collect(); + let n = n.append_one(0); unsafe { with_env_lock(|| { libc::SetEnvironmentVariableW(n.as_ptr(), ptr::null()); @@ -598,19 +604,20 @@ pub fn self_exe_name() -> Option<Path> { unsafe { use libc::funcs::bsd44::*; use libc::consts::os::extra::*; - let mib = vec![CTL_KERN as c_int, - KERN_PROC as c_int, - KERN_PROC_PATHNAME as c_int, -1 as c_int]; + let mut mib = vec![CTL_KERN as c_int, + KERN_PROC as c_int, + KERN_PROC_PATHNAME as c_int, + -1 as c_int]; let mut sz: libc::size_t = 0; - let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint, - ptr::mut_null(), &mut sz, ptr::null(), + let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint, + ptr::mut_null(), &mut sz, ptr::mut_null(), 0u as libc::size_t); if err != 0 { return None; } if sz == 0 { return None; } let mut v: Vec<u8> = Vec::with_capacity(sz as uint); - let err = sysctl(mib.as_ptr(), mib.len() as ::libc::c_uint, - v.as_mut_ptr() as *mut c_void, &mut sz, ptr::null(), - 0u as libc::size_t); + let err = sysctl(mib.as_mut_ptr(), mib.len() as ::libc::c_uint, + v.as_mut_ptr() as *mut c_void, &mut sz, + ptr::mut_null(), 0u as libc::size_t); if err != 0 { return None; } if sz == 0 { return None; } v.set_len(sz as uint - 1); // chop off trailing NUL @@ -803,7 +810,7 @@ pub fn change_dir(p: &Path) -> bool { #[cfg(windows)] fn chdir(p: &Path) -> bool { let p = match p.as_str() { - Some(s) => s.to_utf16().append_one(0), + Some(s) => s.utf16_units().collect::<Vec<u16>>().append_one(0), None => return false, }; unsafe { @@ -827,9 +834,9 @@ pub fn errno() -> int { #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] - fn errno_location() -> *c_int { + fn errno_location() -> *const c_int { extern { - fn __error() -> *c_int; + fn __error() -> *const c_int; } unsafe { __error() @@ -838,9 +845,9 @@ pub fn errno() -> int { #[cfg(target_os = "linux")] #[cfg(target_os = "android")] - fn errno_location() -> *c_int { + fn errno_location() -> *const c_int { extern { - fn __errno_location() -> *c_int; + fn __errno_location() -> *const c_int; } unsafe { __errno_location() @@ -913,7 +920,7 @@ pub fn error_string(errnum: uint) -> String { fail!("strerror_r failure"); } - str::raw::from_c_str(p as *c_char).into_string() + str::raw::from_c_str(p as *const c_char).into_string() } } @@ -932,7 +939,7 @@ pub fn error_string(errnum: uint) -> String { langId: DWORD, buf: LPWSTR, nsize: DWORD, - args: *c_void) + args: *const c_void) -> DWORD; } @@ -997,7 +1004,8 @@ pub fn get_exit_status() -> int { } #[cfg(target_os = "macos")] -unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<Vec<u8>> { +unsafe fn load_argc_and_argv(argc: int, + argv: *const *const c_char) -> Vec<Vec<u8>> { use c_str::CString; Vec::from_fn(argc as uint, |i| { @@ -1015,7 +1023,7 @@ unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> Vec<Vec<u8>> { fn real_args_as_bytes() -> Vec<Vec<u8>> { unsafe { let (argc, argv) = (*_NSGetArgc() as int, - *_NSGetArgv() as **c_char); + *_NSGetArgv() as *const *const c_char); load_argc_and_argv(argc, argv) } } @@ -1040,16 +1048,16 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> { #[link(name = "objc")] extern { - fn sel_registerName(name: *libc::c_uchar) -> Sel; + fn sel_registerName(name: *const libc::c_uchar) -> Sel; fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId; - fn objc_getClass(class_name: *libc::c_uchar) -> NsId; + fn objc_getClass(class_name: *const libc::c_uchar) -> NsId; } #[link(name = "Foundation", kind = "framework")] extern {} - type Sel = *libc::c_void; - type NsId = *libc::c_void; + type Sel = *const libc::c_void; + type NsId = *const libc::c_void; let mut res = Vec::new(); @@ -1067,7 +1075,8 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> { let cnt: int = mem::transmute(objc_msgSend(args, countSel)); for i in range(0, cnt) { let tmp = objc_msgSend(args, objectAtSel, i); - let utf_c_str: *libc::c_char = mem::transmute(objc_msgSend(tmp, utf8Sel)); + let utf_c_str: *const libc::c_char = + mem::transmute(objc_msgSend(tmp, utf8Sel)); let s = CString::new(utf_c_str, false); if s.is_not_null() { res.push(Vec::from_slice(s.as_bytes_no_nul())) @@ -1114,14 +1123,14 @@ fn real_args() -> Vec<String> { while *ptr.offset(len as int) != 0 { len += 1; } // Push it onto the list. - let opt_s = slice::raw::buf_as_slice(ptr, len, |buf| { + let opt_s = slice::raw::buf_as_slice(ptr as *const _, len, |buf| { str::from_utf16(str::truncate_utf16_at_nul(buf)) }); opt_s.expect("CommandLineToArgvW returned invalid UTF-16") }); unsafe { - LocalFree(szArgList as *c_void); + LocalFree(szArgList as *mut c_void); } return args @@ -1132,19 +1141,20 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> { real_args().move_iter().map(|s| s.into_bytes()).collect() } -type LPCWSTR = *u16; +type LPCWSTR = *const u16; #[cfg(windows)] #[link_name="kernel32"] extern "system" { fn GetCommandLineW() -> LPCWSTR; - fn LocalFree(ptr: *c_void); + fn LocalFree(ptr: *mut c_void); } #[cfg(windows)] #[link_name="shell32"] extern "system" { - fn CommandLineToArgvW(lpCmdLine: LPCWSTR, pNumArgs: *mut c_int) -> **u16; + fn CommandLineToArgvW(lpCmdLine: LPCWSTR, + pNumArgs: *mut c_int) -> *mut *mut u16; } /// Returns the arguments which this program was started with (normally passed @@ -1165,8 +1175,8 @@ pub fn args_as_bytes() -> Vec<Vec<u8>> { #[cfg(target_os = "macos")] extern { // These functions are in crt_externs.h. - pub fn _NSGetArgc() -> *c_int; - pub fn _NSGetArgv() -> ***c_char; + pub fn _NSGetArgc() -> *mut c_int; + pub fn _NSGetArgv() -> *mut *mut *mut c_char; } // Round up `from` to be divisible by `to` @@ -1224,7 +1234,7 @@ pub struct MemoryMap { pub enum MemoryMapKind { /// Virtual memory map. Usually used to change the permissions of a given /// chunk of memory. Corresponds to `VirtualAlloc` on Windows. - MapFile(*u8), + MapFile(*const u8), /// Virtual memory map. Usually used to change the permissions of a given /// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on /// Windows. @@ -1241,7 +1251,7 @@ pub enum MapOption { MapExecutable, /// Create a map for a specific address range. Corresponds to `MAP_FIXED` on /// POSIX. - MapAddr(*u8), + MapAddr(*const u8), /// Create a memory mapping for a file with a given fd. MapFd(c_int), /// When using `MapFd`, the start of the map is `uint` bytes from the start @@ -1342,7 +1352,7 @@ impl MemoryMap { if min_len == 0 { return Err(ErrZeroLength) } - let mut addr: *u8 = ptr::null(); + let mut addr: *const u8 = ptr::null(); let mut prot = 0; let mut flags = libc::MAP_PRIVATE; let mut fd = -1; @@ -1502,7 +1512,7 @@ impl MemoryMap { _ => Ok(MemoryMap { data: r as *mut u8, len: len, - kind: MapFile(mapping as *u8) + kind: MapFile(mapping as *const u8) }) } } @@ -1812,7 +1822,7 @@ mod tests { #[ignore] fn test_getenv_big() { let mut s = "".to_string(); - let mut i = 0; + let mut i = 0i; while i < 100 { s.push_str("aaaaaaaaaa"); i += 1; @@ -1990,7 +2000,7 @@ mod tests { open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR) }); lseek_(fd, size); - "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1)); + "x".with_c_str(|x| assert!(write(fd, x as *const c_void, 1) == 1)); fd }; let chunk = match MemoryMap::new(size / 2, [ diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index e55dc165895..7d814df8ebf 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -35,8 +35,8 @@ code, `Path` should be used to refer to the platform-native path. Creation of a path is typically done with either `Path::new(some_str)` or `Path::new(some_vec)`. This path can be modified with `.push()` and `.pop()` (and other setters). The resulting Path can either be passed to another -API that expects a path, or can be turned into a &[u8] with `.as_vec()` or a -Option<&str> with `.as_str()`. Similarly, attributes of the path can be queried +API that expects a path, or can be turned into a `&[u8]` with `.as_vec()` or a +`Option<&str>` with `.as_str()`. Similarly, attributes of the path can be queried with methods such as `.filename()`. There are also methods that return a new path instead of modifying the receiver, such as `.join()` or `.dir_path()`. @@ -63,6 +63,8 @@ println!("path exists: {}", path.exists()); */ +#![experimental] + use collections::Collection; use c_str::CString; use clone::Clone; diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index ec225a588fc..113b0410875 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -242,14 +242,18 @@ impl GenericPathUnsafe for Path { fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool { // assume prefix is Some(DiskPrefix) let rest = path.slice_from(prefix_len(prefix)); - !rest.is_empty() && rest[0].is_ascii() && is_sep(rest[0] as char) + !rest.is_empty() && rest.as_bytes()[0].is_ascii() && is_sep(rest.as_bytes()[0] as char) } fn shares_volume(me: &Path, path: &str) -> bool { // path is assumed to have a prefix of Some(DiskPrefix) let repr = me.repr.as_slice(); match me.prefix { - Some(DiskPrefix) => repr[0] == path[0].to_ascii().to_upper().to_byte(), - Some(VerbatimDiskPrefix) => repr[4] == path[0].to_ascii().to_upper().to_byte(), + Some(DiskPrefix) => { + repr.as_bytes()[0] == path.as_bytes()[0].to_ascii().to_upper().to_byte() + } + Some(VerbatimDiskPrefix) => { + repr.as_bytes()[4] == path.as_bytes()[0].to_ascii().to_upper().to_byte() + } _ => false } } @@ -279,7 +283,7 @@ impl GenericPathUnsafe for Path { // if me is "C:" we don't want to add a path separator match me.prefix { Some(DiskPrefix) if me.repr.len() == plen => (), - _ if !(me.repr.len() > plen && me.repr.as_slice()[me.repr.len()-1] == SEP_BYTE) => { + _ if !(me.repr.len() > plen && me.repr.as_bytes()[me.repr.len()-1] == SEP_BYTE) => { s.push_char(SEP); } _ => () @@ -302,7 +306,7 @@ impl GenericPathUnsafe for Path { // absolute path, or cwd-relative and self is not same volume replace_path(self, path, prefix); } - None if !path.is_empty() && is_sep_(self.prefix, path[0]) => { + None if !path.is_empty() && is_sep_(self.prefix, path.as_bytes()[0]) => { // volume-relative path if self.prefix.is_some() { // truncate self down to the prefix, then append @@ -478,7 +482,7 @@ impl GenericPath for Path { match self.prefix { Some(DiskPrefix) => { let rest = self.repr.as_slice().slice_from(self.prefix_len()); - rest.len() > 0 && rest[0] == SEP_BYTE + rest.len() > 0 && rest.as_bytes()[0] == SEP_BYTE } Some(_) => true, None => false @@ -638,11 +642,11 @@ impl Path { let s = match self.prefix { Some(_) => { let plen = self.prefix_len(); - if repr.len() > plen && repr[plen] == SEP_BYTE { + if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE { repr.slice_from(plen+1) } else { repr.slice_from(plen) } } - None if repr[0] == SEP_BYTE => repr.slice_from(1), + None if repr.as_bytes()[0] == SEP_BYTE => repr.slice_from(1), None => repr }; let ret = s.split_terminator(SEP).map(Some); @@ -665,14 +669,14 @@ impl Path { match (self.prefix, other.prefix) { (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => { self.is_absolute() && - s_repr[0].to_ascii().eq_ignore_case(o_repr[4].to_ascii()) + s_repr.as_bytes()[0].to_ascii().eq_ignore_case(o_repr.as_bytes()[4].to_ascii()) } (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => { other.is_absolute() && - s_repr[4].to_ascii().eq_ignore_case(o_repr[0].to_ascii()) + s_repr.as_bytes()[4].to_ascii().eq_ignore_case(o_repr.as_bytes()[0].to_ascii()) } (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => { - s_repr[4].to_ascii().eq_ignore_case(o_repr[4].to_ascii()) + s_repr.as_bytes()[4].to_ascii().eq_ignore_case(o_repr.as_bytes()[4].to_ascii()) } (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => { s_repr.slice(2, self.prefix_len()) == o_repr.slice(8, other.prefix_len()) @@ -718,12 +722,12 @@ impl Path { let mut comps = comps; match (comps.is_some(),prefix) { (false, Some(DiskPrefix)) => { - if s[0] >= 'a' as u8 && s[0] <= 'z' as u8 { + if s.as_bytes()[0] >= 'a' as u8 && s.as_bytes()[0] <= 'z' as u8 { comps = Some(vec![]); } } (false, Some(VerbatimDiskPrefix)) => { - if s[4] >= 'a' as u8 && s[0] <= 'z' as u8 { + if s.as_bytes()[4] >= 'a' as u8 && s.as_bytes()[0] <= 'z' as u8 { comps = Some(vec![]); } } @@ -778,12 +782,12 @@ impl Path { let mut s = String::with_capacity(n); match prefix { Some(DiskPrefix) => { - s.push_char(prefix_[0].to_ascii().to_upper().to_char()); + s.push_char(prefix_.as_bytes()[0].to_ascii().to_upper().to_char()); s.push_char(':'); } Some(VerbatimDiskPrefix) => { s.push_str(prefix_.slice_to(4)); - s.push_char(prefix_[4].to_ascii().to_upper().to_char()); + s.push_char(prefix_.as_bytes()[4].to_ascii().to_upper().to_char()); s.push_str(prefix_.slice_from(5)); } Some(UNCPrefix(a,b)) => { @@ -845,7 +849,7 @@ impl Path { fn has_nonsemantic_trailing_slash(&self) -> bool { is_verbatim(self) && self.repr.len() > self.prefix_len()+1 && - self.repr.as_slice()[self.repr.len()-1] == SEP_BYTE + self.repr.as_bytes()[self.repr.len()-1] == SEP_BYTE } fn update_normalized<S: Str>(&mut self, s: S) { @@ -861,7 +865,7 @@ impl Path { /// but absolute within that volume. #[inline] pub fn is_vol_relative(path: &Path) -> bool { - path.prefix.is_none() && is_sep_byte(&path.repr.as_slice()[0]) + path.prefix.is_none() && is_sep_byte(&path.repr.as_bytes()[0]) } /// Returns whether the path is considered "cwd-relative", which means a path @@ -991,8 +995,8 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { } else { // \\?\path let idx = path.find('\\'); - if idx == Some(2) && path[1] == ':' as u8 { - let c = path[0]; + if idx == Some(2) && path.as_bytes()[1] == ':' as u8 { + let c = path.as_bytes()[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { // \\?\C:\ path return Some(VerbatimDiskPrefix); @@ -1014,9 +1018,9 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { } _ => () } - } else if path.len() > 1 && path[1] == ':' as u8 { + } else if path.len() > 1 && path.as_bytes()[1] == ':' as u8 { // C: - let c = path[0]; + let c = path.as_bytes()[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { return Some(DiskPrefix); } diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index dfe6988624e..61e8b63af35 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -37,6 +37,8 @@ //! particularly useful standalone functions, like `from_str`, `range`, and //! `drop`, `spawn`, and `channel`. +#![experimental] + // Reexported core operators #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Share}; #[doc(no_inline)] pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not}; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index ffe4a94d2a2..0ffaadef0a1 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -73,6 +73,8 @@ println!("{}", tuple) ``` */ +#![experimental] + use cell::RefCell; use clone::Clone; use io::IoResult; @@ -244,7 +246,7 @@ pub fn random<T: Rand>() -> T { task_rng().gen() } -/// Randomly sample up to `n` elements from an iterator. +/// Randomly sample up to `amount` elements from an iterator. /// /// # Example /// @@ -257,11 +259,11 @@ pub fn random<T: Rand>() -> T { /// ``` pub fn sample<T, I: Iterator<T>, R: Rng>(rng: &mut R, mut iter: I, - amt: uint) -> Vec<T> { - let mut reservoir: Vec<T> = iter.by_ref().take(amt).collect(); + amount: uint) -> Vec<T> { + let mut reservoir: Vec<T> = iter.by_ref().take(amount).collect(); for (i, elem) in iter.enumerate() { - let k = rng.gen_range(0, i + 1 + amt); - if k < amt { + let k = rng.gen_range(0, i + 1 + amount); + if k < amount { *reservoir.get_mut(k) = elem; } } diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 1c1aab15361..60e2c4c8949 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -87,11 +87,12 @@ mod imp { struct SecRandom; - static kSecRandomDefault: *SecRandom = 0 as *SecRandom; + static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom; #[link(name = "Security", kind = "framework")] extern "C" { - fn SecRandomCopyBytes(rnd: *SecRandom, count: size_t, bytes: *mut u8) -> c_int; + fn SecRandomCopyBytes(rnd: *const SecRandom, + count: size_t, bytes: *mut u8) -> c_int; } impl OsRng { diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index e3652ffac6e..8f51e834c6a 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -261,7 +261,8 @@ mod imp { use slice::{MutableVector}; extern { - fn backtrace(buf: *mut *libc::c_void, sz: libc::c_int) -> libc::c_int; + fn backtrace(buf: *mut *const libc::c_void, + sz: libc::c_int) -> libc::c_int; } // while it doesn't requires lock for work as everything is @@ -273,7 +274,7 @@ mod imp { try!(writeln!(w, "stack backtrace:")); // 100 lines should be enough static SIZE: libc::c_int = 100; - let mut buf: [*libc::c_void, ..SIZE] = unsafe {mem::zeroed()}; + let mut buf: [*const libc::c_void, ..SIZE] = unsafe {mem::zeroed()}; let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE) as uint}; // skipping the first one as it is write itself @@ -307,7 +308,7 @@ mod imp { let mut cx = Context { writer: w, last_error: None, idx: 0 }; return match unsafe { uw::_Unwind_Backtrace(trace_fn, - &mut cx as *mut Context as *libc::c_void) + &mut cx as *mut Context as *mut libc::c_void) } { uw::_URC_NO_REASON => { match cx.last_error { @@ -318,10 +319,10 @@ mod imp { _ => Ok(()), }; - extern fn trace_fn(ctx: *uw::_Unwind_Context, - arg: *libc::c_void) -> uw::_Unwind_Reason_Code { + extern fn trace_fn(ctx: *mut uw::_Unwind_Context, + arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code { let cx: &mut Context = unsafe { mem::transmute(arg) }; - let ip = unsafe { uw::_Unwind_GetIP(ctx) as *libc::c_void }; + let ip = unsafe { uw::_Unwind_GetIP(ctx) as *mut libc::c_void }; // dladdr() on osx gets whiny when we use FindEnclosingFunction, and // it appears to work fine without it, so we only use // FindEnclosingFunction on non-osx platforms. In doing so, we get a @@ -365,22 +366,22 @@ mod imp { #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] - fn print(w: &mut Writer, idx: int, addr: *libc::c_void) -> IoResult<()> { + fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { use intrinsics; #[repr(C)] struct Dl_info { - dli_fname: *libc::c_char, - dli_fbase: *libc::c_void, - dli_sname: *libc::c_char, - dli_saddr: *libc::c_void, + dli_fname: *const libc::c_char, + dli_fbase: *mut libc::c_void, + dli_sname: *const libc::c_char, + dli_saddr: *mut libc::c_void, } extern { - fn dladdr(addr: *libc::c_void, + fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int; } let mut info: Dl_info = unsafe { intrinsics::init() }; - if unsafe { dladdr(addr, &mut info) == 0 } { + if unsafe { dladdr(addr as *const libc::c_void, &mut info) == 0 } { output(w, idx,addr, None) } else { output(w, idx, addr, Some(unsafe { @@ -390,7 +391,7 @@ mod imp { } #[cfg(not(target_os = "macos"), not(target_os = "ios"))] - fn print(w: &mut Writer, idx: int, addr: *libc::c_void) -> IoResult<()> { + fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { use collections::Collection; use iter::Iterator; use os; @@ -405,17 +406,17 @@ mod imp { type backtrace_syminfo_callback = extern "C" fn(data: *mut libc::c_void, pc: libc::uintptr_t, - symname: *libc::c_char, + symname: *const libc::c_char, symval: libc::uintptr_t, symsize: libc::uintptr_t); type backtrace_error_callback = extern "C" fn(data: *mut libc::c_void, - msg: *libc::c_char, + msg: *const libc::c_char, errnum: libc::c_int); enum backtrace_state {} #[link(name = "backtrace", kind = "static")] extern { - fn backtrace_create_state(filename: *libc::c_char, + fn backtrace_create_state(filename: *const libc::c_char, threaded: libc::c_int, error: backtrace_error_callback, data: *mut libc::c_void) @@ -431,16 +432,16 @@ mod imp { // helper callbacks //////////////////////////////////////////////////////////////////////// - extern fn error_cb(_data: *mut libc::c_void, _msg: *libc::c_char, + extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char, _errnum: libc::c_int) { // do nothing for now } extern fn syminfo_cb(data: *mut libc::c_void, _pc: libc::uintptr_t, - symname: *libc::c_char, + symname: *const libc::c_char, _symval: libc::uintptr_t, _symsize: libc::uintptr_t) { - let slot = data as *mut *libc::c_char; + let slot = data as *mut *const libc::c_char; unsafe { *slot = symname; } } @@ -502,8 +503,8 @@ mod imp { if state.is_null() { return output(w, idx, addr, None) } - let mut data = 0 as *libc::c_char; - let data_addr = &mut data as *mut *libc::c_char; + let mut data = 0 as *const libc::c_char; + let data_addr = &mut data as *mut *const libc::c_char; let ret = unsafe { backtrace_syminfo(state, addr as libc::uintptr_t, syminfo_cb, error_cb, @@ -517,7 +518,7 @@ mod imp { } // Finally, after all that work above, we can emit a symbol. - fn output(w: &mut Writer, idx: int, addr: *libc::c_void, + fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, s: Option<CString>) -> IoResult<()> { try!(write!(w, " {:2}: {:2$} - ", idx, addr, super::HEX_WIDTH)); match s.as_ref().and_then(|c| c.as_str()) { @@ -557,23 +558,23 @@ mod imp { pub enum _Unwind_Context {} pub type _Unwind_Trace_Fn = - extern fn(ctx: *_Unwind_Context, - arg: *libc::c_void) -> _Unwind_Reason_Code; + extern fn(ctx: *mut _Unwind_Context, + arg: *mut libc::c_void) -> _Unwind_Reason_Code; extern { // No native _Unwind_Backtrace on iOS #[cfg(not(target_os = "ios", target_arch = "arm"))] pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn, - trace_argument: *libc::c_void) + trace_argument: *mut libc::c_void) -> _Unwind_Reason_Code; #[cfg(not(target_os = "android"), not(target_os = "linux", target_arch = "arm"))] - pub fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t; + pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; #[cfg(not(target_os = "android"), not(target_os = "linux", target_arch = "arm"))] - pub fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) - -> *libc::c_void; + pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void) + -> *mut libc::c_void; } // On android, the function _Unwind_GetIP is a macro, and this is the @@ -581,7 +582,7 @@ mod imp { // header file with the definition of _Unwind_GetIP. #[cfg(target_os = "android")] #[cfg(target_os = "linux", target_arch = "arm")] - pub unsafe fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t { + pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { #[repr(C)] enum _Unwind_VRS_Result { _UVRSR_OK = 0, @@ -608,7 +609,7 @@ mod imp { type _Unwind_Word = libc::c_uint; extern { - fn _Unwind_VRS_Get(ctx: *_Unwind_Context, + fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context, klass: _Unwind_VRS_RegClass, word: _Unwind_Word, repr: _Unwind_VRS_DataRepresentation, @@ -627,8 +628,8 @@ mod imp { // a no-op #[cfg(target_os = "android")] #[cfg(target_os = "linux", target_arch = "arm")] - pub unsafe fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) - -> *libc::c_void + pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void) + -> *mut libc::c_void { pc } @@ -677,7 +678,7 @@ mod imp { extern "system" fn(libc::HANDLE, u64, *mut u64, *mut SYMBOL_INFO) -> libc::BOOL; type SymInitializeFn = - extern "system" fn(libc::HANDLE, *libc::c_void, + extern "system" fn(libc::HANDLE, *mut libc::c_void, libc::BOOL) -> libc::BOOL; type SymCleanupFn = extern "system" fn(libc::HANDLE) -> libc::BOOL; @@ -685,8 +686,8 @@ mod imp { type StackWalk64Fn = extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE, *mut STACKFRAME64, *mut arch::CONTEXT, - *libc::c_void, *libc::c_void, - *libc::c_void, *libc::c_void) -> libc::BOOL; + *mut libc::c_void, *mut libc::c_void, + *mut libc::c_void, *mut libc::c_void) -> libc::BOOL; static MAX_SYM_NAME: uint = 2000; static IMAGE_FILE_MACHINE_I386: libc::DWORD = 0x014c; @@ -735,7 +736,7 @@ mod imp { AddrFrame: ADDRESS64, AddrStack: ADDRESS64, AddrBStore: ADDRESS64, - FuncTableEntry: *libc::c_void, + FuncTableEntry: *mut libc::c_void, Params: [u64, ..4], Far: libc::BOOL, Virtual: libc::BOOL, @@ -924,7 +925,7 @@ mod imp { macro_rules! sym( ($e:expr, $t:ident) => (unsafe { match lib.symbol($e) { - Ok(f) => mem::transmute::<*u8, $t>(f), + Ok(f) => mem::transmute::<*mut u8, $t>(f), Err(..) => return Ok(()) } }) ) @@ -944,7 +945,7 @@ mod imp { let image = arch::init_frame(&mut frame, &context); // Initialize this process's symbols - let ret = SymInitialize(process, 0 as *libc::c_void, libc::TRUE); + let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE); if ret != libc::TRUE { return Ok(()) } let _c = Cleanup { handle: process, SymCleanup: SymCleanup }; @@ -952,8 +953,10 @@ mod imp { let mut i = 0i; try!(write!(w, "stack backtrace:\n")); while StackWalk64(image, process, thread, &mut frame, &mut context, - 0 as *libc::c_void, 0 as *libc::c_void, - 0 as *libc::c_void, 0 as *libc::c_void) == libc::TRUE{ + 0 as *mut libc::c_void, + 0 as *mut libc::c_void, + 0 as *mut libc::c_void, + 0 as *mut libc::c_void) == libc::TRUE{ let addr = frame.AddrPC.Offset; if addr == frame.AddrReturn.Offset || addr == 0 || frame.AddrReturn.Offset == 0 { break } diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index 66e7059422b..4490977bde6 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -51,6 +51,8 @@ Several modules in `core` are clients of `rt`: */ +#![experimental] + // FIXME: this should not be here. #![allow(missing_doc)] @@ -79,7 +81,7 @@ mod util; /// the crate's logging flags, registering GC /// metadata, and storing the process arguments. #[allow(experimental)] -pub fn init(argc: int, argv: **u8) { +pub fn init(argc: int, argv: *const *const u8) { rustrt::init(argc, argv); unsafe { unwind::register(failure::on_fail); } } diff --git a/src/libstd/rtdeps.rs b/src/libstd/rtdeps.rs index f8bfde52261..0ffac99775c 100644 --- a/src/libstd/rtdeps.rs +++ b/src/libstd/rtdeps.rs @@ -12,6 +12,8 @@ //! the standard library This varies per-platform, but these libraries are //! necessary for running libstd. +#![experimental] + // All platforms need to link to rustrt #[link(name = "rust_builtin", kind = "static")] extern {} diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 5f45ce25502..cc32818baa4 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -15,6 +15,8 @@ //! and/or blocking at all, but rather provide the necessary tools to build //! other types of concurrent primitives. +#![experimental] + pub use core_sync::{atomics, deque, mpmc_bounded_queue, mpsc_queue, spsc_queue}; pub use core_sync::{Arc, Weak, Mutex, MutexGuard, Condvar, Barrier}; pub use core_sync::{RWLock, RWLockReadGuard, RWLockWriteGuard}; diff --git a/src/libstd/task.rs b/src/libstd/task.rs index dad241002f8..c20cbea0ae7 100644 --- a/src/libstd/task.rs +++ b/src/libstd/task.rs @@ -91,6 +91,8 @@ //! # } //! ``` +#![experimental] + use any::Any; use comm::channel; use io::{Writer, stdio}; @@ -511,10 +513,10 @@ mod test { let (tx, rx) = channel::<uint>(); let x = box 1; - let x_in_parent = (&*x) as *int as uint; + let x_in_parent = (&*x) as *const int as uint; spawnfn(proc() { - let x_in_child = (&*x) as *int as uint; + let x_in_child = (&*x) as *const int as uint; tx.send(x_in_child); }); @@ -630,9 +632,11 @@ mod test { let mut reader = ChanReader::new(rx); let stdout = ChanWriter::new(tx); - TaskBuilder::new().stdout(box stdout as Box<Writer + Send>).try(proc() { - print!("Hello, world!"); - }).unwrap(); + let r = TaskBuilder::new().stdout(box stdout as Box<Writer + Send>) + .try(proc() { + print!("Hello, world!"); + }); + assert!(r.is_ok()); let output = reader.read_to_str().unwrap(); assert_eq!(output, "Hello, world!".to_string()); @@ -647,7 +651,7 @@ fn task_abort_no_kill_runtime() { use std::io::timer; use mem; - let mut tb = TaskBuilder::new(); + let tb = TaskBuilder::new(); let rx = tb.try_future(proc() {}); mem::drop(rx); timer::sleep(1000); diff --git a/src/libstd/to_str.rs b/src/libstd/to_str.rs index 5deb7f151bb..e51e2c4d9ce 100644 --- a/src/libstd/to_str.rs +++ b/src/libstd/to_str.rs @@ -14,6 +14,8 @@ The `ToStr` trait for converting to strings */ +#![experimental] + use fmt; use string::String; diff --git a/src/libsync/atomics.rs b/src/libsync/atomics.rs index 8ce17b9bf3b..195efb844a7 100644 --- a/src/libsync/atomics.rs +++ b/src/libsync/atomics.rs @@ -143,7 +143,7 @@ impl<T> AtomicOption<T> { /// Remove the value, leaving the `AtomicOption` empty. #[inline] pub fn take(&self, order: Ordering) -> Option<Box<T>> { - unsafe { self.swap(mem::transmute(0), order) } + unsafe { self.swap(mem::transmute(0u), order) } } /// Replace an empty value with a non-empty value. @@ -155,7 +155,7 @@ impl<T> AtomicOption<T> { pub fn fill(&self, val: Box<T>, order: Ordering) -> Option<Box<T>> { unsafe { let val = mem::transmute(val); - let expected = mem::transmute(0); + let expected = mem::transmute(0u); let oldval = self.p.compare_and_swap(expected, val, order); if oldval == expected { None diff --git a/src/libsync/comm/duplex.rs b/src/libsync/comm/duplex.rs index 3840e55bb42..44dd63cbf6c 100644 --- a/src/libsync/comm/duplex.rs +++ b/src/libsync/comm/duplex.rs @@ -15,6 +15,10 @@ Higher level communication abstractions. */ #![allow(missing_doc)] +#![deprecated = "This type is replaced by having a pair of channels. This type \ + is not fully composable with other channels in terms of \ + or possible semantics on a duplex stream. It will be removed \ + soon"] use core::prelude::*; @@ -64,7 +68,7 @@ mod test { let (left, right) = duplex(); left.send("abc".to_string()); - right.send(123); + right.send(123i); assert!(left.recv() == 123); assert!(right.recv() == "abc".to_string()); diff --git a/src/libsync/comm/mod.rs b/src/libsync/comm/mod.rs index 3e8f4eef370..6c09a021c43 100644 --- a/src/libsync/comm/mod.rs +++ b/src/libsync/comm/mod.rs @@ -370,6 +370,7 @@ static RESCHED_FREQ: int = 256; /// The receiving-half of Rust's channel type. This half can only be owned by /// one task +#[unstable] pub struct Receiver<T> { inner: Unsafe<Flavor<T>>, receives: Cell<uint>, @@ -380,12 +381,14 @@ pub struct Receiver<T> { /// An iterator over messages on a receiver, this iterator will block /// whenever `next` is called, waiting for a new message, and `None` will be /// returned when the corresponding channel has hung up. +#[unstable] pub struct Messages<'a, T> { rx: &'a Receiver<T> } /// The sending-half of Rust's asynchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. +#[unstable] pub struct Sender<T> { inner: Unsafe<Flavor<T>>, sends: Cell<uint>, @@ -395,6 +398,7 @@ pub struct Sender<T> { /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. +#[unstable = "this type may be renamed, but it will always exist"] pub struct SyncSender<T> { inner: Arc<Unsafe<sync::Packet<T>>>, // can't share in an arc @@ -404,6 +408,7 @@ pub struct SyncSender<T> { /// This enumeration is the list of the possible reasons that try_recv could not /// return data when called. #[deriving(PartialEq, Clone, Show)] +#[experimental = "this is likely to be removed in changing try_recv()"] pub enum TryRecvError { /// This channel is currently empty, but the sender(s) have not yet /// disconnected, so data may yet become available. @@ -416,6 +421,7 @@ pub enum TryRecvError { /// This enumeration is the list of the possible error outcomes for the /// `SyncSender::try_send` method. #[deriving(PartialEq, Clone, Show)] +#[experimental = "this is likely to be removed in changing try_send()"] pub enum TrySendError<T> { /// The data could not be sent on the channel because it would require that /// the callee block to send the data. @@ -478,6 +484,7 @@ impl<T> UnsafeFlavor<T> for Receiver<T> { /// // Let's see what that answer was /// println!("{}", rx.recv()); /// ``` +#[unstable] pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { let a = Arc::new(Unsafe::new(oneshot::Packet::new())); (Sender::new(Oneshot(a.clone())), Receiver::new(Oneshot(a))) @@ -514,6 +521,8 @@ pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { /// assert_eq!(rx.recv(), 1i); /// assert_eq!(rx.recv(), 2i); /// ``` +#[unstable = "this function may be renamed to more accurately reflect the type \ + of channel that is is creating"] pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) { let a = Arc::new(Unsafe::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Sync(a))) @@ -547,6 +556,8 @@ impl<T: Send> Sender<T> { /// /// The purpose of this functionality is to propagate failure among tasks. /// If failure is not desired, then consider using the `send_opt` method + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] pub fn send(&self, t: T) { if self.send_opt(t).is_err() { fail!("sending on a closed channel"); @@ -583,6 +594,7 @@ impl<T: Send> Sender<T> { /// drop(rx); /// assert_eq!(tx.send_opt(1i), Err(1)); /// ``` + #[unstable = "this function may be renamed to send() in the future"] pub fn send_opt(&self, t: T) -> Result<(), T> { // In order to prevent starvation of other tasks in situations where // a task sends repeatedly without ever receiving, we occasionally @@ -638,6 +650,7 @@ impl<T: Send> Sender<T> { } } +#[unstable] impl<T: Send> Clone for Sender<T> { fn clone(&self) -> Sender<T> { let (packet, sleeper) = match *unsafe { self.inner() } { @@ -719,6 +732,8 @@ impl<T: Send> SyncSender<T> { /// If failure is not desired, you can achieve the same semantics with the /// `SyncSender::send_opt` method which will not fail if the receiver /// disconnects. + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] pub fn send(&self, t: T) { if self.send_opt(t).is_err() { fail!("sending on a closed channel"); @@ -736,6 +751,7 @@ impl<T: Send> SyncSender<T> { /// # Failure /// /// This function cannot fail. + #[unstable = "this function may be renamed to send() in the future"] pub fn send_opt(&self, t: T) -> Result<(), T> { unsafe { (*self.inner.get()).send(t) } } @@ -753,11 +769,14 @@ impl<T: Send> SyncSender<T> { /// # Failure /// /// This function cannot fail + #[unstable = "the return type of this function is candidate for \ + modification"] pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> { unsafe { (*self.inner.get()).try_send(t) } } } +#[unstable] impl<T: Send> Clone for SyncSender<T> { fn clone(&self) -> SyncSender<T> { unsafe { (*self.inner.get()).clone_chan(); } @@ -800,6 +819,8 @@ impl<T: Send> Receiver<T> { /// /// * If blocking is not desired, then the `try_recv` method will attempt to /// peek at a value on this receiver. + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] pub fn recv(&self) -> T { match self.recv_opt() { Ok(t) => t, @@ -817,6 +838,7 @@ impl<T: Send> Receiver<T> { /// block on a receiver. /// /// This function cannot fail. + #[unstable = "the return type of this function may be altered"] pub fn try_recv(&self) -> Result<T, TryRecvError> { // If a thread is spinning in try_recv, we should take the opportunity // to reschedule things occasionally. See notes above in scheduling on @@ -881,6 +903,7 @@ impl<T: Send> Receiver<T> { /// /// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of /// the value found on the receiver is returned. + #[unstable = "this function may be renamed to recv()"] pub fn recv_opt(&self) -> Result<T, ()> { loop { let new_port = match *unsafe { self.inner() } { @@ -917,6 +940,7 @@ impl<T: Send> Receiver<T> { /// Returns an iterator which will block waiting for messages, but never /// `fail!`. It will return `None` when the channel has hung up. + #[unstable] pub fn iter<'a>(&'a self) -> Messages<'a, T> { Messages { rx: self } } @@ -1009,6 +1033,7 @@ impl<T: Send> select::Packet for Receiver<T> { } } +#[unstable] impl<'a, T: Send> Iterator<T> for Messages<'a, T> { fn next(&mut self) -> Option<T> { self.rx.recv_opt().ok() } } @@ -1543,7 +1568,7 @@ mod test { let (tx, rx) = channel(); let (cdone, pdone) = channel(); let t = Thread::start(proc() { - let mut hits = 0; + let mut hits = 0u; while hits < 10 { match rx.try_recv() { Ok(()) => { hits += 1; } @@ -1993,7 +2018,7 @@ mod sync_tests { let (tx, rx) = sync_channel::<()>(0); let (cdone, pdone) = channel(); let t = Thread::start(proc() { - let mut hits = 0; + let mut hits = 0u; while hits < 10 { match rx.try_recv() { Ok(()) => { hits += 1; } diff --git a/src/libsync/comm/select.rs b/src/libsync/comm/select.rs index 8d56f9a003b..230bca624f5 100644 --- a/src/libsync/comm/select.rs +++ b/src/libsync/comm/select.rs @@ -44,6 +44,13 @@ //! ``` #![allow(dead_code)] +#![experimental = "This implementation, while likely sufficient, is unsafe and \ + likely to be error prone. At some point in the future this \ + module will likely be replaced, and it is currently \ + unknown how much API breakage that will cause. The ability \ + to select over a number of channels will remain forever, \ + but no guarantees beyond this are being made"] + use core::prelude::*; diff --git a/src/libsync/deque.rs b/src/libsync/deque.rs index 18608a0a370..8d2192aeb53 100644 --- a/src/libsync/deque.rs +++ b/src/libsync/deque.rs @@ -30,15 +30,15 @@ //! let (mut worker, mut stealer) = pool.deque(); //! //! // Only the worker may push/pop -//! worker.push(1); +//! worker.push(1i); //! worker.pop(); //! //! // Stealers take data from the other end of the deque -//! worker.push(1); +//! worker.push(1i); //! stealer.steal(); //! //! // Stealers can be cloned to have many stealers stealing in parallel -//! worker.push(1); +//! worker.push(1i); //! let mut stealer2 = stealer.clone(); //! stealer2.steal(); @@ -137,7 +137,7 @@ pub struct BufferPool<T> { /// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although /// LLVM is probably pretty good at doing this already. struct Buffer<T> { - storage: *T, + storage: *const T, log_size: uint, } @@ -354,7 +354,7 @@ impl<T: Send> Buffer<T> { let size = buffer_alloc_size::<T>(log_size); let buffer = allocate(size, min_align_of::<T>()); Buffer { - storage: buffer as *T, + storage: buffer as *const T, log_size: log_size, } } @@ -364,7 +364,9 @@ impl<T: Send> Buffer<T> { // Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly fn mask(&self) -> int { (1 << self.log_size) - 1 } - unsafe fn elem(&self, i: int) -> *T { self.storage.offset(i & self.mask()) } + unsafe fn elem(&self, i: int) -> *const T { + self.storage.offset(i & self.mask()) + } // This does not protect against loading duplicate values of the same cell, // nor does this clear out the contents contained within. Hence, this is a @@ -610,7 +612,8 @@ mod tests { let s = s.clone(); let unique_box = box AtomicUint::new(0); let thread_box = unsafe { - *mem::transmute::<&Box<AtomicUint>, **mut AtomicUint>(&unique_box) + *mem::transmute::<&Box<AtomicUint>, + *const *mut AtomicUint>(&unique_box) }; (Thread::start(proc() { unsafe { diff --git a/src/libsync/lock.rs b/src/libsync/lock.rs index dff9fee2b77..1d119bafea1 100644 --- a/src/libsync/lock.rs +++ b/src/libsync/lock.rs @@ -158,7 +158,7 @@ impl<'a> Condvar<'a> { /// ``` /// use sync::{Mutex, Arc}; /// -/// let mutex = Arc::new(Mutex::new(1)); +/// let mutex = Arc::new(Mutex::new(1i)); /// let mutex2 = mutex.clone(); /// /// spawn(proc() { @@ -487,7 +487,7 @@ mod tests { #[test] #[should_fail] fn test_arc_condvar_poison() { - let arc = Arc::new(Mutex::new(1)); + let arc = Arc::new(Mutex::new(1i)); let arc2 = arc.clone(); let (tx, rx) = channel(); diff --git a/src/libsync/mpsc_intrusive.rs b/src/libsync/mpsc_intrusive.rs index 6af733ddb4b..2b6886ab7f4 100644 --- a/src/libsync/mpsc_intrusive.rs +++ b/src/libsync/mpsc_intrusive.rs @@ -104,7 +104,7 @@ impl<T: Send> Queue<T> { mem::transmute(&self.stub) }; let mut next = (*tail).next(atomics::Relaxed); - if tail as uint == &self.stub as *DummyNode as uint { + if tail as uint == &self.stub as *const DummyNode as uint { if next.is_null() { return None; } diff --git a/src/libsync/mpsc_queue.rs b/src/libsync/mpsc_queue.rs index 4bb0acf580c..ecd37e68880 100644 --- a/src/libsync/mpsc_queue.rs +++ b/src/libsync/mpsc_queue.rs @@ -167,8 +167,8 @@ mod tests { #[test] fn test_full() { let q = Queue::new(); - q.push(box 1); - q.push(box 2); + q.push(box 1i); + q.push(box 2i); } #[test] diff --git a/src/libsync/raw.rs b/src/libsync/raw.rs index 35865e65612..26cc0b2c6a2 100644 --- a/src/libsync/raw.rs +++ b/src/libsync/raw.rs @@ -890,7 +890,7 @@ mod tests { let x2 = x.clone(); let mut sharedstate = box 0; { - let ptr: *int = &*sharedstate; + let ptr: *const int = &*sharedstate; task::spawn(proc() { let sharedstate: &mut int = unsafe { mem::transmute(ptr) }; diff --git a/src/libsync/spsc_queue.rs b/src/libsync/spsc_queue.rs index a4da1fd2335..2834d404c18 100644 --- a/src/libsync/spsc_queue.rs +++ b/src/libsync/spsc_queue.rs @@ -252,8 +252,8 @@ mod test { #[test] fn drop_full() { let q = Queue::new(0); - q.push(box 1); - q.push(box 2); + q.push(box 1i); + q.push(box 2i); } #[test] @@ -284,7 +284,7 @@ mod test { for _ in range(0u, 100000) { loop { match b.pop() { - Some(1) => break, + Some(1i) => break, Some(_) => fail!(), None => {} } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index d24c2be5a74..529b460adcd 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -401,6 +401,7 @@ pub enum Decl_ { DeclItem(Gc<Item>), } +/// represents one arm of a 'match' #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)] pub struct Arm { pub attrs: Vec<Attribute>, diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 16c463f0c96..dfaa9fb5fcb 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -18,6 +18,7 @@ use std::fmt; use std::io; use std::iter::range; use std::string::String; +use term::WriterWrapper; use term; // maximum number of lines we will print for each error; arbitrary. @@ -281,7 +282,7 @@ pub struct EmitterWriter { } enum Destination { - Terminal(Box<term::Terminal<Box<Writer + Send>> + Send>), + Terminal(Box<term::Terminal<WriterWrapper> + Send>), Raw(Box<Writer + Send>), } @@ -414,7 +415,7 @@ fn highlight_lines(err: &mut EmitterWriter, } let orig = fm.get_line(*lines.lines.get(0) as int); for pos in range(0u, left-skip) { - let cur_char = orig.as_slice()[pos] as char; + let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). // That way the squiggly line will usually appear in the correct diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 88ebe8a60fa..59cdec1ea88 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -43,22 +43,116 @@ pub fn expand_deriving_ord(cx: &mut ExtCtxt, } } ); + let ordering_ty = Literal(Path::new(vec!["std", "cmp", "Ordering"])); + let ret_ty = Literal(Path::new_(vec!["std", "option", "Option"], + None, + vec![box ordering_ty], + true)); + + let inline = cx.meta_word(span, InternedString::new("inline")); + let attrs = vec!(cx.attribute(span, inline)); + + let partial_cmp_def = MethodDef { + name: "partial_cmp", + generics: LifetimeBounds::empty(), + explicit_self: borrowed_explicit_self(), + args: vec![borrowed_self()], + ret_ty: ret_ty, + attributes: attrs, + const_nonmatching: false, + combine_substructure: combine_substructure(|cx, span, substr| { + cs_partial_cmp(cx, span, substr) + }) + }; + let trait_def = TraitDef { span: span, - attributes: Vec::new(), - path: Path::new(vec!("std", "cmp", "PartialOrd")), - additional_bounds: Vec::new(), + attributes: vec![], + path: Path::new(vec!["std", "cmp", "PartialOrd"]), + additional_bounds: vec![], generics: LifetimeBounds::empty(), - methods: vec!( + methods: vec![ + partial_cmp_def, md!("lt", true, false), md!("le", true, true), md!("gt", false, false), md!("ge", false, true) - ) + ] }; trait_def.expand(cx, mitem, item, push) } +pub fn some_ordering_const(cx: &mut ExtCtxt, span: Span, cnst: Ordering) -> Gc<ast::Expr> { + let cnst = match cnst { + Less => "Less", + Equal => "Equal", + Greater => "Greater" + }; + let ordering = cx.path_global(span, + vec!(cx.ident_of("std"), + cx.ident_of("cmp"), + cx.ident_of(cnst))); + let ordering = cx.expr_path(ordering); + cx.expr_some(span, ordering) +} + +pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, + substr: &Substructure) -> Gc<Expr> { + let test_id = cx.ident_of("__test"); + let equals_expr = some_ordering_const(cx, span, Equal); + + /* + Builds: + + let __test = self_field1.partial_cmp(&other_field2); + if __test == ::std::option::Some(::std::cmp::Equal) { + let __test = self_field2.partial_cmp(&other_field2); + if __test == ::std::option::Some(::std::cmp::Equal) { + ... + } else { + __test + } + } else { + __test + } + + FIXME #6449: These `if`s could/should be `match`es. + */ + cs_same_method_fold( + // foldr nests the if-elses correctly, leaving the first field + // as the outermost one, and the last as the innermost. + false, + |cx, span, old, new| { + // let __test = new; + // if __test == Some(::std::cmp::Equal) { + // old + // } else { + // __test + // } + + let assign = cx.stmt_let(span, false, test_id, new); + + let cond = cx.expr_binary(span, ast::BiEq, + cx.expr_ident(span, test_id), + equals_expr.clone()); + let if_ = cx.expr_if(span, + cond, + old, Some(cx.expr_ident(span, test_id))); + cx.expr_block(cx.block(span, vec!(assign), Some(if_))) + }, + equals_expr.clone(), + |cx, span, list, _| { + match list { + // an earlier nonmatching variant is Less than a + // later one. + [(self_var, _, _), (other_var, _, _)] => + some_ordering_const(cx, span, self_var.cmp(&other_var)), + _ => cx.span_bug(span, "not exactly 2 arguments in `deriving(Ord)`") + } + }, + cx, span, substr) +} + /// Strict inequality. fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> Gc<Expr> { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 321c56d4bbf..b9cedb7a779 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -31,6 +31,7 @@ use util::small_vector::SmallVector; use std::gc::{Gc, GC}; + pub fn expand_expr(e: Gc<ast::Expr>, fld: &mut MacroExpander) -> Gc<ast::Expr> { match e.node { // expr_mac should really be expr_ext or something; it's the @@ -53,7 +54,6 @@ pub fn expand_expr(e: Gc<ast::Expr>, fld: &mut MacroExpander) -> Gc<ast::Expr> { } let extname = pth.segments.get(0).identifier; let extnamestr = token::get_ident(extname); - // leaving explicit deref here to highlight unbox op: let marked_after = match fld.extsbox.find(&extname.name) { None => { fld.cx.span_err( @@ -130,8 +130,6 @@ pub fn expand_expr(e: Gc<ast::Expr>, fld: &mut MacroExpander) -> Gc<ast::Expr> { // From: `['<ident>:] for <src_pat> in <src_expr> <src_loop_block>` // FIXME #6993: change type of opt_ident to Option<Name> ast::ExprForLoop(src_pat, src_expr, src_loop_block, opt_ident) => { - // Expand any interior macros etc. - // NB: we don't fold pats yet. Curious. let span = e.span; @@ -252,7 +250,7 @@ fn expand_loop_block(loop_block: P<Block>, // the same context will pick that up in the deferred renaming pass // and be renamed incorrectly. let mut rename_list = vec!(rename); - let mut rename_fld = renames_to_fold(&mut rename_list); + let mut rename_fld = IdentRenamer{renames: &mut rename_list}; let renamed_ident = rename_fld.fold_ident(label); // The rename *must* be added to the enclosed syntax context for @@ -281,7 +279,7 @@ macro_rules! with_exts_frame ( ) // When we enter a module, record it, for the sake of `module!` -pub fn expand_item(it: Gc<ast::Item>, fld: &mut MacroExpander) +fn expand_item(it: Gc<ast::Item>, fld: &mut MacroExpander) -> SmallVector<Gc<ast::Item>> { let it = expand_item_modifiers(it, fld); @@ -386,13 +384,13 @@ fn expand_item_modifiers(mut it: Gc<ast::Item>, fld: &mut MacroExpander) } // does this attribute list contain "macro_escape" ? -pub fn contains_macro_escape(attrs: &[ast::Attribute]) -> bool { +fn contains_macro_escape(attrs: &[ast::Attribute]) -> bool { attr::contains_name(attrs, "macro_escape") } // Support for item-position macro invocations, exactly the same // logic as for expression-position macro invocations. -pub fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander) +fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander) -> SmallVector<Gc<ast::Item>> { let (pth, tts) = match it.node { ItemMac(codemap::Spanned { @@ -498,7 +496,7 @@ pub fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander) } // expand a stmt -pub fn expand_stmt(s: &Stmt, fld: &mut MacroExpander) -> SmallVector<Gc<Stmt>> { +fn expand_stmt(s: &Stmt, fld: &mut MacroExpander) -> SmallVector<Gc<Stmt>> { // why the copying here and not in expand_expr? // looks like classic changed-in-only-one-place let (pth, tts, semi) = match s.node { @@ -609,25 +607,21 @@ fn expand_non_macro_stmt(s: &Stmt, fld: &mut MacroExpander) span: span, source: source, } = **local; - // expand the pat (it might contain exprs... #:(o)> + // expand the pat (it might contain macro uses): let expanded_pat = fld.fold_pat(pat); // find the pat_idents in the pattern: // oh dear heaven... this is going to include the enum // names, as well... but that should be okay, as long as // the new names are gensyms for the old ones. - let mut name_finder = new_name_finder(Vec::new()); - name_finder.visit_pat(&*expanded_pat,()); // generate fresh names, push them to a new pending list - let mut new_pending_renames = Vec::new(); - for ident in name_finder.ident_accumulator.iter() { - let new_name = fresh_name(ident); - new_pending_renames.push((*ident,new_name)); - } + let idents = pattern_bindings(expanded_pat); + let mut new_pending_renames = + idents.iter().map(|ident| (*ident, fresh_name(ident))).collect(); + // rewrite the pattern using the new names (the old + // ones have already been applied): let rewritten_pat = { - let mut rename_fld = - renames_to_fold(&mut new_pending_renames); - // rewrite the pattern using the new names (the old - // ones have already been applied): + // nested binding to allow borrow to expire: + let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames}; rename_fld.fold_pat(expanded_pat) }; // add them to the existing pending renames: @@ -659,9 +653,47 @@ fn expand_non_macro_stmt(s: &Stmt, fld: &mut MacroExpander) } } +fn expand_arm(arm: &ast::Arm, fld: &mut MacroExpander) -> ast::Arm { + // expand pats... they might contain macro uses: + let expanded_pats : Vec<Gc<ast::Pat>> = arm.pats.iter().map(|pat| fld.fold_pat(*pat)).collect(); + if expanded_pats.len() == 0 { + fail!("encountered match arm with 0 patterns"); + } + // all of the pats must have the same set of bindings, so use the + // first one to extract them and generate new names: + let first_pat = expanded_pats.get(0); + // code duplicated from 'let', above. Perhaps this can be lifted + // into a separate function: + let idents = pattern_bindings(*first_pat); + let mut new_pending_renames = + idents.iter().map(|id| (*id,fresh_name(id))).collect(); + // rewrite all of the patterns using the new names (the old + // ones have already been applied). Note that we depend here + // on the guarantee that after expansion, there can't be any + // Path expressions (a.k.a. varrefs) left in the pattern. If + // this were false, we'd need to apply this renaming only to + // the bindings, and not to the varrefs, using a more targeted + // fold-er. + let mut rename_fld = IdentRenamer{renames:&mut new_pending_renames}; + let rewritten_pats = + expanded_pats.iter().map(|pat| rename_fld.fold_pat(*pat)).collect(); + // apply renaming and then expansion to the guard and the body: + let rewritten_guard = + arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g))); + let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body)); + ast::Arm { + attrs: arm.attrs.iter().map(|x| fld.fold_attribute(*x)).collect(), + pats: rewritten_pats, + guard: rewritten_guard, + body: rewritten_body, + } +} + + + // a visitor that extracts the pat_ident (binding) paths // from a given thingy and puts them in a mutable -// array (passed in to the traversal). +// array #[deriving(Clone)] struct NameFinderContext { ident_accumulator: Vec<ast::Ident> , @@ -701,38 +733,38 @@ impl Visitor<()> for NameFinderContext { } -// return a visitor that extracts the pat_ident paths -// from a given thingy and puts them in a mutable -// array (passed in to the traversal) -fn new_name_finder(idents: Vec<ast::Ident> ) -> NameFinderContext { - NameFinderContext { - ident_accumulator: idents, - } +// find the pat_ident paths in a pattern +fn pattern_bindings(pat : &ast::Pat) -> Vec<ast::Ident> { + let mut name_finder = NameFinderContext{ident_accumulator:Vec::new()}; + name_finder.visit_pat(pat,()); + name_finder.ident_accumulator } // expand a block. pushes a new exts_frame, then calls expand_block_elts -pub fn expand_block(blk: &Block, fld: &mut MacroExpander) -> P<Block> { +fn expand_block(blk: &Block, fld: &mut MacroExpander) -> P<Block> { // see note below about treatment of exts table with_exts_frame!(fld.extsbox,false, expand_block_elts(blk, fld)) } // expand the elements of a block. -pub fn expand_block_elts(b: &Block, fld: &mut MacroExpander) -> P<Block> { +fn expand_block_elts(b: &Block, fld: &mut MacroExpander) -> P<Block> { let new_view_items = b.view_items.iter().map(|x| fld.fold_view_item(x)).collect(); let new_stmts = b.stmts.iter().flat_map(|x| { + // perform all pending renames let renamed_stmt = { let pending_renames = &mut fld.extsbox.info().pending_renames; - let mut rename_fld = renames_to_fold(pending_renames); + let mut rename_fld = IdentRenamer{renames:pending_renames}; rename_fld.fold_stmt(&**x).expect_one("rename_fold didn't return one value") }; + // expand macros in the statement fld.fold_stmt(&*renamed_stmt).move_iter() }).collect(); let new_expr = b.expr.map(|x| { let expr = { let pending_renames = &mut fld.extsbox.info().pending_renames; - let mut rename_fld = renames_to_fold(pending_renames); + let mut rename_fld = IdentRenamer{renames:pending_renames}; rename_fld.fold_expr(x) }; fld.fold_expr(expr) @@ -747,7 +779,7 @@ pub fn expand_block_elts(b: &Block, fld: &mut MacroExpander) -> P<Block> { }) } -pub fn expand_pat(p: Gc<ast::Pat>, fld: &mut MacroExpander) -> Gc<ast::Pat> { +fn expand_pat(p: Gc<ast::Pat>, fld: &mut MacroExpander) -> Gc<ast::Pat> { let (pth, tts) = match p.node { PatMac(ref mac) => { match mac.node { @@ -824,6 +856,9 @@ pub fn expand_pat(p: Gc<ast::Pat>, fld: &mut MacroExpander) -> Gc<ast::Pat> { } } +// a tree-folder that applies every rename in its (mutable) list +// to every identifier, including both bindings and varrefs +// (and lots of things that will turn out to be neither) pub struct IdentRenamer<'a> { renames: &'a mut RenameList, } @@ -840,15 +875,7 @@ impl<'a> Folder for IdentRenamer<'a> { } } -// given a mutable list of renames, return a tree-folder that applies those -// renames. -pub fn renames_to_fold<'a>(renames: &'a mut RenameList) -> IdentRenamer<'a> { - IdentRenamer { - renames: renames, - } -} - -pub fn new_span(cx: &ExtCtxt, sp: Span) -> Span { +fn new_span(cx: &ExtCtxt, sp: Span) -> Span { /* this discards information in the case of macro-defining macros */ Span { lo: sp.lo, @@ -883,6 +910,10 @@ impl<'a, 'b> Folder for MacroExpander<'a, 'b> { expand_block(&*block, self) } + fn fold_arm(&mut self, arm: &ast::Arm) -> ast::Arm { + expand_arm(arm, self) + } + fn new_span(&mut self, span: Span) -> Span { new_span(self.cx, span) } @@ -965,35 +996,30 @@ impl Folder for Marker { } } -// just a convenience: -fn new_mark_folder(m: Mrk) -> Marker { - Marker {mark: m} -} - // apply a given mark to the given token trees. Used prior to expansion of a macro. fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> { - fold_tts(tts, &mut new_mark_folder(m)) + fold_tts(tts, &mut Marker{mark:m}) } // apply a given mark to the given expr. Used following the expansion of a macro. fn mark_expr(expr: Gc<ast::Expr>, m: Mrk) -> Gc<ast::Expr> { - new_mark_folder(m).fold_expr(expr) + Marker{mark:m}.fold_expr(expr) } // apply a given mark to the given pattern. Used following the expansion of a macro. fn mark_pat(pat: Gc<ast::Pat>, m: Mrk) -> Gc<ast::Pat> { - new_mark_folder(m).fold_pat(pat) + Marker{mark:m}.fold_pat(pat) } // apply a given mark to the given stmt. Used following the expansion of a macro. fn mark_stmt(expr: &ast::Stmt, m: Mrk) -> Gc<ast::Stmt> { - new_mark_folder(m).fold_stmt(expr) + Marker{mark:m}.fold_stmt(expr) .expect_one("marking a stmt didn't return a stmt") } // apply a given mark to the given item. Used following the expansion of a macro. fn mark_item(expr: Gc<ast::Item>, m: Mrk) -> SmallVector<Gc<ast::Item>> { - new_mark_folder(m).fold_item(expr) + Marker{mark:m}.fold_item(expr) } fn original_span(cx: &ExtCtxt) -> Gc<codemap::ExpnInfo> { @@ -1013,7 +1039,8 @@ fn original_span(cx: &ExtCtxt) -> Gc<codemap::ExpnInfo> { #[cfg(test)] mod test { - use super::{new_name_finder, expand_crate, contains_macro_escape}; + use super::{pattern_bindings, expand_crate, contains_macro_escape}; + use super::{NameFinderContext}; use ast; use ast::{Attribute_, AttrOuter, MetaWord}; use attr; @@ -1043,22 +1070,22 @@ mod test { match *expr { ast::Expr{id:_,span:_,node:ast::ExprPath(ref p)} => { self.path_accumulator.push(p.clone()); - // not calling visit_path, should be fine. + // not calling visit_path, but it should be fine. } _ => visit::walk_expr(self,expr,()) } } } - // return a visitor that extracts the paths - // from a given thingy and puts them in a mutable - // array (passed in to the traversal) - fn new_path_finder(paths: Vec<ast::Path> ) -> PathExprFinderContext { - PathExprFinderContext { - path_accumulator: paths - } + // find the variable references in a crate + fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> { + let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()}; + visit::walk_crate(&mut path_finder, the_crate, ()); + path_finder.path_accumulator } + + // these following tests are quite fragile, in that they don't test what // *kind* of failure occurs. @@ -1150,6 +1177,14 @@ mod test { expand_crate(&ps,cfg,vec!(),vec!(),crate_ast) } + // find the pat_ident paths in a crate + fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> { + let mut name_finder = NameFinderContext{ident_accumulator:Vec::new()}; + visit::walk_crate(&mut name_finder, the_crate, ()); + name_finder.ident_accumulator + } + + //fn expand_and_resolve(crate_str: @str) -> ast::crate { //let expanded_ast = expand_crate_str(crate_str); // println!("expanded: {:?}\n",expanded_ast); @@ -1246,15 +1281,27 @@ mod test { 0) } - // FIXME #9384, match variable hygiene. Should expand into - // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 => x_2 + x_1}}}} - #[ignore] + // match variable hygiene. Should expand into + // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}} #[test] fn issue_9384(){ run_renaming_test( - &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x => x + $ex}})) - fn z() {match 8 {x => bad_macro!(_x)}}", + &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}})) + fn z() {match 8 {x => bad_macro!(x)}}", // NB: the third "binding" is the repeat of the second one. - vec!(vec!(1),vec!(0),vec!(0)), + vec!(vec!(1,3),vec!(0,2),vec!(0,2)), + true), + 0) + } + + // interpolated nodes weren't getting labeled. + // should expand into + // fn main(){let g1_1 = 13; g1_1}} + #[test] fn pat_expand_issue_15221(){ + run_renaming_test( + &("macro_rules! inner ( ($e:pat ) => ($e)) + macro_rules! outer ( ($e:pat ) => (inner!($e))) + fn main() { let outer!(g) = 13; g;}", + vec!(vec!(0)), true), 0) } @@ -1283,15 +1330,8 @@ mod test { (ref str,ref conns, bic) => (str.to_owned(), conns.clone(), bic) }; let cr = expand_crate_str(teststr.to_string()); - // find the bindings: - let mut name_finder = new_name_finder(Vec::new()); - visit::walk_crate(&mut name_finder,&cr,()); - let bindings = name_finder.ident_accumulator; - - // find the varrefs: - let mut path_finder = new_path_finder(Vec::new()); - visit::walk_crate(&mut path_finder,&cr,()); - let varrefs = path_finder.path_accumulator; + let bindings = crate_bindings(&cr); + let varrefs = crate_varrefs(&cr); // must be one check clause for each binding: assert_eq!(bindings.len(),bound_connections.len()); @@ -1315,9 +1355,13 @@ mod test { .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: {:?}",varref); - println!("binding: {:?}", *bindings.get(binding_idx)); + println!("varref #{}: {}",idx, varref_idents); + println!("binding #{}: {}", binding_idx, *bindings.get(binding_idx)); mtwt::with_sctable(|x| mtwt::display_sctable(x)); } assert_eq!(varref_name,binding_name); @@ -1332,11 +1376,15 @@ mod test { == 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: {:?}",varref); + println!("varref: {}",varref_idents); // good lord, you can't make a path with 0 segments, can you? let string = token::get_ident(varref.segments .get(0) @@ -1344,7 +1392,7 @@ mod test { println!("varref's first segment's uint: {}, and string: \"{}\"", varref.segments.get(0).identifier.name, string.get()); - println!("binding: {:?}", *bindings.get(binding_idx)); + println!("binding: {}", *bindings.get(binding_idx)); mtwt::with_sctable(|x| mtwt::display_sctable(x)); } assert!(!fail); @@ -1360,10 +1408,7 @@ foo_module!() ".to_string(); let cr = expand_crate_str(crate_str); // find the xx binding - let mut name_finder = new_name_finder(Vec::new()); - visit::walk_crate(&mut name_finder, &cr, ()); - let bindings = name_finder.ident_accumulator; - + let bindings = crate_bindings(&cr); let cxbinds: Vec<&ast::Ident> = bindings.iter().filter(|b| { let ident = token::get_ident(**b); @@ -1376,10 +1421,7 @@ foo_module!() _ => fail!("expected just one binding for ext_cx") }; let resolved_binding = mtwt::resolve(*cxbind); - // find all the xx varrefs: - let mut path_finder = new_path_finder(Vec::new()); - visit::walk_crate(&mut path_finder, &cr, ()); - let varrefs = path_finder.path_accumulator; + let varrefs = crate_varrefs(&cr); // the xx binding should bind all of the xx varrefs: for (idx,v) in varrefs.iter().filter(|p| { @@ -1405,10 +1447,8 @@ foo_module!() fn pat_idents(){ let pat = string_to_pat( "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string()); - let mut pat_idents = new_name_finder(Vec::new()); - pat_idents.visit_pat(pat, ()); - assert_eq!(pat_idents.ident_accumulator, - strs_to_idents(vec!("a","c","b","d"))); + let idents = pattern_bindings(pat); + assert_eq!(idents, strs_to_idents(vec!("a","c","b","d"))); } // test the list of identifier patterns gathered by the visitor. Note that @@ -1418,12 +1458,10 @@ foo_module!() fn crate_idents(){ let the_crate = string_to_crate("fn main (a : int) -> int {|b| { match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string()); - let mut idents = new_name_finder(Vec::new()); - //visit::walk_crate(&mut idents, &the_crate, ()); - idents.visit_mod(&the_crate.module, the_crate.span, ast::CRATE_NODE_ID, ()); - assert_eq!(idents.ident_accumulator, - strs_to_idents(vec!("a","b","None","i","i","z","y"))); + let idents = crate_bindings(&the_crate); + assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y"))); } + // } diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 6c97a8aed1f..48895d34022 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -30,6 +30,7 @@ use std::collections::HashMap; // 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>>, @@ -160,7 +161,7 @@ fn with_resolve_table_mut<T>(op: |&mut ResolveTable| -> T) -> T { } // Resolve a syntax object to a name, per MTWT. -// adding memorization to possibly resolve 500+ seconds in resolve for librustc (!) +// adding memoization to resolve 500+ seconds in resolve for librustc (!) fn resolve_internal(id: Ident, table: &SCTable, resolve_table: &mut ResolveTable) -> Name { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 6d2b0ceed8b..c6177ce31f5 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -86,7 +86,7 @@ pub trait Folder { kind: sf.node.kind, id: id, ty: self.fold_ty(sf.node.ty), - attrs: sf.node.attrs.iter().map(|e| fold_attribute_(*e, self)).collect() + attrs: sf.node.attrs.iter().map(|e| self.fold_attribute(*e)).collect() }, span: self.new_span(sf.span) } @@ -118,7 +118,7 @@ pub trait Folder { fn fold_arm(&mut self, a: &Arm) -> Arm { Arm { - attrs: a.attrs.iter().map(|x| fold_attribute_(*x, self)).collect(), + attrs: a.attrs.iter().map(|x| self.fold_attribute(*x)).collect(), pats: a.pats.iter().map(|x| self.fold_pat(*x)).collect(), guard: a.guard.map(|x| self.fold_expr(x)), body: self.fold_expr(a.body), @@ -251,7 +251,7 @@ pub trait Folder { } } - let attrs = v.node.attrs.iter().map(|x| fold_attribute_(*x, self)).collect(); + let attrs = v.node.attrs.iter().map(|x| self.fold_attribute(*x)).collect(); let de = match v.node.disr_expr { Some(e) => Some(self.fold_expr(e)), @@ -344,6 +344,21 @@ pub trait Folder { fn fold_lifetime(&mut self, l: &Lifetime) -> Lifetime { noop_fold_lifetime(l, self) } + + //used in noop_fold_item and noop_fold_crate + fn fold_attribute(&mut self, at: Attribute) -> Attribute { + Spanned { + span: self.new_span(at.span), + node: ast::Attribute_ { + id: at.node.id, + style: at.node.style, + value: fold_meta_item_(at.node.value, self), + is_sugared_doc: at.node.is_sugared_doc + } + } + } + + } /* some little folds that probably aren't useful to have in Folder itself*/ @@ -364,19 +379,6 @@ fn fold_meta_item_<T: Folder>(mi: Gc<MetaItem>, fld: &mut T) -> Gc<MetaItem> { span: fld.new_span(mi.span) } } -//used in noop_fold_item and noop_fold_crate -fn fold_attribute_<T: Folder>(at: Attribute, fld: &mut T) -> Attribute { - Spanned { - span: fld.new_span(at.span), - node: ast::Attribute_ { - id: at.node.id, - style: at.node.style, - value: fold_meta_item_(at.node.value, fld), - is_sugared_doc: at.node.is_sugared_doc - } - } -} - //used in noop_fold_foreign_item and noop_fold_fn_decl fn fold_arg_<T: Folder>(a: &Arg, fld: &mut T) -> Arg { let id = fld.new_id(a.id); // Needs to be first, for ast_map. @@ -387,53 +389,80 @@ fn fold_arg_<T: Folder>(a: &Arg, fld: &mut T) -> Arg { } } -// build a new vector of tts by appling the Folder's fold_ident to -// all of the identifiers in the token trees. -// -// This is part of hygiene magic. As far as hygiene is concerned, there -// are three types of let pattern bindings or loop labels: -// - those defined and used in non-macro part of the program -// - those used as part of macro invocation arguments -// - those defined and used inside macro definitions -// Lexically, type 1 and 2 are in one group and type 3 the other. If they -// clash, in order for let and loop label to work hygienically, one group -// or the other needs to be renamed. The problem is that type 2 and 3 are -// parsed together (inside the macro expand function). After being parsed and -// AST being constructed, they can no longer be distinguished from each other. -// -// For that reason, type 2 let bindings and loop labels are actually renamed -// in the form of tokens instead of AST nodes, here. There are wasted effort -// since many token::IDENT are not necessary part of let bindings and most -// token::LIFETIME are certainly not loop labels. But we can't tell in their -// token form. So this is less ideal and hacky but it works. -pub fn fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> { - tts.iter().map(|tt| { - match *tt { - TTTok(span, ref tok) => - TTTok(span,maybe_fold_ident(tok,fld)), - TTDelim(ref tts) => TTDelim(Rc::new(fold_tts(tts.as_slice(), fld))), - TTSeq(span, ref pattern, ref sep, is_optional) => +pub fn fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree { + match *tt { + TTTok(span, ref tok) => + TTTok(span, fold_token(tok,fld)), + TTDelim(ref tts) => TTDelim(Rc::new(fold_tts(tts.as_slice(), fld))), + TTSeq(span, ref pattern, ref sep, is_optional) => TTSeq(span, Rc::new(fold_tts(pattern.as_slice(), fld)), - sep.as_ref().map(|tok|maybe_fold_ident(tok,fld)), + sep.as_ref().map(|tok| fold_token(tok,fld)), is_optional), - TTNonterminal(sp,ref ident) => + TTNonterminal(sp,ref ident) => TTNonterminal(sp,fld.fold_ident(*ident)) - } - }).collect() + } +} + +pub fn fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> { + tts.iter().map(|tt| fold_tt(tt,fld)).collect() } -// apply ident folder if it's an ident, otherwise leave it alone -fn maybe_fold_ident<T: Folder>(t: &token::Token, fld: &mut T) -> token::Token { + +// apply ident folder if it's an ident, apply other folds to interpolated nodes +fn fold_token<T: Folder>(t: &token::Token, fld: &mut T) -> token::Token { match *t { token::IDENT(id, followed_by_colons) => { token::IDENT(fld.fold_ident(id), followed_by_colons) } token::LIFETIME(id) => token::LIFETIME(fld.fold_ident(id)), + token::INTERPOLATED(ref nt) => token::INTERPOLATED(fold_interpolated(nt,fld)), _ => (*t).clone() } } +// apply folder to elements of interpolated nodes +// +// NB: this can occur only when applying a fold to partially expanded code, where +// parsed pieces have gotten implanted ito *other* macro invocations. This is relevant +// for macro hygiene, but possibly not elsewhere. +// +// One problem here occurs because the types for fold_item, fold_stmt, etc. allow the +// folder to return *multiple* items; this is a problem for the nodes here, because +// they insist on having exactly one piece. One solution would be to mangle the fold +// trait to include one-to-many and one-to-one versions of these entry points, but that +// would probably confuse a lot of people and help very few. Instead, I'm just going +// to put in dynamic checks. I think the performance impact of this will be pretty much +// nonexistent. The danger is that someone will apply a fold to a partially expanded +// node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't +// getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this +// comment, and doing something appropriate. +// +// BTW, design choice: I considered just changing the type of, e.g., NtItem to contain +// multiple items, but decided against it when I looked at parse_item_or_view_item and +// tried to figure out what I would do with multiple items there.... +fn fold_interpolated<T: Folder>(nt : &token::Nonterminal, fld: &mut T) -> token::Nonterminal { + match *nt { + token::NtItem(item) => + token::NtItem(fld.fold_item(item) + .expect_one("expected fold to produce exactly one item")), + token::NtBlock(block) => token::NtBlock(fld.fold_block(block)), + token::NtStmt(stmt) => + token::NtStmt(fld.fold_stmt(stmt) + .expect_one("expected fold to produce exactly one statement")), + token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)), + token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)), + token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)), + token::NtIdent(ref id, is_mod_name) => + token::NtIdent(box fld.fold_ident(**id),is_mod_name), + token::NtMeta(meta_item) => token::NtMeta(fold_meta_item_(meta_item,fld)), + token::NtPath(ref path) => token::NtPath(box fld.fold_path(*path)), + token::NtTT(tt) => token::NtTT(box (GC) fold_tt(tt,fld)), + // it looks to me like we can leave out the matchers: token::NtMatchers(matchers) + _ => (*nt).clone() + } +} + pub fn noop_fold_fn_decl<T: Folder>(decl: &FnDecl, fld: &mut T) -> P<FnDecl> { P(FnDecl { inputs: decl.inputs.iter().map(|x| fold_arg_(x, fld)).collect(), // bad copy @@ -526,7 +555,7 @@ fn fold_struct_field<T: Folder>(f: &StructField, fld: &mut T) -> StructField { kind: f.node.kind, id: id, ty: fld.fold_ty(f.node.ty), - attrs: f.node.attrs.iter().map(|a| fold_attribute_(*a, fld)).collect(), + attrs: f.node.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(), }, span: fld.new_span(f.span), } @@ -578,7 +607,7 @@ pub fn noop_fold_view_item<T: Folder>(vi: &ViewItem, folder: &mut T) }; ViewItem { node: inner_view_item, - attrs: vi.attrs.iter().map(|a| fold_attribute_(*a, folder)).collect(), + attrs: vi.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(), vis: vi.vis, span: folder.new_span(vi.span), } @@ -658,7 +687,7 @@ pub fn noop_fold_type_method<T: Folder>(m: &TypeMethod, fld: &mut T) -> TypeMeth TypeMethod { id: id, ident: fld.fold_ident(m.ident), - attrs: m.attrs.iter().map(|a| fold_attribute_(*a, fld)).collect(), + attrs: m.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(), fn_style: m.fn_style, decl: fld.fold_fn_decl(&*m.decl), generics: fold_generics(&m.generics, fld), @@ -681,14 +710,21 @@ pub fn noop_fold_mod<T: Folder>(m: &Mod, folder: &mut T) -> Mod { pub fn noop_fold_crate<T: Folder>(c: Crate, folder: &mut T) -> Crate { Crate { module: folder.fold_mod(&c.module), - attrs: c.attrs.iter().map(|x| fold_attribute_(*x, folder)).collect(), + attrs: c.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(), config: c.config.iter().map(|x| fold_meta_item_(*x, folder)).collect(), span: folder.new_span(c.span), } } +// fold one item into possibly many items pub fn noop_fold_item<T: Folder>(i: &Item, folder: &mut T) -> SmallVector<Gc<Item>> { + SmallVector::one(box(GC) noop_fold_item_(i,folder)) +} + + +// fold one item into exactly one item +pub fn noop_fold_item_<T: Folder>(i: &Item, folder: &mut T) -> Item { let id = folder.new_id(i.id); // Needs to be first, for ast_map. let node = folder.fold_item_underscore(&i.node); let ident = match node { @@ -699,14 +735,14 @@ pub fn noop_fold_item<T: Folder>(i: &Item, _ => i.ident }; - SmallVector::one(box(GC) Item { + Item { id: id, ident: folder.fold_ident(ident), - attrs: i.attrs.iter().map(|e| fold_attribute_(*e, folder)).collect(), + attrs: i.attrs.iter().map(|e| folder.fold_attribute(*e)).collect(), node: node, vis: i.vis, span: folder.new_span(i.span) - }) + } } pub fn noop_fold_foreign_item<T: Folder>(ni: &ForeignItem, @@ -715,7 +751,7 @@ pub fn noop_fold_foreign_item<T: Folder>(ni: &ForeignItem, box(GC) ForeignItem { id: id, ident: folder.fold_ident(ni.ident), - attrs: ni.attrs.iter().map(|x| fold_attribute_(*x, folder)).collect(), + attrs: ni.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(), node: match ni.node { ForeignItemFn(ref fdec, ref generics) => { ForeignItemFn(P(FnDecl { @@ -739,7 +775,7 @@ pub fn noop_fold_method<T: Folder>(m: &Method, folder: &mut T) -> Gc<Method> { box(GC) Method { id: id, ident: folder.fold_ident(m.ident), - attrs: m.attrs.iter().map(|a| fold_attribute_(*a, folder)).collect(), + attrs: m.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(), generics: fold_generics(&m.generics, folder), explicit_self: folder.fold_explicit_self(&m.explicit_self), fn_style: m.fn_style, diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 016dd879dcd..530ea013112 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -69,9 +69,9 @@ impl<T> OwnedSlice<T> { static PTR_MARKER: u8 = 0; let ptr = if self.data.is_null() { // length zero, i.e. this will never be read as a T. - &PTR_MARKER as *u8 as *T + &PTR_MARKER as *const u8 as *const T } else { - self.data as *T + self.data as *const T }; let slice: &[T] = unsafe {mem::transmute(raw::Slice { diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index ac570c88837..0f188fdf18a 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -1203,8 +1203,8 @@ impl<'a> StringReader<'a> { fn read_one_line_comment(&mut self) -> String { let val = self.read_to_eol(); - assert!((val.as_slice()[0] == '/' as u8 && val.as_slice()[1] == '/' as u8) - || (val.as_slice()[0] == '#' as u8 && val.as_slice()[1] == '!' as u8)); + assert!((val.as_bytes()[0] == '/' as u8 && val.as_bytes()[1] == '/' as u8) + || (val.as_bytes()[0] == '#' as u8 && val.as_bytes()[1] == '!' as u8)); return val; } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 1cb09bb8d89..0fd5a7086b7 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1448,7 +1448,11 @@ impl<'a> Parser<'a> { } else if self.eat_keyword(keywords::Const) { MutImmutable } else { - // NOTE: after a stage0 snap this should turn into a span_err. + let span = self.last_span; + self.span_err(span, + "bare raw pointers are no longer allowed, you should \ + likely use `*mut T`, but otherwise `*T` is now \ + known as `*const T`"); MutImmutable }; let t = self.parse_ty(true); diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 9549d5b8389..a93e8270d98 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -114,6 +114,7 @@ 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 NtPath(Box<ast::Path>), diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 87ed2076d61..a9cf4fbd9f0 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -479,7 +479,11 @@ impl<'a> State<'a> { } ast::TyPtr(ref mt) => { try!(word(&mut self.s, "*")); - try!(self.print_mt(mt)); + match mt.mutbl { + ast::MutMutable => try!(self.word_nbsp("mut")), + ast::MutImmutable => try!(self.word_nbsp("const")), + } + try!(self.print_type(&*mt.ty)); } ast::TyRptr(ref lifetime, ref mt) => { try!(word(&mut self.s, "&")); @@ -994,7 +998,7 @@ impl<'a> State<'a> { pub fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0; + let mut count = 0u; for attr in attrs.iter() { match attr.node.style { ast::AttrOuter => { @@ -1012,7 +1016,7 @@ impl<'a> State<'a> { pub fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0; + let mut count = 0u; for attr in attrs.iter() { match attr.node.style { ast::AttrInner => { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index d5cc2c7f304..43367611ab2 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -166,8 +166,8 @@ mod test { let v: SmallVector<int> = SmallVector::zero(); assert_eq!(0, v.len()); - assert_eq!(1, SmallVector::one(1).len()); - assert_eq!(5, SmallVector::many(vec!(1, 2, 3, 4, 5)).len()); + assert_eq!(1, SmallVector::one(1i).len()); + assert_eq!(5, SmallVector::many(vec!(1i, 2, 3, 4, 5)).len()); } #[test] @@ -215,7 +215,7 @@ mod test { #[test] #[should_fail] fn test_expect_one_many() { - SmallVector::many(vec!(1, 2)).expect_one(""); + SmallVector::many(vec!(1i, 2)).expect_one(""); } #[test] diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 7eeb2dd26a9..56694e28b66 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -66,28 +66,52 @@ pub mod terminfo; #[cfg(windows)] mod win; +/// A hack to work around the fact that `Box<Writer + Send>` does not +/// currently implement `Writer`. +pub struct WriterWrapper { + wrapped: Box<Writer + Send>, +} + +impl Writer for WriterWrapper { + #[inline] + fn write(&mut self, buf: &[u8]) -> IoResult<()> { + self.wrapped.write(buf) + } + + #[inline] + fn flush(&mut self) -> IoResult<()> { + self.wrapped.flush() + } +} + #[cfg(not(windows))] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. -pub fn stdout() -> Option<Box<Terminal<Box<Writer + Send>> + Send>> { - let ti: Option<TerminfoTerminal<Box<Writer + Send>>> - = Terminal::new(box std::io::stdout() as Box<Writer + Send>); - ti.map(|t| box t as Box<Terminal<Box<Writer + Send> + Send> + Send>) +pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { + let ti: Option<TerminfoTerminal<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stdout() as Box<Writer + Send>, + }); + ti.map(|t| box t as Box<Terminal<WriterWrapper> + Send>) } #[cfg(windows)] /// Return a Terminal wrapping stdout, or None if a terminal couldn't be /// opened. -pub fn stdout() -> Option<Box<Terminal<Box<Writer + Send> + Send> + Send>> { - let ti: Option<TerminfoTerminal<Box<Writer + Send>>> - = Terminal::new(box std::io::stdout() as Box<Writer + Send>); +pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> { + let ti: Option<TerminfoTerminal<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stdout() as Box<Writer + Send>, + }); match ti { - Some(t) => Some(box t as Box<Terminal<Box<Writer + Send> + Send> + Send>), + Some(t) => Some(box t as Box<Terminal<WriterWrapper> + Send>), None => { - let wc: Option<WinConsole<Box<Writer + Send>>> - = Terminal::new(box std::io::stdout() as Box<Writer + Send>); - wc.map(|w| box w as Box<Terminal<Box<Writer + Send> + Send> + Send>) + let wc: Option<WinConsole<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stdout() as Box<Writer + Send>, + }); + wc.map(|w| box w as Box<Terminal<WriterWrapper> + Send>) } } } @@ -95,25 +119,31 @@ pub fn stdout() -> Option<Box<Terminal<Box<Writer + Send> + Send> + Send>> { #[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. -pub fn stderr() -> Option<Box<Terminal<Box<Writer + Send> + Send> + Send> + Send> { - let ti: Option<TerminfoTerminal<Box<Writer + Send>>> - = Terminal::new(box std::io::stderr() as Box<Writer + Send>); - ti.map(|t| box t as Box<Terminal<Box<Writer + Send> + Send> + Send>) +pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send> + Send> { + let ti: Option<TerminfoTerminal<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stderr() as Box<Writer + Send>, + }); + ti.map(|t| box t as Box<Terminal<WriterWrapper> + Send>) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. -pub fn stderr() -> Option<Box<Terminal<Box<Writer + Send> + Send> + Send>> { - let ti: Option<TerminfoTerminal<Box<Writer + Send>>> - = Terminal::new(box std::io::stderr() as Box<Writer + Send>); +pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send> + Send> { + let ti: Option<TerminfoTerminal<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stderr() as Box<Writer + Send>, + }); match ti { - Some(t) => Some(box t as Box<Terminal<Box<Writer + Send> + Send> + Send>), + Some(t) => Some(box t as Box<Terminal<WriterWrapper> + Send>), None => { - let wc: Option<WinConsole<Box<Writer + Send>>> - = Terminal::new(box std::io::stderr() as Box<Writer + Send>); - wc.map(|w| box w as Box<Terminal<Box<Writer + Send> + Send> + Send>) + let wc: Option<WinConsole<WriterWrapper>> + = Terminal::new(WriterWrapper { + wrapped: box std::io::stderr() as Box<Writer + Send>, + }); + wc.map(|w| box w as Box<Terminal<WriterWrapper> + Send>) } } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 03773fad9a8..02f7ebc6d21 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -474,7 +474,7 @@ pub enum TestResult { } enum OutputLocation<T> { - Pretty(Box<term::Terminal<Box<Writer + Send>> + Send>), + Pretty(Box<term::Terminal<term::WriterWrapper> + Send>), Raw(T), } @@ -1104,7 +1104,7 @@ fn calc_result(desc: &TestDesc, task_succeeded: bool) -> TestResult { impl ToJson for Metric { fn to_json(&self) -> json::Json { - let mut map = box TreeMap::new(); + let mut map = TreeMap::new(); map.insert("value".to_string(), json::Number(self.value)); map.insert("noise".to_string(), json::Number(self.noise)); json::Object(map) diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index 8245c58fc5d..fc191c78eef 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -375,7 +375,7 @@ pub fn strptime(s: &str, format: &str) -> Result<Tm, String> { fn match_str(s: &str, pos: uint, needle: &str) -> bool { let mut i = pos; for ch in needle.bytes() { - if s[i] != ch { + if s.as_bytes()[i] != ch { return false; } i += 1u; @@ -1091,7 +1091,7 @@ mod tests { // `SetEnvironmentVariable`, which `os::setenv` internally uses. // It is why we use `putenv` here. extern { - fn _putenv(envstring: *libc::c_char) -> libc::c_int; + fn _putenv(envstring: *const libc::c_char) -> libc::c_int; } unsafe { diff --git a/src/liburl/lib.rs b/src/liburl/lib.rs index 93072095f9d..a60cc8e992b 100644 --- a/src/liburl/lib.rs +++ b/src/liburl/lib.rs @@ -546,7 +546,7 @@ fn get_authority(rawurl: &str) -> let mut host = "".to_string(); let mut port = None; - let mut colon_count = 0; + let mut colon_count = 0u; let mut pos = 0; let mut begin = 2; let mut end = len; diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index d1abde987eb..297afe4aa59 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -324,8 +324,8 @@ impl Uuid { let mut s: Vec<u8> = Vec::from_elem(32, 0u8); for i in range(0u, 16u) { let digit = format!("{:02x}", self.bytes[i] as uint); - *s.get_mut(i*2+0) = digit.as_slice()[0]; - *s.get_mut(i*2+1) = digit.as_slice()[1]; + *s.get_mut(i*2+0) = digit.as_bytes()[0]; + *s.get_mut(i*2+1) = digit.as_bytes()[1]; } str::from_utf8(s.as_slice()).unwrap().to_string() } diff --git a/src/snapshots.txt b/src/snapshots.txt index ac11d94d2e6..5c694b34193 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,11 @@ +S 2014-06-25 bab614f + freebsd-x86_64 14cb361c8fdefa2534bb6776a04815c08680ecd6 + linux-i386 8fec4845626c557431a4aa7bfb2b5cfc65ad9eda + linux-x86_64 2304534c8e2431a5da2086164dd3a3e019b87ecd + macos-i386 d9e348cc1f9021f0f8e8907880fded80afb5db5b + macos-x86_64 aa790195d1f8191dce2f990ec4323bcc69566288 + winnt-i386 19b67f8a583516553a4fe62e453eecc5c17aff8e + S 2014-06-21 db9af1d freebsd-x86_64 ef2bd0fc0b0efa2bd6f5c1eaa60a2ec8df533254 linux-i386 84339ea0f796ae468ef86797ef4587274bec19ea diff --git a/src/test/auxiliary/issue-8044.rs b/src/test/auxiliary/issue-8044.rs index c0c884f5480..d8f96e5abd4 100644 --- a/src/test/auxiliary/issue-8044.rs +++ b/src/test/auxiliary/issue-8044.rs @@ -23,5 +23,5 @@ pub fn leaf<V>(value: V) -> TreeItem<V> { } fn main() { - BTree::<int> { node: leaf(1) }; + BTree::<int> { node: leaf(1i) }; } diff --git a/src/test/auxiliary/issue-9906.rs b/src/test/auxiliary/issue-9906.rs index 1e746bf39db..c0cb501735d 100644 --- a/src/test/auxiliary/issue-9906.rs +++ b/src/test/auxiliary/issue-9906.rs @@ -22,6 +22,6 @@ mod other { } pub fn foo(){ - 1+1; + 1i+1; } } diff --git a/src/test/auxiliary/issue13507.rs b/src/test/auxiliary/issue13507.rs index 918ba0a2dce..ee7787d6fcc 100644 --- a/src/test/auxiliary/issue13507.rs +++ b/src/test/auxiliary/issue13507.rs @@ -64,7 +64,7 @@ pub mod testtypes { // As with ty_str, what type should be used for ty_vec? // Tests ty_ptr - pub type FooPtr = *u8; + pub type FooPtr = *const u8; // Skipping ty_rptr diff --git a/src/test/auxiliary/xcrate_static_addresses.rs b/src/test/auxiliary/xcrate_static_addresses.rs index 13705107cfe..8065533dd73 100644 --- a/src/test/auxiliary/xcrate_static_addresses.rs +++ b/src/test/auxiliary/xcrate_static_addresses.rs @@ -18,13 +18,13 @@ static global0: int = 4; pub static global2: &'static int = &global0; pub fn verify_same(a: &'static int) { - let a = a as *int as uint; - let b = &global as *int as uint; + let a = a as *const int as uint; + let b = &global as *const int as uint; assert_eq!(a, b); } pub fn verify_same2(a: &'static int) { - let a = a as *int as uint; - let b = global2 as *int as uint; + let a = a as *const int as uint; + let b = global2 as *const int as uint; assert_eq!(a, b); } diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 716646da37e..2b9abfbc350 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -15,7 +15,7 @@ // This also serves as a pipes test, because Arcs are implemented with pipes. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 extern crate time; diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index 2580e6cad21..afed753f455 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -15,7 +15,7 @@ // This also serves as a pipes test, because Arcs are implemented with pipes. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 extern crate time; diff --git a/src/test/bench/rt-spawn-rate.rs b/src/test/bench/rt-spawn-rate.rs index a091c6be9f8..2737c6df533 100644 --- a/src/test/bench/rt-spawn-rate.rs +++ b/src/test/bench/rt-spawn-rate.rs @@ -21,7 +21,7 @@ use std::uint; // return. #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 67be7d121a4..195c146c12f 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -183,7 +183,7 @@ fn main() { if line.len() == 0u { continue; } - match (line.as_slice()[0] as char, proc_mode) { + match (line.as_bytes()[0] as char, proc_mode) { // start processing if this is the one ('>', false) => { diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 0cb21807f92..2d98668496c 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -1,12 +1,43 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ // -// 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. +// contributed by the Rust Project Developers + +// Copyright (c) 2012-2014 The Rust Project Developers +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// - Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// - Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in +// the documentation and/or other materials provided with the +// distribution. +// +// - Neither the name of "The Computer Language Benchmarks Game" nor +// the name of "The Computer Language Shootout Benchmarks" nor the +// names of its contributors may be used to endorse or promote +// products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + #![feature(macro_rules)] #![feature(simd)] #![allow(experimental)] diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index a0ff8e8c1f9..e13c53407e4 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -38,7 +38,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #![feature(phase)] #[phase(plugin)] extern crate green; diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index 949cf439df1..8cec135944f 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #![feature(phase)] #![allow(non_snake_case_functions)] diff --git a/src/test/bench/silly-test-spawn.rs b/src/test/bench/silly-test-spawn.rs index fbd35c57adc..1e5eedfa8a9 100644 --- a/src/test/bench/silly-test-spawn.rs +++ b/src/test/bench/silly-test-spawn.rs @@ -17,7 +17,7 @@ extern crate green; extern crate rustuv; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/compile-fail/borrowck-anon-fields-tuple.rs b/src/test/compile-fail/borrowck-anon-fields-tuple.rs index ebaed01756f..9a452ed18f6 100644 --- a/src/test/compile-fail/borrowck-anon-fields-tuple.rs +++ b/src/test/compile-fail/borrowck-anon-fields-tuple.rs @@ -12,7 +12,7 @@ // anonymous fields of a tuple vs the same anonymous field. fn distinct_variant() { - let mut y = (1, 2); + let mut y = (1i, 2i); let a = match y { (ref mut a, _) => a @@ -27,7 +27,7 @@ fn distinct_variant() { } fn same_variant() { - let mut y = (1, 2); + let mut y = (1i, 2i); let a = match y { (ref mut a, _) => a diff --git a/src/test/compile-fail/borrowck-array-double-move.rs b/src/test/compile-fail/borrowck-array-double-move.rs index c7fb646f585..c872d0dc4b9 100644 --- a/src/test/compile-fail/borrowck-array-double-move.rs +++ b/src/test/compile-fail/borrowck-array-double-move.rs @@ -9,9 +9,9 @@ // except according to those terms. fn f() { - let mut a = [box 0, box 1]; + let mut a = [box 0i, box 1i]; drop(a[0]); - a[1] = box 2; + a[1] = box 2i; drop(a[0]); //~ ERROR use of moved value: `a[..]` } diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs index de68dd311c6..30aed76a4eb 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs @@ -14,7 +14,7 @@ use std::ops::Deref; struct Rc<T> { - value: *T + value: *const T } impl<T> Deref<T> for Rc<T> { diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs b/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs index 7aac9458e3c..5397c5b8a56 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs @@ -14,7 +14,7 @@ use std::ops::Deref; struct Rc<T> { - value: *T + value: *const T } impl<T> Deref<T> for Rc<T> { diff --git a/src/test/compile-fail/borrowck-break-uninit-2.rs b/src/test/compile-fail/borrowck-break-uninit-2.rs index de18759e30a..0b10ccfdca1 100644 --- a/src/test/compile-fail/borrowck-break-uninit-2.rs +++ b/src/test/compile-fail/borrowck-break-uninit-2.rs @@ -11,14 +11,14 @@ fn foo() -> int { let x: int; - while 1 != 2 { + while 1i != 2 { break; x = 0; } println!("{}", x); //~ ERROR use of possibly uninitialized variable: `x` - return 17; + return 17i; } fn main() { println!("{}", foo()); } diff --git a/src/test/compile-fail/borrowck-closures-mut-and-imm.rs b/src/test/compile-fail/borrowck-closures-mut-and-imm.rs index ce8b17ea40b..886026e45d9 100644 --- a/src/test/compile-fail/borrowck-closures-mut-and-imm.rs +++ b/src/test/compile-fail/borrowck-closures-mut-and-imm.rs @@ -21,37 +21,37 @@ fn set(x: &mut int) { } fn a() { - let mut x = 3; + let mut x = 3i; let c1 = || x = 4; let c2 = || x * 5; //~ ERROR cannot borrow `x` } fn b() { - let mut x = 3; + let mut x = 3i; let c1 = || set(&mut x); let c2 = || get(&x); //~ ERROR cannot borrow `x` } fn c() { - let mut x = 3; + let mut x = 3i; let c1 = || set(&mut x); let c2 = || x * 5; //~ ERROR cannot borrow `x` } fn d() { - let mut x = 3; + let mut x = 3i; let c2 = || x * 5; x = 5; //~ ERROR cannot assign } fn e() { - let mut x = 3; + let mut x = 3i; let c1 = || get(&x); x = 5; //~ ERROR cannot assign } fn f() { - let mut x = box 3; + let mut x = box 3i; let c1 = || get(&*x); *x = 5; //~ ERROR cannot assign } diff --git a/src/test/compile-fail/borrowck-closures-two-mut.rs b/src/test/compile-fail/borrowck-closures-two-mut.rs index e1967d4e6df..6d382854d49 100644 --- a/src/test/compile-fail/borrowck-closures-two-mut.rs +++ b/src/test/compile-fail/borrowck-closures-two-mut.rs @@ -14,7 +14,7 @@ fn a() { - let mut x = 3; + let mut x = 3i; let c1 = || x = 4; let c2 = || x = 5; //~ ERROR cannot borrow `x` as mutable more than once } @@ -24,19 +24,19 @@ fn set(x: &mut int) { } fn b() { - let mut x = 3; + let mut x = 3i; let c1 = || set(&mut x); let c2 = || set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once } fn c() { - let mut x = 3; + let mut x = 3i; let c1 = || x = 5; let c2 = || set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once } fn d() { - let mut x = 3; + let mut x = 3i; let c1 = || x = 5; let c2 = || { let _y = || set(&mut x); }; // (nested closure) //~^ ERROR cannot borrow `x` as mutable more than once diff --git a/src/test/compile-fail/borrowck-if-no-else.rs b/src/test/compile-fail/borrowck-if-no-else.rs index a35b36fd78c..854d42219ea 100644 --- a/src/test/compile-fail/borrowck-if-no-else.rs +++ b/src/test/compile-fail/borrowck-if-no-else.rs @@ -11,6 +11,6 @@ fn foo(x: int) { println!("{}", x); } fn main() { - let x: int; if 1 > 2 { x = 10; } + let x: int; if 1i > 2 { x = 10; } foo(x); //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/borrowck-if-with-else.rs b/src/test/compile-fail/borrowck-if-with-else.rs index 6e2dae0af7d..74888cca2d4 100644 --- a/src/test/compile-fail/borrowck-if-with-else.rs +++ b/src/test/compile-fail/borrowck-if-with-else.rs @@ -14,7 +14,7 @@ fn foo(x: int) { println!("{:?}", x); } fn main() { let x: int; - if 1 > 2 { + if 1i > 2 { println!("whoops"); } else { x = 10; diff --git a/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs b/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs index 8af10231921..d127e9345cd 100644 --- a/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs +++ b/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut _a = 3; + let mut _a = 3i; let _b = &mut _a; { let _c = &*_b; diff --git a/src/test/compile-fail/borrowck-issue-2657-1.rs b/src/test/compile-fail/borrowck-issue-2657-1.rs index 9313473d6c9..9d28b2a436f 100644 --- a/src/test/compile-fail/borrowck-issue-2657-1.rs +++ b/src/test/compile-fail/borrowck-issue-2657-1.rs @@ -9,11 +9,11 @@ // except according to those terms. fn main() { -let x = Some(box 1); -match x { - Some(ref _y) => { - let _a = x; //~ ERROR cannot move - } - _ => {} -} + let x = Some(box 1i); + match x { + Some(ref _y) => { + let _a = x; //~ ERROR cannot move + } + _ => {} + } } diff --git a/src/test/compile-fail/borrowck-issue-2657-2.rs b/src/test/compile-fail/borrowck-issue-2657-2.rs index 39c3ae8fdfd..973cf3bf8c8 100644 --- a/src/test/compile-fail/borrowck-issue-2657-2.rs +++ b/src/test/compile-fail/borrowck-issue-2657-2.rs @@ -9,11 +9,11 @@ // except according to those terms. fn main() { -let x = Some(box 1); -match x { - Some(ref y) => { - let _b = *y; //~ ERROR cannot move out - } - _ => {} -} + let x = Some(box 1i); + match x { + Some(ref y) => { + let _b = *y; //~ ERROR cannot move out + } + _ => {} + } } diff --git a/src/test/compile-fail/borrowck-lend-flow-match.rs b/src/test/compile-fail/borrowck-lend-flow-match.rs index 7a494b5959a..c6020df2bc2 100644 --- a/src/test/compile-fail/borrowck-lend-flow-match.rs +++ b/src/test/compile-fail/borrowck-lend-flow-match.rs @@ -35,20 +35,20 @@ fn guard() { // Here the guard performs a borrow. This borrow "infects" all // subsequent arms (but not the prior ones). - let mut a = box 3; - let mut b = box 4; + let mut a = box 3u; + let mut b = box 4u; let mut w = &*a; - match 22 { + match 22i { _ if cond() => { - b = box 5; + b = box 5u; } _ if link(&*b, &mut w) => { - b = box 6; //~ ERROR cannot assign + b = box 6u; //~ ERROR cannot assign } _ => { - b = box 7; //~ ERROR cannot assign + b = box 7u; //~ ERROR cannot assign } } diff --git a/src/test/compile-fail/borrowck-let-suggestion.rs b/src/test/compile-fail/borrowck-let-suggestion.rs index a03087f9b2d..385111170b1 100644 --- a/src/test/compile-fail/borrowck-let-suggestion.rs +++ b/src/test/compile-fail/borrowck-let-suggestion.rs @@ -9,9 +9,9 @@ // except according to those terms. fn f() { - let x = [1].iter(); //~ ERROR borrowed value does not live long enough - //~^^ NOTE reference must be valid for the block - //~^^ NOTE consider using a `let` binding to increase its lifetime + let x = [1i].iter(); //~ ERROR borrowed value does not live long enough + //~^^ NOTE reference must be valid for the block + //~^^ NOTE consider using a `let` binding to increase its lifetime } fn main() { diff --git a/src/test/compile-fail/borrowck-managed-pointer-deref-scope.rs b/src/test/compile-fail/borrowck-managed-pointer-deref-scope.rs index dba2c7dca76..30430e00ef3 100644 --- a/src/test/compile-fail/borrowck-managed-pointer-deref-scope.rs +++ b/src/test/compile-fail/borrowck-managed-pointer-deref-scope.rs @@ -24,10 +24,10 @@ fn foo<'a>(x: &'a Gc<int>) -> &'a int { } fn bar() { - let a = 3; + let a = 3i; let mut y = &a; if true { - let x = box(GC) 3; + let x = box(GC) 3i; y = &*x; //~ ERROR `*x` does not live long enough } } diff --git a/src/test/compile-fail/borrowck-match-binding-is-assignment.rs b/src/test/compile-fail/borrowck-match-binding-is-assignment.rs index 6b5dd570e34..f599f237ba6 100644 --- a/src/test/compile-fail/borrowck-match-binding-is-assignment.rs +++ b/src/test/compile-fail/borrowck-match-binding-is-assignment.rs @@ -43,7 +43,7 @@ pub fn main() { } } - match [1,2,3] { + match [1i,2,3] { [x,_,_] => { x += 1; //~ ERROR re-assignment of immutable variable `x` } diff --git a/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs b/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs index 35106487f34..63409f5afb0 100644 --- a/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs +++ b/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs @@ -12,7 +12,7 @@ // borrowed path. fn main() { - let a = box box 2; + let a = box box 2i; let b = &a; let z = *a; //~ ERROR: cannot move out of `*a` because it is borrowed diff --git a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs index c507b636f15..87bb8ef7a58 100644 --- a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs +++ b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn foo(x: *Box<int>) -> Box<int> { +fn foo(x: *const Box<int>) -> Box<int> { let y = *x; //~ ERROR dereference of unsafe pointer requires unsafe function or block return y; } diff --git a/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs b/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs index 1a96e5ef4b0..79626179163 100644 --- a/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs +++ b/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs @@ -11,6 +11,6 @@ use std::rc::Rc; pub fn main() { - let _x = Rc::new(vec!(1, 2)).move_iter(); + let _x = Rc::new(vec!(1i, 2)).move_iter(); //~^ ERROR cannot move out of dereference of `&`-pointer } diff --git a/src/test/compile-fail/borrowck-multiple-captures.rs b/src/test/compile-fail/borrowck-multiple-captures.rs index e12d2b91479..6faa634ad00 100644 --- a/src/test/compile-fail/borrowck-multiple-captures.rs +++ b/src/test/compile-fail/borrowck-multiple-captures.rs @@ -13,9 +13,9 @@ use std::task; fn borrow<T>(_: &T) { } fn different_vars_after_borrows() { - let x1 = box 1; + let x1 = box 1i; let p1 = &x1; - let x2 = box 2; + let x2 = box 2i; let p2 = &x2; task::spawn(proc() { drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed @@ -26,9 +26,9 @@ fn different_vars_after_borrows() { } fn different_vars_after_moves() { - let x1 = box 1; + let x1 = box 1i; drop(x1); - let x2 = box 2; + let x2 = box 2i; drop(x2); task::spawn(proc() { drop(x1); //~ ERROR capture of moved value: `x1` @@ -37,7 +37,7 @@ fn different_vars_after_moves() { } fn same_var_after_borrow() { - let x = box 1; + let x = box 1i; let p = &x; task::spawn(proc() { drop(x); //~ ERROR cannot move `x` into closure because it is borrowed @@ -47,7 +47,7 @@ fn same_var_after_borrow() { } fn same_var_after_move() { - let x = box 1; + let x = box 1i; drop(x); task::spawn(proc() { drop(x); //~ ERROR capture of moved value: `x` diff --git a/src/test/compile-fail/borrowck-preserve-box-in-field.rs b/src/test/compile-fail/borrowck-preserve-box-in-field.rs index 416c272b8ce..1ea4a98c45b 100644 --- a/src/test/compile-fail/borrowck-preserve-box-in-field.rs +++ b/src/test/compile-fail/borrowck-preserve-box-in-field.rs @@ -28,12 +28,12 @@ pub fn main() { borrow(x.f, |b_x| { //~^ ERROR cannot borrow `x` as mutable because `*x.f` is also borrowed as immutable assert_eq!(*b_x, 3); - assert_eq!(&(*x.f) as *int, &(*b_x) as *int); + assert_eq!(&(*x.f) as *const int, &(*b_x) as *const int); //~^ NOTE borrow occurs due to use of `x` in closure x = box(GC) F {f: box 4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); - assert!(&(*x.f) as *int != &(*b_x) as *int); + assert!(&(*x.f) as *const int != &(*b_x) as *const int); }) } diff --git a/src/test/compile-fail/borrowck-preserve-box-in-uniq.rs b/src/test/compile-fail/borrowck-preserve-box-in-uniq.rs index dcfead3a1c2..979791ad763 100644 --- a/src/test/compile-fail/borrowck-preserve-box-in-uniq.rs +++ b/src/test/compile-fail/borrowck-preserve-box-in-uniq.rs @@ -28,12 +28,12 @@ pub fn main() { borrow(x.f, |b_x| { //~^ ERROR cannot borrow `x` as mutable because `*x.f` is also borrowed as immutable assert_eq!(*b_x, 3); - assert_eq!(&(*x.f) as *int, &(*b_x) as *int); + assert_eq!(&(*x.f) as *const int, &(*b_x) as *const int); //~^ NOTE borrow occurs due to use of `x` in closure *x = box(GC) F{f: box 4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); - assert!(&(*x.f) as *int != &(*b_x) as *int); + assert!(&(*x.f) as *const int != &(*b_x) as *const int); }) } diff --git a/src/test/compile-fail/borrowck-preserve-box.rs b/src/test/compile-fail/borrowck-preserve-box.rs index ccf0fb3711a..9eadb62c3a0 100644 --- a/src/test/compile-fail/borrowck-preserve-box.rs +++ b/src/test/compile-fail/borrowck-preserve-box.rs @@ -26,12 +26,12 @@ pub fn main() { borrow(x, |b_x| { //~^ ERROR cannot borrow `x` as mutable because `*x` is also borrowed as immutable assert_eq!(*b_x, 3); - assert_eq!(&(*x) as *int, &(*b_x) as *int); + assert_eq!(&(*x) as *const int, &(*b_x) as *const int); //~^ NOTE borrow occurs due to use of `x` in closure x = box(GC) 22; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); - assert!(&(*x) as *int != &(*b_x) as *int); + assert!(&(*x) as *const int != &(*b_x) as *const int); }) } diff --git a/src/test/compile-fail/borrowck-preserve-expl-deref.rs b/src/test/compile-fail/borrowck-preserve-expl-deref.rs index 4a7a7b0f265..066bb53cdc4 100644 --- a/src/test/compile-fail/borrowck-preserve-expl-deref.rs +++ b/src/test/compile-fail/borrowck-preserve-expl-deref.rs @@ -28,12 +28,12 @@ pub fn main() { borrow((*x).f, |b_x| { //~^ ERROR cannot borrow `x` as mutable because `*x.f` is also borrowed as immutable assert_eq!(*b_x, 3); - assert_eq!(&(*x.f) as *int, &(*b_x) as *int); + assert_eq!(&(*x.f) as *const int, &(*b_x) as *const int); //~^ NOTE borrow occurs due to use of `x` in closure x = box(GC) F {f: box 4}; println!("&*b_x = {:p}", &(*b_x)); assert_eq!(*b_x, 3); - assert!(&(*x.f) as *int != &(*b_x) as *int); + assert!(&(*x.f) as *const int != &(*b_x) as *const int); }) } diff --git a/src/test/compile-fail/borrowck-uniq-via-lend.rs b/src/test/compile-fail/borrowck-uniq-via-lend.rs index fb03ad61f3d..5a129956487 100644 --- a/src/test/compile-fail/borrowck-uniq-via-lend.rs +++ b/src/test/compile-fail/borrowck-uniq-via-lend.rs @@ -12,7 +12,7 @@ fn borrow(_v: &int) {} fn local() { - let mut v = box 3; + let mut v = box 3i; borrow(v); } @@ -31,27 +31,27 @@ fn local_recs() { } fn aliased_imm() { - let mut v = box 3; + let mut v = box 3i; let _w = &v; borrow(v); } fn aliased_mut() { - let mut v = box 3; + let mut v = box 3i; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn aliased_other() { - let mut v = box 3; - let mut w = box 4; + let mut v = box 3i; + let mut w = box 4i; let _x = &mut w; borrow(v); } fn aliased_other_reassign() { - let mut v = box 3; - let mut w = box 4; + let mut v = box 3i; + let mut w = box 4i; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` diff --git a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs index cca8ed93388..7b092d16eec 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut a = [1, 2, 3, 4]; + let mut a = [1i, 2, 3, 4]; let t = match a { [1, 2, ..tail] => tail, _ => unreachable!() diff --git a/src/test/compile-fail/borrowck-vec-pattern-nesting.rs b/src/test/compile-fail/borrowck-vec-pattern-nesting.rs index f41f74b166f..4a56f982106 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-nesting.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-nesting.rs @@ -10,7 +10,7 @@ fn a() { - let mut vec = [box 1, box 2, box 3]; + let mut vec = [box 1i, box 2, box 3]; match vec { [box ref _a, _, _] => { vec[0] = box 4; //~ ERROR cannot assign @@ -19,7 +19,7 @@ fn a() { } fn b() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec!(box 1i, box 2, box 3); let vec: &mut [Box<int>] = vec.as_mut_slice(); match vec { [.._b] => { @@ -29,7 +29,7 @@ fn b() { } fn c() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec!(box 1i, box 2, box 3); let vec: &mut [Box<int>] = vec.as_mut_slice(); match vec { [_a, //~ ERROR cannot move out @@ -47,7 +47,7 @@ fn c() { } fn d() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec!(box 1i, box 2, box 3); let vec: &mut [Box<int>] = vec.as_mut_slice(); match vec { [.._a, //~ ERROR cannot move out @@ -58,7 +58,7 @@ fn d() { } fn e() { - let mut vec = vec!(box 1, box 2, box 3); + let mut vec = vec!(box 1i, box 2, box 3); let vec: &mut [Box<int>] = vec.as_mut_slice(); match vec { [_a, _b, _c] => {} //~ ERROR cannot move out diff --git a/src/test/compile-fail/borrowck-while.rs b/src/test/compile-fail/borrowck-while.rs index b904fd53d72..b5703e56642 100644 --- a/src/test/compile-fail/borrowck-while.rs +++ b/src/test/compile-fail/borrowck-while.rs @@ -10,7 +10,7 @@ fn f() -> int { let mut x: int; - while 1 == 1 { x = 10; } + while 1i == 1 { x = 10; } return x; //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/builtin-superkinds-self-type.rs b/src/test/compile-fail/builtin-superkinds-self-type.rs index 0d5a71559e8..bea025df6fc 100644 --- a/src/test/compile-fail/builtin-superkinds-self-type.rs +++ b/src/test/compile-fail/builtin-superkinds-self-type.rs @@ -21,6 +21,6 @@ impl <T: Share> Foo for T { } fn main() { let (tx, rx) = channel(); - 1193182.foo(tx); - assert!(rx.recv() == 1193182); + 1193182i.foo(tx); + assert!(rx.recv() == 1193182i); } diff --git a/src/test/compile-fail/const-block-non-item-statement.rs b/src/test/compile-fail/const-block-non-item-statement.rs index ace917c704a..d8f771cfb5a 100644 --- a/src/test/compile-fail/const-block-non-item-statement.rs +++ b/src/test/compile-fail/const-block-non-item-statement.rs @@ -10,7 +10,7 @@ #![feature(macro_rules)] -static A: uint = { 1; 2 }; +static A: uint = { 1u; 2 }; //~^ ERROR: blocks in constants are limited to items and tail expressions static B: uint = { { } 2 }; @@ -21,7 +21,7 @@ macro_rules! foo { } static C: uint = { foo!() 2 }; -static D: uint = { let x = 4; 2 }; +static D: uint = { let x = 4u; 2 }; //~^ ERROR: blocks in constants are limited to items and tail expressions pub fn main() { diff --git a/src/test/compile-fail/const-cast-different-types.rs b/src/test/compile-fail/const-cast-different-types.rs index 77c26d9e6de..f7d5ddb3145 100644 --- a/src/test/compile-fail/const-cast-different-types.rs +++ b/src/test/compile-fail/const-cast-different-types.rs @@ -9,8 +9,8 @@ // except according to those terms. static a: &'static str = "foo"; -static b: *u8 = a as *u8; //~ ERROR non-scalar cast -static c: *u8 = &a as *u8; //~ ERROR mismatched types +static b: *const u8 = a as *const u8; //~ ERROR non-scalar cast +static c: *const u8 = &a as *const u8; //~ ERROR mismatched types fn main() { } diff --git a/src/test/compile-fail/const-cast-wrong-type.rs b/src/test/compile-fail/const-cast-wrong-type.rs index 875358ea142..223426dc7c6 100644 --- a/src/test/compile-fail/const-cast-wrong-type.rs +++ b/src/test/compile-fail/const-cast-wrong-type.rs @@ -9,7 +9,7 @@ // except according to those terms. static a: [u8, ..3] = ['h' as u8, 'i' as u8, 0 as u8]; -static b: *i8 = &a as *i8; //~ ERROR mismatched types +static b: *const i8 = &a as *const i8; //~ ERROR mismatched types fn main() { } diff --git a/src/test/compile-fail/deriving-span-PartialOrd-enum-struct-variant.rs b/src/test/compile-fail/deriving-span-PartialOrd-enum-struct-variant.rs index 077286eef49..dd6c11d2b39 100644 --- a/src/test/compile-fail/deriving-span-PartialOrd-enum-struct-variant.rs +++ b/src/test/compile-fail/deriving-span-PartialOrd-enum-struct-variant.rs @@ -27,6 +27,7 @@ enum Enum { //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR +//~^^^^^^^^ ERROR } } diff --git a/src/test/compile-fail/deriving-span-PartialOrd-enum.rs b/src/test/compile-fail/deriving-span-PartialOrd-enum.rs index 8fd4ba6053e..1b3d73a6f8b 100644 --- a/src/test/compile-fail/deriving-span-PartialOrd-enum.rs +++ b/src/test/compile-fail/deriving-span-PartialOrd-enum.rs @@ -27,6 +27,7 @@ enum Enum { //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR +//~^^^^^^^^ ERROR ) } diff --git a/src/test/compile-fail/deriving-span-PartialOrd-struct.rs b/src/test/compile-fail/deriving-span-PartialOrd-struct.rs index 3a198a542e4..2ef3b4dfe8a 100644 --- a/src/test/compile-fail/deriving-span-PartialOrd-struct.rs +++ b/src/test/compile-fail/deriving-span-PartialOrd-struct.rs @@ -26,6 +26,7 @@ struct Struct { //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR +//~^^^^^^^^ ERROR } fn main() {} diff --git a/src/test/compile-fail/deriving-span-PartialOrd-tuple-struct.rs b/src/test/compile-fail/deriving-span-PartialOrd-tuple-struct.rs index 2de3c18425b..303896737dc 100644 --- a/src/test/compile-fail/deriving-span-PartialOrd-tuple-struct.rs +++ b/src/test/compile-fail/deriving-span-PartialOrd-tuple-struct.rs @@ -26,6 +26,7 @@ struct Struct( //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR +//~^^^^^^^^ ERROR ); fn main() {} diff --git a/src/test/compile-fail/drop-with-active-borrows-1.rs b/src/test/compile-fail/drop-with-active-borrows-1.rs new file mode 100644 index 00000000000..9d5020eaee8 --- /dev/null +++ b/src/test/compile-fail/drop-with-active-borrows-1.rs @@ -0,0 +1,19 @@ +// Copyright 2012 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 a = "".to_string(); + let b: Vec<&str> = a.as_slice().lines().collect(); + drop(a); //~ ERROR cannot move out of `a` because it is borrowed + for s in b.iter() { + println!("{}", *s); + } +} + diff --git a/src/test/compile-fail/drop-with-active-borrows-2.rs b/src/test/compile-fail/drop-with-active-borrows-2.rs new file mode 100644 index 00000000000..2700ceff68a --- /dev/null +++ b/src/test/compile-fail/drop-with-active-borrows-2.rs @@ -0,0 +1,19 @@ +// Copyright 2012 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 read_lines_borrowed() -> Vec<&str> { + let raw_lines: Vec<String> = vec!("foo ".to_string(), " bar".to_string()); + raw_lines.iter().map(|l| l.as_slice().trim()).collect() + //~^ ERROR `raw_lines` does not live long enough +} + +fn main() { + println!("{}", read_lines_borrowed()); +} diff --git a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs index 8b00b614909..8de613ac03d 100644 --- a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs +++ b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs @@ -11,6 +11,6 @@ fn main() { for - &1 //~ ERROR refutable pattern in `for` loop binding - in [1].iter() {} + &1i //~ ERROR refutable pattern in `for` loop binding + in [1i].iter() {} } diff --git a/src/test/compile-fail/integer-literal-suffix-inference-2.rs b/src/test/compile-fail/integer-literal-suffix-inference-2.rs new file mode 100644 index 00000000000..7c862d04d20 --- /dev/null +++ b/src/test/compile-fail/integer-literal-suffix-inference-2.rs @@ -0,0 +1,17 @@ +// Copyright 2012 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 foo(_: *const ()) {} + +fn main() { + let a = 3; //~ ERROR cannot determine a type for this local variable + foo(&a as *const _ as *const ()); +} + diff --git a/src/test/compile-fail/integer-literal-suffix-inference-3.rs b/src/test/compile-fail/integer-literal-suffix-inference-3.rs new file mode 100644 index 00000000000..dc3db985660 --- /dev/null +++ b/src/test/compile-fail/integer-literal-suffix-inference-3.rs @@ -0,0 +1,15 @@ +// Copyright 2012 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() { + println!("{}", std::mem::size_of_val(&1)); + //~^ ERROR cannot determine a type for this expression +} + diff --git a/src/test/compile-fail/integral-indexing.rs b/src/test/compile-fail/integral-indexing.rs index 967229a3407..8b1f9eb1986 100644 --- a/src/test/compile-fail/integral-indexing.rs +++ b/src/test/compile-fail/integral-indexing.rs @@ -17,10 +17,10 @@ pub fn main() { assert_eq!(v.as_slice()[3u32], 3); //~ ERROR: mismatched types assert_eq!(v.as_slice()[3i32], 3); //~ ERROR: mismatched types println!("{}", v.as_slice()[3u8]); //~ ERROR: mismatched types - assert_eq!(s.as_slice()[3u], 'd' as u8); - assert_eq!(s.as_slice()[3u8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_slice()[3i8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_slice()[3u32], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_slice()[3i32], 'd' as u8); //~ ERROR: mismatched types - println!("{}", s.as_slice()[3u8]); //~ ERROR: mismatched types + assert_eq!(s.as_bytes()[3u], 'd' as u8); + assert_eq!(s.as_bytes()[3u8], 'd' as u8); //~ ERROR: mismatched types + assert_eq!(s.as_bytes()[3i8], 'd' as u8); //~ ERROR: mismatched types + assert_eq!(s.as_bytes()[3u32], 'd' as u8); //~ ERROR: mismatched types + assert_eq!(s.as_bytes()[3i32], 'd' as u8); //~ ERROR: mismatched types + println!("{}", s.as_bytes()[3u8]); //~ ERROR: mismatched types } diff --git a/src/test/compile-fail/issue-10398.rs b/src/test/compile-fail/issue-10398.rs index 97642377ba8..9141ab669bb 100644 --- a/src/test/compile-fail/issue-10398.rs +++ b/src/test/compile-fail/issue-10398.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = box 1; + let x = box 1i; let f: proc() = proc() { let _a = x; drop(x); diff --git a/src/test/compile-fail/issue-11493.rs b/src/test/compile-fail/issue-11493.rs index 333ff7118d4..7856a5dcf7f 100644 --- a/src/test/compile-fail/issue-11493.rs +++ b/src/test/compile-fail/issue-11493.rs @@ -11,6 +11,6 @@ // This file must never have a trailing newline fn main() { - let x = Some(3); - let y = x.as_ref().unwrap_or(&5); //~ ERROR: borrowed value does not live long enough + let x = Some(3i); + let y = x.as_ref().unwrap_or(&5i); //~ ERROR: borrowed value does not live long enough } diff --git a/src/test/compile-fail/issue-11873.rs b/src/test/compile-fail/issue-11873.rs index 0ca326c1e0d..e1acab4008a 100644 --- a/src/test/compile-fail/issue-11873.rs +++ b/src/test/compile-fail/issue-11873.rs @@ -9,8 +9,8 @@ // except according to those terms. fn main() { - let mut v = vec!(1); - let f = || v.push(2); + let mut v = vec!(1i); + let f = || v.push(2i); let _w = v; //~ ERROR: cannot move out of `v` f(); diff --git a/src/test/compile-fail/issue-11925.rs b/src/test/compile-fail/issue-11925.rs index a8d2c7509ce..5d62c25ea17 100644 --- a/src/test/compile-fail/issue-11925.rs +++ b/src/test/compile-fail/issue-11925.rs @@ -10,7 +10,7 @@ fn main() { let r = { - let x = box 42; + let x = box 42i; let f = proc() &x; //~ ERROR: `x` does not live long enough f() }; diff --git a/src/test/compile-fail/issue-12041.rs b/src/test/compile-fail/issue-12041.rs index 9ad59367312..f824a06aed1 100644 --- a/src/test/compile-fail/issue-12041.rs +++ b/src/test/compile-fail/issue-12041.rs @@ -14,7 +14,7 @@ fn main() { loop { let tx = tx; //~^ ERROR: use of moved value: `tx` - tx.send(1); + tx.send(1i); } }); } diff --git a/src/test/compile-fail/issue-12552.rs b/src/test/compile-fail/issue-12552.rs new file mode 100644 index 00000000000..e4788bac256 --- /dev/null +++ b/src/test/compile-fail/issue-12552.rs @@ -0,0 +1,21 @@ +// 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. + +// this code used to cause an ICE + +fn main() { + let t = Err(0); + match t { + Some(k) => match k { //~ ERROR mismatched types + a => println!("{}", a) + }, + None => () //~ ERROR mismatched types + } +} diff --git a/src/test/compile-fail/issue-14254.rs b/src/test/compile-fail/issue-14254.rs index 8b7267ab776..dc19b9d51c8 100644 --- a/src/test/compile-fail/issue-14254.rs +++ b/src/test/compile-fail/issue-14254.rs @@ -24,7 +24,7 @@ impl BarTy { fn b(&self) {} } -impl Foo for *BarTy { +impl Foo for *const BarTy { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? @@ -76,7 +76,7 @@ impl Foo for Box<BarTy> { } } -impl Foo for *int { +impl Foo for *const int { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? diff --git a/src/test/compile-fail/issue-15260.rs b/src/test/compile-fail/issue-15260.rs new file mode 100644 index 00000000000..06826139884 --- /dev/null +++ b/src/test/compile-fail/issue-15260.rs @@ -0,0 +1,19 @@ +// 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. + +struct Foo { + a: uint, +} + +fn main(){ + let Foo {a: _, a: _} = Foo {a: 29}; + //~^ ERROR field `a` bound twice in pattern +} + diff --git a/src/test/compile-fail/issue-1962.rs b/src/test/compile-fail/issue-1962.rs index db3e9c23b76..c59ee328eff 100644 --- a/src/test/compile-fail/issue-1962.rs +++ b/src/test/compile-fail/issue-1962.rs @@ -10,9 +10,9 @@ // compile-flags: -D while-true fn main() { - let mut i = 0; + let mut i = 0i; while true { //~ ERROR denote infinite loops with loop - i += 1; - if i == 5 { break; } + i += 1i; + if i == 5i { break; } } } diff --git a/src/test/compile-fail/issue-2995.rs b/src/test/compile-fail/issue-2995.rs index ea8ee8699e4..920897e6828 100644 --- a/src/test/compile-fail/issue-2995.rs +++ b/src/test/compile-fail/issue-2995.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn bad (p: *int) { +fn bad (p: *const int) { let _q: &int = p as ∫ //~ ERROR non-scalar cast } diff --git a/src/test/compile-fail/issue-3096-2.rs b/src/test/compile-fail/issue-3096-2.rs index 799f5b4d532..2d1ad9a2692 100644 --- a/src/test/compile-fail/issue-3096-2.rs +++ b/src/test/compile-fail/issue-3096-2.rs @@ -11,6 +11,6 @@ enum bottom { } fn main() { - let x = &() as *() as *bottom; + let x = &() as *const () as *const bottom; match x { } //~ ERROR non-exhaustive patterns } diff --git a/src/test/compile-fail/issue-3344.rs b/src/test/compile-fail/issue-3344.rs index d6fe83a7703..293f372866d 100644 --- a/src/test/compile-fail/issue-3344.rs +++ b/src/test/compile-fail/issue-3344.rs @@ -10,7 +10,7 @@ #[deriving(PartialEq)] struct thing(uint); -impl PartialOrd for thing { //~ ERROR not all trait methods implemented, missing: `lt` +impl PartialOrd for thing { //~ ERROR not all trait methods implemented, missing: `partial_cmp` fn le(&self, other: &thing) -> bool { true } fn ge(&self, other: &thing) -> bool { true } } diff --git a/src/test/compile-fail/issue-3707.rs b/src/test/compile-fail/issue-3707.rs index 4e128b63e92..2445638d62e 100644 --- a/src/test/compile-fail/issue-3707.rs +++ b/src/test/compile-fail/issue-3707.rs @@ -14,7 +14,7 @@ struct Obj { impl Obj { pub fn boom() -> bool { - return 1+1 == 2 + return 1i+1 == 2 } pub fn chirp(&self) { self.boom(); //~ ERROR `&Obj` does not implement any method in scope named `boom` @@ -24,5 +24,5 @@ impl Obj { fn main() { let o = Obj { member: 0 }; o.chirp(); - 1 + 1; + 1i + 1; } diff --git a/src/test/compile-fail/issue-9575.rs b/src/test/compile-fail/issue-9575.rs index cc03361ee27..aa3d9d9fef0 100644 --- a/src/test/compile-fail/issue-9575.rs +++ b/src/test/compile-fail/issue-9575.rs @@ -9,7 +9,7 @@ // except according to those terms. #[start] -fn start(argc: int, argv: **u8, crate_map: *u8) -> int { - //~^ ERROR start function expects type: `fn(int, **u8) -> int` +fn start(argc: int, argv: *const *const u8, crate_map: *const u8) -> int { + //~^ ERROR start function expects type: `fn(int, *const *const u8) -> int` 0 } diff --git a/src/test/compile-fail/kindck-copy.rs b/src/test/compile-fail/kindck-copy.rs index 06232580198..f2a3d86ef0f 100644 --- a/src/test/compile-fail/kindck-copy.rs +++ b/src/test/compile-fail/kindck-copy.rs @@ -60,8 +60,8 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::<||>(); //~ ERROR does not fulfill // unsafe ptrs are ok - assert_copy::<*int>(); - assert_copy::<*&'a mut int>(); + assert_copy::<*const int>(); + assert_copy::<*const &'a mut int>(); // regular old ints and such are ok assert_copy::<int>(); diff --git a/src/test/compile-fail/kindck-send.rs b/src/test/compile-fail/kindck-send.rs index 313b6eeb347..424c7a4e430 100644 --- a/src/test/compile-fail/kindck-send.rs +++ b/src/test/compile-fail/kindck-send.rs @@ -52,8 +52,8 @@ fn test<'a,T,U:Send>(_: &'a int) { // assert_send::<Box<Dummy+'a>>(); // ERROR does not fulfill `Send` // unsafe ptrs are ok unless they point at unsendable things - assert_send::<*int>(); - assert_send::<*&'a int>(); //~ ERROR does not fulfill `Send` + assert_send::<*const int>(); + assert_send::<*const &'a int>(); //~ ERROR does not fulfill `Send` } fn main() { diff --git a/src/test/compile-fail/linkage3.rs b/src/test/compile-fail/linkage3.rs index 11ae2fcf940..6c1b3ef67cc 100644 --- a/src/test/compile-fail/linkage3.rs +++ b/src/test/compile-fail/linkage3.rs @@ -11,7 +11,7 @@ #![feature(linkage)] extern { - #[linkage = "foo"] static foo: *i32; + #[linkage = "foo"] static foo: *const i32; //~^ ERROR: invalid linkage specified } diff --git a/src/test/compile-fail/lint-ctypes.rs b/src/test/compile-fail/lint-ctypes.rs index 3de0a0446d8..9e609814c8b 100644 --- a/src/test/compile-fail/lint-ctypes.rs +++ b/src/test/compile-fail/lint-ctypes.rs @@ -15,11 +15,11 @@ extern crate libc; extern { pub fn bare_type1(size: int); //~ ERROR: found rust type pub fn bare_type2(size: uint); //~ ERROR: found rust type - pub fn ptr_type1(size: *int); //~ ERROR: found rust type - pub fn ptr_type2(size: *uint); //~ ERROR: found rust type + pub fn ptr_type1(size: *const int); //~ ERROR: found rust type + pub fn ptr_type2(size: *const uint); //~ ERROR: found rust type - pub fn good1(size: *libc::c_int); - pub fn good2(size: *libc::c_uint); + pub fn good1(size: *const libc::c_int); + pub fn good2(size: *const libc::c_uint); } fn main() { diff --git a/src/test/compile-fail/lint-dead-code-1.rs b/src/test/compile-fail/lint-dead-code-1.rs index b68a2241e1a..8417f7810ea 100644 --- a/src/test/compile-fail/lint-dead-code-1.rs +++ b/src/test/compile-fail/lint-dead-code-1.rs @@ -35,9 +35,9 @@ static priv_static: int = 0; //~ ERROR: code is never used static used_static: int = 0; pub static used_static2: int = used_static; static USED_STATIC: int = 0; -static STATIC_USED_IN_ENUM_DISCRIMINANT: uint = 10; +static STATIC_USED_IN_ENUM_DISCRIMINANT: int = 10; -pub type typ = *UsedStruct4; +pub type typ = *const UsedStruct4; pub struct PubStruct; struct PrivStruct; //~ ERROR: code is never used struct UsedStruct1 { @@ -58,11 +58,11 @@ struct StructUsedInEnum; struct StructUsedInGeneric; pub struct PubStruct2 { #[allow(dead_code)] - struct_used_as_field: *StructUsedAsField + struct_used_as_field: *const StructUsedAsField } pub enum pub_enum { foo1, bar1 } -pub enum pub_enum2 { a(*StructUsedInEnum) } +pub enum pub_enum2 { a(*const StructUsedInEnum) } pub enum pub_enum3 { Foo = STATIC_USED_IN_ENUM_DISCRIMINANT } enum priv_enum { foo2, bar2 } //~ ERROR: code is never used enum used_enum { foo3, bar3 } @@ -77,7 +77,7 @@ pub fn pub_fn() { let e = foo3; SemiUsedStruct::la_la_la(); - let i = 1; + let i = 1i; match i { USED_STATIC => (), _ => () @@ -106,4 +106,4 @@ fn h() {} // Similarly, lang items are live #[lang="fail_"] -fn fail(_: *u8, _: *u8, _: uint) -> ! { loop {} } +fn fail(_: *const u8, _: *const u8, _: uint) -> ! { loop {} } diff --git a/src/test/compile-fail/lint-dead-code-2.rs b/src/test/compile-fail/lint-dead-code-2.rs index 1563850c641..4ad56ce9154 100644 --- a/src/test/compile-fail/lint-dead-code-2.rs +++ b/src/test/compile-fail/lint-dead-code-2.rs @@ -36,7 +36,7 @@ fn dead_fn2() {} //~ ERROR: code is never used fn used_fn() {} #[start] -fn start(_: int, _: **u8) -> int { +fn start(_: int, _: *const *const u8) -> int { used_fn(); let foo = Foo; foo.bar2(); diff --git a/src/test/compile-fail/lint-dead-code-3.rs b/src/test/compile-fail/lint-dead-code-3.rs index b0d517d18f7..4687d66ca53 100644 --- a/src/test/compile-fail/lint-dead-code-3.rs +++ b/src/test/compile-fail/lint-dead-code-3.rs @@ -54,8 +54,8 @@ mod blah { enum c_void {} extern { - fn free(p: *c_void); - fn malloc(size: size_t) -> *c_void; + fn free(p: *const c_void); + fn malloc(size: size_t) -> *const c_void; } pub fn baz() { @@ -65,7 +65,7 @@ mod blah { enum c_void {} //~ ERROR: code is never used extern { - fn free(p: *c_void); //~ ERROR: code is never used + fn free(p: *const c_void); //~ ERROR: code is never used } // Check provided method diff --git a/src/test/compile-fail/lint-heap-memory.rs b/src/test/compile-fail/lint-heap-memory.rs index 2ec9efe9498..8f495645dc7 100644 --- a/src/test/compile-fail/lint-heap-memory.rs +++ b/src/test/compile-fail/lint-heap-memory.rs @@ -21,11 +21,11 @@ struct Foo { struct Bar { x: Box<int> } //~ ERROR type uses owned fn main() { - let _x : Bar = Bar {x : box 10}; //~ ERROR type uses owned + let _x : Bar = Bar {x : box 10i}; //~ ERROR type uses owned - box(GC) 2; //~ ERROR type uses managed + box(GC) 2i; //~ ERROR type uses managed - box 2; //~ ERROR type uses owned + box 2i; //~ ERROR type uses owned fn g(_: Box<Clone>) {} //~ ERROR type uses owned proc() {}; //~ ERROR type uses owned } diff --git a/src/test/compile-fail/lint-raw-ptr-deriving.rs b/src/test/compile-fail/lint-raw-ptr-deriving.rs index d3fdd508f45..da43324d494 100644 --- a/src/test/compile-fail/lint-raw-ptr-deriving.rs +++ b/src/test/compile-fail/lint-raw-ptr-deriving.rs @@ -14,7 +14,7 @@ #[deriving(Clone)] struct Foo { - x: *int //~ ERROR use of `#[deriving]` with a raw pointer + x: *const int //~ ERROR use of `#[deriving]` with a raw pointer } #[deriving(Clone)] @@ -22,14 +22,14 @@ struct Bar(*mut int); //~ ERROR use of `#[deriving]` with a raw pointer #[deriving(Clone)] enum Baz { - A(*int), //~ ERROR use of `#[deriving]` with a raw pointer + A(*const int), //~ ERROR use of `#[deriving]` with a raw pointer B { x: *mut int } //~ ERROR use of `#[deriving]` with a raw pointer } #[deriving(Clone)] struct Buzz { - x: (*int, //~ ERROR use of `#[deriving]` with a raw pointer - *uint) //~ ERROR use of `#[deriving]` with a raw pointer + x: (*const int, //~ ERROR use of `#[deriving]` with a raw pointer + *const uint) //~ ERROR use of `#[deriving]` with a raw pointer } fn main() {} diff --git a/src/test/compile-fail/lint-unnecessary-parens.rs b/src/test/compile-fail/lint-unnecessary-parens.rs index b2abe025794..d51d5b4af87 100644 --- a/src/test/compile-fail/lint-unnecessary-parens.rs +++ b/src/test/compile-fail/lint-unnecessary-parens.rs @@ -10,19 +10,42 @@ #![deny(unnecessary_parens)] +#[deriving(Eq, PartialEq)] +struct X { y: bool } +impl X { + fn foo(&self) -> bool { self.y } +} + fn foo() -> int { - return (1); //~ ERROR unnecessary parentheses around `return` value + return (1i); //~ ERROR unnecessary parentheses around `return` value +} +fn bar() -> X { + return (X { y: true }); //~ ERROR unnecessary parentheses around `return` value } fn main() { foo(); + bar(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } - let mut _a = (0); //~ ERROR unnecessary parentheses around assigned value - _a = (0); //~ ERROR unnecessary parentheses around assigned value - _a += (1); //~ ERROR unnecessary parentheses around assigned value + let v = X { y: false }; + // struct lits needs parens, so these shouldn't warn. + if (v == X { y: true }) {} + if (X { y: true } == v) {} + if (X { y: false }.y) {} + + while (X { y: false }.foo()) {} + while (true | X { y: false }.y) {} + + match (X { y: false }) { + _ => {} + } + + let mut _a = (0i); //~ ERROR unnecessary parentheses around assigned value + _a = (0i); //~ ERROR unnecessary parentheses around assigned value + _a += (1i); //~ ERROR unnecessary parentheses around assigned value } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index 4334d2f63ea..f03e748e417 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -55,7 +55,7 @@ mod bar { pub mod c { use foo::Point; use foo::Square; //~ ERROR unused import - pub fn cc(p: Point) -> int { return 2 * (p.x + p.y); } + pub fn cc(p: Point) -> int { return 2i * (p.x + p.y); } } #[allow(unused_imports)] @@ -66,8 +66,8 @@ mod bar { fn main() { cal(foo::Point{x:3, y:9}); - let mut a = 3; - let mut b = 4; + let mut a = 3i; + let mut b = 4i; swap(&mut a, &mut b); test::C.b(); let _a = foo(); diff --git a/src/test/compile-fail/lint-unused-mut-variables.rs b/src/test/compile-fail/lint-unused-mut-variables.rs index d5f34669a25..c5281bf6781 100644 --- a/src/test/compile-fail/lint-unused-mut-variables.rs +++ b/src/test/compile-fail/lint-unused-mut-variables.rs @@ -18,16 +18,16 @@ fn main() { // negative cases - let mut a = 3; //~ ERROR: variable does not need to be mutable - let mut a = 2; //~ ERROR: variable does not need to be mutable - let mut b = 3; //~ ERROR: variable does not need to be mutable - let mut a = vec!(3); //~ ERROR: variable does not need to be mutable - let (mut a, b) = (1, 2); //~ ERROR: variable does not need to be mutable + let mut a = 3i; //~ ERROR: variable does not need to be mutable + let mut a = 2i; //~ ERROR: variable does not need to be mutable + let mut b = 3i; //~ ERROR: variable does not need to be mutable + let mut a = vec!(3i); //~ ERROR: variable does not need to be mutable + let (mut a, b) = (1i, 2i); //~ ERROR: variable does not need to be mutable - match 30 { + match 30i { mut x => {} //~ ERROR: variable does not need to be mutable } - match (30, 2) { + match (30i, 2i) { (mut x, 1) | //~ ERROR: variable does not need to be mutable (mut x, 2) | (mut x, 3) => { @@ -35,28 +35,28 @@ fn main() { _ => {} } - let x = |mut y: int| 10; //~ ERROR: variable does not need to be mutable + let x = |mut y: int| 10i; //~ ERROR: variable does not need to be mutable fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable // positive cases - let mut a = 2; - a = 3; + let mut a = 2i; + a = 3i; let mut a = Vec::new(); - a.push(3); + a.push(3i); let mut a = Vec::new(); callback(|| { - a.push(3); + a.push(3i); }); - let (mut a, b) = (1, 2); + let (mut a, b) = (1i, 2i); a = 34; - match 30 { + match 30i { mut x => { - x = 21; + x = 21i; } } - match (30, 2) { + match (30i, 2i) { (mut x, 1) | (mut x, 2) | (mut x, 3) => { @@ -65,12 +65,12 @@ fn main() { _ => {} } - let x = |mut y: int| y = 32; - fn nothing(mut foo: int) { foo = 37; } + let x = |mut y: int| y = 32i; + fn nothing(mut foo: int) { foo = 37i; } // leading underscore should avoid the warning, just like the // unused variable lint. - let mut _allowed = 1; + let mut _allowed = 1i; } fn callback(f: ||) {} @@ -78,6 +78,6 @@ fn callback(f: ||) {} // make sure the lint attribute can be turned off #[allow(unused_mut)] fn foo(mut a: int) { - let mut a = 3; - let mut b = vec!(2); + let mut a = 3i; + let mut b = vec!(2i); } diff --git a/src/test/compile-fail/liveness-unused.rs b/src/test/compile-fail/liveness-unused.rs index ee44872d122..68dbacaae5c 100644 --- a/src/test/compile-fail/liveness-unused.rs +++ b/src/test/compile-fail/liveness-unused.rs @@ -29,40 +29,40 @@ fn f1d() { } fn f2() { - let x = 3; + let x = 3i; //~^ ERROR unused variable: `x` } fn f3() { - let mut x = 3; + let mut x = 3i; //~^ ERROR variable `x` is assigned to, but never used - x += 4; + x += 4i; //~^ ERROR value assigned to `x` is never read } fn f3b() { - let mut z = 3; + let mut z = 3i; //~^ ERROR variable `z` is assigned to, but never used loop { - z += 4; + z += 4i; } } #[allow(unused_variable)] fn f3c() { - let mut z = 3; - loop { z += 4; } + let mut z = 3i; + loop { z += 4i; } } #[allow(unused_variable)] #[allow(dead_assignment)] fn f3d() { - let mut x = 3; - x += 4; + let mut x = 3i; + x += 4i; } fn f4() { - match Some(3) { + match Some(3i) { Some(i) => { //~^ ERROR unused variable: `i` } @@ -75,7 +75,7 @@ enum tri { } fn f4b() -> int { - match a(3) { + match a(3i) { a(i) | b(i) | c(i) => { i } diff --git a/src/test/compile-fail/match-ill-type2.rs b/src/test/compile-fail/match-ill-type2.rs index d8d665e2af6..17f02abc8ec 100644 --- a/src/test/compile-fail/match-ill-type2.rs +++ b/src/test/compile-fail/match-ill-type2.rs @@ -9,9 +9,9 @@ // except according to those terms. fn main() { - match 1 { - 1 => 1, //~ ERROR mismatched types between arms - 2u => 1, - _ => 2, + match 1i { + 1i => 1i, + 2u => 1i, //~ ERROR mismatched types + _ => 2i, }; } diff --git a/src/test/compile-fail/match-non-exhaustive.rs b/src/test/compile-fail/match-non-exhaustive.rs index a24d2ed4b7f..20adbeebdf1 100644 --- a/src/test/compile-fail/match-non-exhaustive.rs +++ b/src/test/compile-fail/match-non-exhaustive.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - match 0 { 1 => () } //~ ERROR non-exhaustive patterns - match 0 { 0 if false => () } //~ ERROR non-exhaustive patterns + match 0i { 1i => () } //~ ERROR non-exhaustive patterns + match 0i { 0i if false => () } //~ ERROR non-exhaustive patterns } diff --git a/src/test/compile-fail/match-range-fail-dominate.rs b/src/test/compile-fail/match-range-fail-dominate.rs index 3f484511859..7c9c371c526 100644 --- a/src/test/compile-fail/match-range-fail-dominate.rs +++ b/src/test/compile-fail/match-range-fail-dominate.rs @@ -39,9 +39,9 @@ fn main() { _ => {} }; - match 1.0 { - 0.01 .. 6.5 => {} - 0.02 => {} + match 1.0f64 { + 0.01f64 .. 6.5f64 => {} + 0.02f64 => {} _ => {} }; } diff --git a/src/test/compile-fail/match-vec-fixed.rs b/src/test/compile-fail/match-vec-fixed.rs index e778dd18e68..bac9fef2b17 100644 --- a/src/test/compile-fail/match-vec-fixed.rs +++ b/src/test/compile-fail/match-vec-fixed.rs @@ -9,7 +9,7 @@ // except according to those terms. fn a() { - let v = [1, 2, 3]; + let v = [1i, 2, 3]; match v { [_, _, _] => {} [_, _, _] => {} //~ ERROR unreachable pattern diff --git a/src/test/compile-fail/moves-based-on-type-exprs.rs b/src/test/compile-fail/moves-based-on-type-exprs.rs index 82aa5c36c8e..7a882b26db5 100644 --- a/src/test/compile-fail/moves-based-on-type-exprs.rs +++ b/src/test/compile-fail/moves-based-on-type-exprs.rs @@ -25,13 +25,13 @@ fn f10() { fn f20() { let x = "hi".to_string(); - let _y = (x, 3); + let _y = (x, 3i); touch(&x); //~ ERROR use of moved value: `x` } fn f21() { - let x = vec!(1, 2, 3); - let _y = (*x.get(0), 3); + let x = vec!(1i, 2, 3); + let _y = (*x.get(0), 3i); touch(&x); } @@ -62,9 +62,9 @@ fn f50(cond: bool) { let x = "hi".to_string(); let y = "ho".to_string(); let _y = match cond { - _ if guard(x) => 10, - true => 10, - false => 20, + _ if guard(x) => 10i, + true => 10i, + false => 20i, }; touch(&x); //~ ERROR use of moved value: `x` touch(&y); diff --git a/src/test/compile-fail/mut-cant-alias.rs b/src/test/compile-fail/mut-cant-alias.rs index 99d7258477a..ce6e793d55d 100644 --- a/src/test/compile-fail/mut-cant-alias.rs +++ b/src/test/compile-fail/mut-cant-alias.rs @@ -11,7 +11,7 @@ use std::cell::RefCell; fn main() { - let m = RefCell::new(0); + let m = RefCell::new(0i); let mut b = m.borrow_mut(); let b1 = &mut *b; let b2 = &mut *b; //~ ERROR cannot borrow diff --git a/src/test/compile-fail/mut-not-freeze.rs b/src/test/compile-fail/mut-not-freeze.rs index f1e7ef216c3..985bfec392c 100644 --- a/src/test/compile-fail/mut-not-freeze.rs +++ b/src/test/compile-fail/mut-not-freeze.rs @@ -13,6 +13,6 @@ use std::cell::RefCell; fn f<T: Share>(_: T) {} fn main() { - let x = RefCell::new(0); + let x = RefCell::new(0i); f(x); //~ ERROR: which does not fulfill `Share` } diff --git a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs index 8e968d90a2f..e269a736ce2 100644 --- a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs +++ b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs @@ -11,7 +11,7 @@ use std::cell::RefCell; fn main() { - let m = RefCell::new(0); + let m = RefCell::new(0i); let p; { let b = m.borrow(); diff --git a/src/test/compile-fail/no_send-rc.rs b/src/test/compile-fail/no_send-rc.rs index bf79d1393b8..291340e55b8 100644 --- a/src/test/compile-fail/no_send-rc.rs +++ b/src/test/compile-fail/no_send-rc.rs @@ -13,7 +13,7 @@ use std::rc::Rc; fn bar<T: Send>(_: T) {} fn main() { - let x = Rc::new(5); + let x = Rc::new(5i); bar(x); //~^ ERROR instantiating a type parameter with an incompatible type `alloc::rc::Rc<int>`, // which does not fulfill `Send` diff --git a/src/test/compile-fail/no_share-rc.rs b/src/test/compile-fail/no_share-rc.rs index ad79d038212..f49592b1735 100644 --- a/src/test/compile-fail/no_share-rc.rs +++ b/src/test/compile-fail/no_share-rc.rs @@ -14,7 +14,7 @@ use std::cell::RefCell; fn bar<T: Share>(_: T) {} fn main() { - let x = Rc::new(RefCell::new(5)); + let x = Rc::new(RefCell::new(5i)); bar(x); //~^ ERROR instantiating a type parameter with an incompatible type // `std::rc::Rc<std::cell::RefCell<int>>`, which does not fulfill `Share` diff --git a/src/test/compile-fail/non-copyable-void.rs b/src/test/compile-fail/non-copyable-void.rs index 5025e2e509b..cd134ccf71d 100644 --- a/src/test/compile-fail/non-copyable-void.rs +++ b/src/test/compile-fail/non-copyable-void.rs @@ -11,8 +11,8 @@ extern crate libc; fn main() { - let x : *Vec<int> = &vec!(1,2,3); - let y : *libc::c_void = x as *libc::c_void; + let x : *const Vec<int> = &vec!(1,2,3); + let y : *const libc::c_void = x as *const libc::c_void; unsafe { let _z = (*y).clone(); //~^ ERROR does not implement any method in scope diff --git a/src/test/compile-fail/non-exhaustive-match.rs b/src/test/compile-fail/non-exhaustive-match.rs index cd78419439a..4de4af87712 100644 --- a/src/test/compile-fail/non-exhaustive-match.rs +++ b/src/test/compile-fail/non-exhaustive-match.rs @@ -16,10 +16,10 @@ fn main() { match true { //~ ERROR non-exhaustive patterns: `false` not covered true => {} } - match Some(10) { //~ ERROR non-exhaustive patterns: `Some(_)` not covered + match Some(10i) { //~ ERROR non-exhaustive patterns: `Some(_)` not covered None => {} } - match (2, 3, 4) { //~ ERROR non-exhaustive patterns: `(_, _, _)` not covered + match (2i, 3i, 4i) { //~ ERROR non-exhaustive patterns: `(_, _, _)` not covered (_, _, 4) => {} } match (a, a) { //~ ERROR non-exhaustive patterns: `(a, a)` not covered @@ -35,20 +35,20 @@ fn main() { (_, a) => {} (b, b) => {} } - let vec = vec!(Some(42), None, Some(21)); + let vec = vec!(Some(42i), None, Some(21i)); let vec: &[Option<int>] = vec.as_slice(); match vec { //~ ERROR non-exhaustive patterns: `[]` not covered [Some(..), None, ..tail] => {} [Some(..), Some(..), ..tail] => {} [None] => {} } - let vec = vec!(1); + let vec = vec!(1i); let vec: &[int] = vec.as_slice(); match vec { [_, ..tail] => (), [] => () } - let vec = vec!(0.5); + let vec = vec!(0.5f32); let vec: &[f32] = vec.as_slice(); match vec { //~ ERROR non-exhaustive patterns: `[_, _, _, _]` not covered [0.1, 0.2, 0.3] => (), @@ -56,7 +56,7 @@ fn main() { [0.1] => (), [] => () } - let vec = vec!(Some(42), None, Some(21)); + let vec = vec!(Some(42i), None, Some(21i)); let vec: &[Option<int>] = vec.as_slice(); match vec { [Some(..), None, ..tail] => {} diff --git a/src/test/compile-fail/privacy1.rs b/src/test/compile-fail/privacy1.rs index 6df52c394fc..015d221e7ef 100644 --- a/src/test/compile-fail/privacy1.rs +++ b/src/test/compile-fail/privacy1.rs @@ -184,4 +184,4 @@ pub mod mytest { } } -#[start] fn main(_: int, _: **u8) -> int { 3 } +#[start] fn main(_: int, _: *const *const u8) -> int { 3 } diff --git a/src/test/compile-fail/privacy2.rs b/src/test/compile-fail/privacy2.rs index 5a5b6eb8436..1a94751b46b 100644 --- a/src/test/compile-fail/privacy2.rs +++ b/src/test/compile-fail/privacy2.rs @@ -33,5 +33,5 @@ fn test2() { //~^ ERROR unresolved import `bar::glob::foo`. There is no `foo` in `bar::glob` } -#[start] fn main(_: int, _: **u8) -> int { 3 } +#[start] fn main(_: int, _: *const *const u8) -> int { 3 } diff --git a/src/test/compile-fail/privacy3.rs b/src/test/compile-fail/privacy3.rs index 6898a0cde17..4c67a9910cf 100644 --- a/src/test/compile-fail/privacy3.rs +++ b/src/test/compile-fail/privacy3.rs @@ -30,4 +30,4 @@ fn test1() { gpriv(); } -#[start] fn main(_: int, _: **u8) -> int { 3 } +#[start] fn main(_: int, _: *const *const u8) -> int { 3 } diff --git a/src/test/compile-fail/privacy4.rs b/src/test/compile-fail/privacy4.rs index 18a94cb86c8..65f4a0e950f 100644 --- a/src/test/compile-fail/privacy4.rs +++ b/src/test/compile-fail/privacy4.rs @@ -29,4 +29,4 @@ fn test2() { gpriv(); } -#[start] fn main(_: int, _: **u8) -> int { 3 } +#[start] fn main(_: int, _: *const *const u8) -> int { 3 } diff --git a/src/test/compile-fail/refutable-pattern-errors.rs b/src/test/compile-fail/refutable-pattern-errors.rs index 9128ee68e26..28533518a25 100644 --- a/src/test/compile-fail/refutable-pattern-errors.rs +++ b/src/test/compile-fail/refutable-pattern-errors.rs @@ -13,6 +13,6 @@ fn func((1, (Some(1), 2..3)): (int, (Option<int>, int))) { } //~^ ERROR refutable pattern in function argument: `(_, _)` not covered fn main() { - let (1, (Some(1), 2..3)) = (1, (None, 2)); + let (1i, (Some(1i), 2i..3i)) = (1i, (None, 2i)); //~^ ERROR refutable pattern in local binding: `(_, _)` not covered } diff --git a/src/test/compile-fail/regionck-closure-lifetimes.rs b/src/test/compile-fail/regionck-closure-lifetimes.rs index 731b045d0f3..846e03d57c3 100644 --- a/src/test/compile-fail/regionck-closure-lifetimes.rs +++ b/src/test/compile-fail/regionck-closure-lifetimes.rs @@ -13,9 +13,9 @@ fn env<'a>(blk: |p: ||: 'a|) { // the lifetime `'a`, which outlives the current // block. - let mut state = 0; + let mut state = 0i; let statep = &mut state; - blk(|| *statep = 1); //~ ERROR cannot infer + blk(|| *statep = 1i); //~ ERROR cannot infer } fn no_env_no_for<'a>(blk: |p: |||: 'a) { @@ -31,7 +31,7 @@ fn repeating_loop() { // external to the loop. let closure; - let state = 0; + let state = 0i; loop { closure = || state; //~ ERROR cannot infer @@ -47,7 +47,7 @@ fn repeating_while() { // external to the loop. let closure; - let state = 0; + let state = 0i; while true { closure = || state; //~ ERROR cannot infer diff --git a/src/test/compile-fail/regions-escape-loop-via-variable.rs b/src/test/compile-fail/regions-escape-loop-via-variable.rs index f588655d1af..472df87dd2b 100644 --- a/src/test/compile-fail/regions-escape-loop-via-variable.rs +++ b/src/test/compile-fail/regions-escape-loop-via-variable.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = 3; + let x = 3i; // Here, the variable `p` gets inferred to a type with a lifetime // of the loop body. The regionck then determines that this type @@ -17,7 +17,7 @@ fn main() { let mut p = &x; loop { - let x = 1 + *p; + let x = 1i + *p; p = &x; //~ ERROR `x` does not live long enough } } diff --git a/src/test/compile-fail/regions-escape-loop-via-vec.rs b/src/test/compile-fail/regions-escape-loop-via-vec.rs index 89350f16167..22c6bdd2d50 100644 --- a/src/test/compile-fail/regions-escape-loop-via-vec.rs +++ b/src/test/compile-fail/regions-escape-loop-via-vec.rs @@ -10,7 +10,7 @@ // The type of `y` ends up getting inferred to the type of the block. fn broken() { - let mut x = 3; + let mut x = 3i; let mut _y = vec!(&mut x); while x < 10 { //~ ERROR cannot use `x` because it was mutably borrowed let mut z = x; //~ ERROR cannot use `x` because it was mutably borrowed diff --git a/src/test/compile-fail/regions-escape-via-trait-or-not.rs b/src/test/compile-fail/regions-escape-via-trait-or-not.rs index 7f54fe298a1..980a4aed34f 100644 --- a/src/test/compile-fail/regions-escape-via-trait-or-not.rs +++ b/src/test/compile-fail/regions-escape-via-trait-or-not.rs @@ -23,7 +23,7 @@ fn with<R:deref>(f: |x: &int| -> R) -> int { } fn return_it() -> int { - with(|o| o) //~ ERROR lifetime of function argument does not outlive the function call + with(|o| o) //~ ERROR cannot infer an appropriate lifetime } fn main() { diff --git a/src/test/compile-fail/static-assert2.rs b/src/test/compile-fail/static-assert2.rs index d5e70205e95..6adc3b0aaf8 100644 --- a/src/test/compile-fail/static-assert2.rs +++ b/src/test/compile-fail/static-assert2.rs @@ -11,6 +11,6 @@ #![allow(dead_code)] #[static_assert] -static E: bool = 1 == 2; //~ ERROR static assertion failed +static E: bool = 1i == 2; //~ ERROR static assertion failed fn main() {} diff --git a/src/test/compile-fail/static-mut-not-pat.rs b/src/test/compile-fail/static-mut-not-pat.rs index 997003a28d4..c410e856552 100644 --- a/src/test/compile-fail/static-mut-not-pat.rs +++ b/src/test/compile-fail/static-mut-not-pat.rs @@ -19,7 +19,7 @@ fn main() { // name as a variable, hence this should be an unreachable pattern situation // instead of spitting out a custom error about some identifier collisions // (we should allow shadowing) - match 4 { + match 4i { a => {} _ => {} //~ ERROR: unreachable pattern } diff --git a/src/test/compile-fail/static-region-bound.rs b/src/test/compile-fail/static-region-bound.rs index 880fbf0cb1d..d78643ccd10 100644 --- a/src/test/compile-fail/static-region-bound.rs +++ b/src/test/compile-fail/static-region-bound.rs @@ -15,8 +15,8 @@ use std::gc::GC; fn f<T:'static>(_: T) {} fn main() { - let x = box(GC) 3; + let x = box(GC) 3i; f(x); - let x = &3; + let x = &3i; f(x); //~ ERROR instantiating a type parameter with an incompatible type } diff --git a/src/test/run-pass/str-idx.rs b/src/test/compile-fail/str-idx.rs index 8ac13e81463..25e4c90e774 100644 --- a/src/test/run-pass/str-idx.rs +++ b/src/test/compile-fail/str-idx.rs @@ -11,8 +11,6 @@ extern crate debug; pub fn main() { - let s = "hello".to_string(); - let c: u8 = s.as_slice()[4]; - println!("{:?}", c); - assert_eq!(c, 0x6f as u8); + let s: &str = "hello"; + let c: u8 = s[4]; //~ ERROR cannot index a value of type `&str` } diff --git a/src/test/compile-fail/typeck-unsafe-always-share.rs b/src/test/compile-fail/typeck-unsafe-always-share.rs index 6dec86ddf62..72ef4a03eab 100644 --- a/src/test/compile-fail/typeck-unsafe-always-share.rs +++ b/src/test/compile-fail/typeck-unsafe-always-share.rs @@ -28,7 +28,7 @@ fn test<T: Share>(s: T){ } fn main() { - let us = Unsafe::new(MyShare{u: Unsafe::new(0)}); + let us = Unsafe::new(MyShare{u: Unsafe::new(0i)}); test(us); let uns = Unsafe::new(NoShare{m: marker::NoShare}); diff --git a/src/test/compile-fail/unique-unique-kind.rs b/src/test/compile-fail/unique-unique-kind.rs index e8dc0fc3b6c..67fbc08bd94 100644 --- a/src/test/compile-fail/unique-unique-kind.rs +++ b/src/test/compile-fail/unique-unique-kind.rs @@ -16,6 +16,6 @@ fn f<T:Send>(_i: T) { } fn main() { - let i = box box(GC) 100; + let i = box box(GC) 100i; f(i); //~ ERROR does not fulfill `Send` } diff --git a/src/test/compile-fail/unreachable-code.rs b/src/test/compile-fail/unreachable-code.rs index 96adb29cbc8..fb9a6b52018 100644 --- a/src/test/compile-fail/unreachable-code.rs +++ b/src/test/compile-fail/unreachable-code.rs @@ -14,5 +14,5 @@ fn main() { loop{} - let a = 3; //~ ERROR: unreachable statement + let a = 3i; //~ ERROR: unreachable statement } diff --git a/src/test/compile-fail/unsafe-fn-assign-deref-ptr.rs b/src/test/compile-fail/unsafe-fn-assign-deref-ptr.rs index a9480c60886..97908118e35 100644 --- a/src/test/compile-fail/unsafe-fn-assign-deref-ptr.rs +++ b/src/test/compile-fail/unsafe-fn-assign-deref-ptr.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn f(p: *u8) { +fn f(p: *const u8) { *p = 0u8; //~ ERROR dereference of unsafe pointer requires unsafe function or block return; } diff --git a/src/test/compile-fail/unsafe-fn-autoderef.rs b/src/test/compile-fail/unsafe-fn-autoderef.rs index 4572e084f66..464abd57872 100644 --- a/src/test/compile-fail/unsafe-fn-autoderef.rs +++ b/src/test/compile-fail/unsafe-fn-autoderef.rs @@ -12,7 +12,7 @@ struct Rec { f: int } -fn f(p: *Rec) -> int { +fn f(p: *const Rec) -> int { // Test that * ptrs do not autoderef. There is a deeper reason for // prohibiting this, beyond making unsafe things annoying (which doesn't @@ -26,7 +26,7 @@ fn f(p: *Rec) -> int { // are prohibited by various checks, such as that the enum is // instantiable and so forth). - return p.f; //~ ERROR attempted access of field `f` on type `*Rec` + return p.f; //~ ERROR attempted access of field `f` on type `*const Rec` } fn main() { diff --git a/src/test/compile-fail/unsafe-fn-deref-ptr.rs b/src/test/compile-fail/unsafe-fn-deref-ptr.rs index fb631e02b6f..bdf079e24d2 100644 --- a/src/test/compile-fail/unsafe-fn-deref-ptr.rs +++ b/src/test/compile-fail/unsafe-fn-deref-ptr.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn f(p: *u8) -> u8 { +fn f(p: *const u8) -> u8 { return *p; //~ ERROR dereference of unsafe pointer requires unsafe function or block } diff --git a/src/test/compile-fail/unsized3.rs b/src/test/compile-fail/unsized3.rs index c321871c40f..c5cc7e8f716 100644 --- a/src/test/compile-fail/unsized3.rs +++ b/src/test/compile-fail/unsized3.rs @@ -51,8 +51,8 @@ fn f8<type X>(x1: &S<X>, x2: &S<X>) { // Test some tuples. fn f9<type X>(x1: Box<S<X>>, x2: Box<E<X>>) { - f5(&(*x1, 34)); //~ERROR instantiating a type parameter with an incompatible type `(S<X>,int)`, - f5(&(32, *x2)); //~ERROR instantiating a type parameter with an incompatible type `(int,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>)`, } // I would like these to fail eventually. diff --git a/src/test/compile-fail/unsized6.rs b/src/test/compile-fail/unsized6.rs index 9916fdba20f..061b003b5e3 100644 --- a/src/test/compile-fail/unsized6.rs +++ b/src/test/compile-fail/unsized6.rs @@ -29,12 +29,12 @@ fn f2<type X: T>(x: &X) { fn f3<type 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, 4); //~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>) { 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, 4); //~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` diff --git a/src/test/compile-fail/variadic-ffi.rs b/src/test/compile-fail/variadic-ffi.rs index aa58d2e08e9..2110d4c8009 100644 --- a/src/test/compile-fail/variadic-ffi.rs +++ b/src/test/compile-fail/variadic-ffi.rs @@ -9,7 +9,7 @@ // except according to those terms. extern "stdcall" { - fn printf(_: *u8, ...); //~ ERROR: variadic function must have C calling convention + fn printf(_: *const u8, ...); //~ ERROR: variadic function must have C calling convention } extern { diff --git a/src/test/compile-fail/variance-trait-matching-2.rs b/src/test/compile-fail/variance-trait-matching-2.rs new file mode 100644 index 00000000000..f549c78be9d --- /dev/null +++ b/src/test/compile-fail/variance-trait-matching-2.rs @@ -0,0 +1,31 @@ +// 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. + +extern crate serialize; + +use std::io::MemWriter; +use std::io; +use serialize::{Encodable, Encoder}; + +pub fn buffer_encode<'a, + T:Encodable<serialize::json::Encoder<'a>,io::IoError>>( + to_encode_object: &T) + -> Vec<u8> { + let mut m = MemWriter::new(); + { + let mut encoder = + serialize::json::Encoder::new(&mut m as &mut io::Writer); + //~^ ERROR `m` does not live long enough + to_encode_object.encode(&mut encoder); + } + m.unwrap() +} + +fn main() {} diff --git a/src/test/compile-fail/variance-trait-matching.rs b/src/test/compile-fail/variance-trait-matching.rs new file mode 100644 index 00000000000..1644705222f --- /dev/null +++ b/src/test/compile-fail/variance-trait-matching.rs @@ -0,0 +1,30 @@ +// 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. + +// Issue #5781. Tests that subtyping is handled properly in trait matching. + +trait Make<'a> { + fn make(x: &'a mut int) -> Self; +} + +impl<'a> Make<'a> for &'a mut int { + fn make(x: &'a mut int) -> &'a mut int { + x + } +} + +fn f() -> &'static mut int { + let mut x = 1; + let y: &'static mut int = Make::make(&mut x); //~ ERROR `x` does not live long enough + y +} + +fn main() {} + diff --git a/src/test/compile-fail/vec-mut-iter-borrow.rs b/src/test/compile-fail/vec-mut-iter-borrow.rs index a3c7fc2d4c8..9a179f434c2 100644 --- a/src/test/compile-fail/vec-mut-iter-borrow.rs +++ b/src/test/compile-fail/vec-mut-iter-borrow.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut xs = vec!(1, 2, 3, 4); + let mut xs = vec!(1i, 2, 3, 4); for x in xs.mut_iter() { xs.push(1) //~ ERROR cannot borrow `xs` diff --git a/src/test/compile-fail/vector-cast-weirdness.rs b/src/test/compile-fail/vector-cast-weirdness.rs index da0f0f5f7c9..e096e5eb436 100644 --- a/src/test/compile-fail/vector-cast-weirdness.rs +++ b/src/test/compile-fail/vector-cast-weirdness.rs @@ -18,9 +18,9 @@ struct X { fn main() { let x1 = X { y: [0, 0] }; - let p1: *u8 = &x1.y as *_; //~ ERROR mismatched types - let t1: *[u8, ..2] = &x1.y as *_; - let h1: *[u8, ..2] = &x1.y as *[u8, ..2]; + let p1: *const u8 = &x1.y as *const _; //~ ERROR mismatched types + let t1: *const [u8, ..2] = &x1.y as *const _; + let h1: *const [u8, ..2] = &x1.y as *const [u8, ..2]; let mut x1 = X { y: [0, 0] }; diff --git a/src/test/compile-fail/warn-foreign-int-types.rs b/src/test/compile-fail/warn-foreign-int-types.rs index 8a5881d3797..cfa6623176c 100644 --- a/src/test/compile-fail/warn-foreign-int-types.rs +++ b/src/test/compile-fail/warn-foreign-int-types.rs @@ -13,7 +13,7 @@ mod xx { extern { - pub fn strlen(str: *u8) -> uint; //~ ERROR found rust type `uint` + pub fn strlen(str: *const u8) -> uint; //~ ERROR found rust type `uint` pub fn foo(x: int, y: uint); //~ ERROR found rust type `int` //~^ ERROR found rust type `uint` } diff --git a/src/test/compile-fail/warn-path-statement.rs b/src/test/compile-fail/warn-path-statement.rs index 90515807ac6..8b6d160a6c5 100644 --- a/src/test/compile-fail/warn-path-statement.rs +++ b/src/test/compile-fail/warn-path-statement.rs @@ -11,6 +11,6 @@ // compile-flags: -D path-statement fn main() { - let x = 10; + let x = 10i; x; //~ ERROR path statement with no effect } diff --git a/src/test/debuginfo/basic-types-metadata.rs b/src/test/debuginfo/basic-types-metadata.rs index da32518d993..51d2f36cc78 100644 --- a/src/test/debuginfo/basic-types-metadata.rs +++ b/src/test/debuginfo/basic-types-metadata.rs @@ -67,7 +67,7 @@ fn main() { let f32: f32 = 2.5; let f64: f64 = 3.5; _zzz(); - if 1 == 1 { _yyy(); } + if 1i == 1 { _yyy(); } } fn _zzz() {()} diff --git a/src/test/debuginfo/box.rs b/src/test/debuginfo/box.rs index 01129c845e9..dcfe1804510 100644 --- a/src/test/debuginfo/box.rs +++ b/src/test/debuginfo/box.rs @@ -30,9 +30,9 @@ use std::gc::GC; fn main() { - let a = box 1; - let b = box() (2, 3.5); - let c = box(GC) 4; + let a = box 1i; + let b = box() (2i, 3.5f64); + let c = box(GC) 4i; let d = box(GC) false; _zzz(); } diff --git a/src/test/debuginfo/closure-in-generic-function.rs b/src/test/debuginfo/closure-in-generic-function.rs index 7a89b682d15..cc241040f2b 100644 --- a/src/test/debuginfo/closure-in-generic-function.rs +++ b/src/test/debuginfo/closure-in-generic-function.rs @@ -39,8 +39,8 @@ fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) { } fn main() { - some_generic_fun(0.5, 10); - some_generic_fun(&29, box 110); + some_generic_fun(0.5f64, 10i); + some_generic_fun(&29i, box 110i); } fn zzz() {()} diff --git a/src/test/debuginfo/destructured-local.rs b/src/test/debuginfo/destructured-local.rs index c543a11475e..d91d98f4305 100644 --- a/src/test/debuginfo/destructured-local.rs +++ b/src/test/debuginfo/destructured-local.rs @@ -156,7 +156,7 @@ fn main() { let Struct { a: k, b: l } = Struct { a: 12, b: 13 }; // ignored tuple element - let (m, _, n) = (14, 15, 16); + let (m, _, n) = (14i, 15i, 16i); // ignored struct field let Struct { b: o, .. } = Struct { a: 17, b: 18 }; @@ -169,25 +169,25 @@ fn main() { // complex nesting let ((u, v), ((w, (x, Struct { a: y, b: z})), Struct { a: ae, b: oe }), ue) = - ((25, 26), ((27, (28, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33); + ((25i, 26i), ((27i, (28i, Struct { a: 29, b: 30})), Struct { a: 31, b: 32 }), 33i); // reference - let &aa = &(34, 35); + let &aa = &(34i, 35i); // reference - let &bb = &(36, 37); + let &bb = &(36i, 37i); // contained reference - let (&cc, _) = (&38, 39); + let (&cc, _) = (&38i, 39i); // unique pointer - let box dd = box() (40, 41, 42); + let box dd = box() (40i, 41i, 42i); // ref binding - let ref ee = (43, 44, 45); + let ref ee = (43i, 44i, 45i); // ref binding in tuple - let (ref ff, gg) = (46, (47, 48)); + let (ref ff, gg) = (46i, (47i, 48i)); // ref binding in struct let Struct { b: ref hh, .. } = Struct { a: 49, b: 50 }; diff --git a/src/test/debuginfo/function-arg-initialization.rs b/src/test/debuginfo/function-arg-initialization.rs index d439f49fe69..535efa0b84e 100644 --- a/src/test/debuginfo/function-arg-initialization.rs +++ b/src/test/debuginfo/function-arg-initialization.rs @@ -155,7 +155,7 @@ fn non_immediate_args(a: BigStruct, b: BigStruct) { } fn binding(a: i64, b: u64, c: f64) { - let x = 0; + let x = 0i; } fn assignment(mut a: u64, b: u64, c: f64) { diff --git a/src/test/debuginfo/function-prologue-stepping-no-split-stack.rs b/src/test/debuginfo/function-prologue-stepping-no-split-stack.rs index a9ccf3cdb16..0160a6f1879 100644 --- a/src/test/debuginfo/function-prologue-stepping-no-split-stack.rs +++ b/src/test/debuginfo/function-prologue-stepping-no-split-stack.rs @@ -152,7 +152,7 @@ fn non_immediate_args(a: BigStruct, b: BigStruct) { #[no_split_stack] fn binding(a: i64, b: u64, c: f64) { - let x = 0; + let x = 0i; } #[no_split_stack] diff --git a/src/test/debuginfo/generic-functions-nested.rs b/src/test/debuginfo/generic-functions-nested.rs index d9b20a84cdd..1805405dc1e 100644 --- a/src/test/debuginfo/generic-functions-nested.rs +++ b/src/test/debuginfo/generic-functions-nested.rs @@ -43,8 +43,8 @@ // gdb-command:continue fn outer<TA: Clone>(a: TA) { - inner(a.clone(), 1); - inner(a.clone(), 2.5); + inner(a.clone(), 1i); + inner(a.clone(), 2.5f64); fn inner<TX, TY>(x: TX, y: TY) { zzz(); diff --git a/src/test/debuginfo/generic-method-on-generic-struct.rs b/src/test/debuginfo/generic-method-on-generic-struct.rs index ad088d9a5eb..9ed1c0175a9 100644 --- a/src/test/debuginfo/generic-method-on-generic-struct.rs +++ b/src/test/debuginfo/generic-method-on-generic-struct.rs @@ -91,7 +91,7 @@ fn main() { let _ = stack.self_by_ref(-1, -2_i8); let _ = stack.self_by_val(-3, -4_i16); - let owned = box Struct { x: 1234.5 }; + let owned = box Struct { x: 1234.5f64 }; let _ = owned.self_by_ref(-5, -6_i32); let _ = owned.self_by_val(-7, -8_i64); let _ = owned.self_owned(-9, -10.5_f32); diff --git a/src/test/debuginfo/generic-static-method-on-struct-and-enum.rs b/src/test/debuginfo/generic-static-method-on-struct-and-enum.rs index 82a9d708966..b62b6f186b9 100644 --- a/src/test/debuginfo/generic-static-method-on-struct-and-enum.rs +++ b/src/test/debuginfo/generic-static-method-on-struct-and-enum.rs @@ -61,8 +61,8 @@ impl Enum { } fn main() { - Struct::static_method(1, 2); - Enum::static_method(-3, 4.5, 5); + Struct::static_method(1i, 2i); + Enum::static_method(-3i, 4.5f64, 5i); } fn zzz() {()} diff --git a/src/test/debuginfo/generic-struct-style-enum.rs b/src/test/debuginfo/generic-struct-style-enum.rs index eddf4dfd755..7fec116b8e5 100644 --- a/src/test/debuginfo/generic-struct-style-enum.rs +++ b/src/test/debuginfo/generic-struct-style-enum.rs @@ -72,7 +72,7 @@ fn main() { // 0b01011001 = 89 let case3: Regular<u16, i32, u64> = Case3 { a: 0, b: 6438275382588823897 }; - let univariant = TheOnlyCase { a: -1 }; + let univariant = TheOnlyCase { a: -1i }; zzz(); } diff --git a/src/test/debuginfo/generic-struct.rs b/src/test/debuginfo/generic-struct.rs index 69217f4b878..a2c5a0973fc 100644 --- a/src/test/debuginfo/generic-struct.rs +++ b/src/test/debuginfo/generic-struct.rs @@ -31,10 +31,13 @@ struct AGenericStruct<TKey, TValue> { fn main() { - let int_int = AGenericStruct { key: 0, value: 1 }; - let int_float = AGenericStruct { key: 2, value: 3.5 }; - let float_int = AGenericStruct { key: 4.5, value: 5 }; - let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key: 7, value: 8.5 } }; + let int_int = AGenericStruct { key: 0i, value: 1i }; + let int_float = AGenericStruct { key: 2i, value: 3.5f64 }; + let float_int = AGenericStruct { key: 4.5f64, value: 5i }; + let float_int_float = AGenericStruct { + key: 6.5f64, + value: AGenericStruct { key: 7i, value: 8.5f64 }, + }; zzz(); } diff --git a/src/test/debuginfo/lexical-scope-in-for-loop.rs b/src/test/debuginfo/lexical-scope-in-for-loop.rs index 0f6ac953179..0fb823a74cc 100644 --- a/src/test/debuginfo/lexical-scope-in-for-loop.rs +++ b/src/test/debuginfo/lexical-scope-in-for-loop.rs @@ -55,15 +55,15 @@ fn main() { - let range = [1, 2, 3]; + let range = [1i, 2, 3]; - let x = 1000000; // wan meeeljen doollaars! + let x = 1000000i; // wan meeeljen doollaars! for &x in range.iter() { zzz(); sentinel(); - let x = -1 * x; + let x = -1i * x; zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scope-in-if.rs b/src/test/debuginfo/lexical-scope-in-if.rs index ef573735d0d..6018e62af00 100644 --- a/src/test/debuginfo/lexical-scope-in-if.rs +++ b/src/test/debuginfo/lexical-scope-in-if.rs @@ -80,8 +80,8 @@ fn main() { - let x = 999; - let y = -1; + let x = 999i; + let y = -1i; zzz(); sentinel(); @@ -90,13 +90,13 @@ fn main() { zzz(); sentinel(); - let x = 1001; + let x = 1001i; zzz(); sentinel(); - let x = 1002; - let y = 1003; + let x = 1002i; + let y = 1003i; zzz(); sentinel(); } else { @@ -112,8 +112,8 @@ fn main() { zzz(); sentinel(); - let x = 1004; - let y = 1005; + let x = 1004i; + let y = 1005i; zzz(); sentinel(); } diff --git a/src/test/debuginfo/lexical-scope-in-match.rs b/src/test/debuginfo/lexical-scope-in-match.rs index b347afbbbcd..7bec677e4b1 100644 --- a/src/test/debuginfo/lexical-scope-in-match.rs +++ b/src/test/debuginfo/lexical-scope-in-match.rs @@ -81,13 +81,13 @@ struct Struct { fn main() { - let shadowed = 231; - let not_shadowed = 232; + let shadowed = 231i; + let not_shadowed = 232i; zzz(); sentinel(); - match (233, 234) { + match (233i, 234i) { (shadowed, local_to_arm) => { zzz(); @@ -95,7 +95,7 @@ fn main() { } } - match (235, 236) { + match (235i, 236i) { // with literal (235, shadowed) => { @@ -132,7 +132,7 @@ fn main() { _ => {} } - match (243, 244) { + match (243i, 244i) { (shadowed, ref local_to_arm) => { zzz(); diff --git a/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs b/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs index ad8f04d1fc7..0e47f2c9921 100644 --- a/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs +++ b/src/test/debuginfo/lexical-scope-in-parameterless-closure.rs @@ -16,6 +16,6 @@ // Nothing to do here really, just make sure it compiles. See issue #8513. fn main() { let _ = ||(); - let _ = range(1u,3).map(|_| 5); + let _ = range(1u,3).map(|_| 5i); } diff --git a/src/test/debuginfo/lexical-scope-in-stack-closure.rs b/src/test/debuginfo/lexical-scope-in-stack-closure.rs index c56cdbe0315..0168eaa86c2 100644 --- a/src/test/debuginfo/lexical-scope-in-stack-closure.rs +++ b/src/test/debuginfo/lexical-scope-in-stack-closure.rs @@ -55,7 +55,7 @@ fn main() { zzz(); sentinel(); - let x = 2.5; + let x = 2.5f64; zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scope-in-unconditional-loop.rs b/src/test/debuginfo/lexical-scope-in-unconditional-loop.rs index 12e95c4f9c7..48edd7ae12a 100644 --- a/src/test/debuginfo/lexical-scope-in-unconditional-loop.rs +++ b/src/test/debuginfo/lexical-scope-in-unconditional-loop.rs @@ -84,7 +84,7 @@ fn main() { - let mut x = 0; + let mut x = 0i; loop { if x >= 2 { @@ -108,7 +108,7 @@ fn main() { zzz(); sentinel(); - let x = -987; + let x = -987i; zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scope-in-unique-closure.rs b/src/test/debuginfo/lexical-scope-in-unique-closure.rs index 328910b0f13..ce3b2a530e2 100644 --- a/src/test/debuginfo/lexical-scope-in-unique-closure.rs +++ b/src/test/debuginfo/lexical-scope-in-unique-closure.rs @@ -55,7 +55,7 @@ fn main() { zzz(); sentinel(); - let x = 2.5; + let x = 2.5f64; zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scope-in-while.rs b/src/test/debuginfo/lexical-scope-in-while.rs index 1b2a9f75182..d726eb6581e 100644 --- a/src/test/debuginfo/lexical-scope-in-while.rs +++ b/src/test/debuginfo/lexical-scope-in-while.rs @@ -84,7 +84,7 @@ fn main() { - let mut x = 0; + let mut x = 0i; while x < 2 { zzz(); @@ -104,7 +104,7 @@ fn main() { zzz(); sentinel(); - let x = -987; + let x = -987i; zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scope-with-macro.rs b/src/test/debuginfo/lexical-scope-with-macro.rs index 3fb6f10fe33..e55271239d4 100644 --- a/src/test/debuginfo/lexical-scope-with-macro.rs +++ b/src/test/debuginfo/lexical-scope-with-macro.rs @@ -77,7 +77,7 @@ macro_rules! no_new_scope( macro_rules! new_scope( () => ({ - let a = 890242; + let a = 890242i; zzz(); sentinel(); }) @@ -105,8 +105,8 @@ macro_rules! dup_expr( fn main() { - let a = trivial!(10); - let b = no_new_scope!(33); + let a = trivial!(10i); + let b = no_new_scope!(33i); zzz(); sentinel(); @@ -116,12 +116,12 @@ fn main() { zzz(); sentinel(); - shadow_within_macro!(100); + shadow_within_macro!(100i); zzz(); sentinel(); - let c = dup_expr!(10 * 20); + let c = dup_expr!(10i * 20); zzz(); sentinel(); diff --git a/src/test/debuginfo/lexical-scopes-in-block-expression.rs b/src/test/debuginfo/lexical-scopes-in-block-expression.rs index 41b88dc3e98..2a9969dc6e9 100644 --- a/src/test/debuginfo/lexical-scopes-in-block-expression.rs +++ b/src/test/debuginfo/lexical-scopes-in-block-expression.rs @@ -227,8 +227,8 @@ fn a_function(x: int) -> int { fn main() { - let val = -1; - let ten = 10; + let val = -1i; + let ten = 10i; // surrounded by struct expression let point = Point { @@ -280,7 +280,7 @@ fn main() { sentinel(); val - }, 0); + }, 0i); zzz(); sentinel(); @@ -355,7 +355,7 @@ fn main() { sentinel(); // index expression - let a_vector = [10, ..20]; + let a_vector = [10i, ..20]; let _ = a_vector[{ zzz(); sentinel(); diff --git a/src/test/debuginfo/limited-debuginfo.rs b/src/test/debuginfo/limited-debuginfo.rs index 616f312c078..9cda2c45131 100644 --- a/src/test/debuginfo/limited-debuginfo.rs +++ b/src/test/debuginfo/limited-debuginfo.rs @@ -46,7 +46,7 @@ fn zzz() {()} fn some_function(a: int, b: int) { let some_variable = Struct { a: 11, b: 22 }; - let some_other_variable = 23; + let some_other_variable = 23i; zzz(); } diff --git a/src/test/debuginfo/managed-pointer-within-unique.rs b/src/test/debuginfo/managed-pointer-within-unique.rs index b56db2d1846..cc18ea64f38 100644 --- a/src/test/debuginfo/managed-pointer-within-unique.rs +++ b/src/test/debuginfo/managed-pointer-within-unique.rs @@ -37,9 +37,9 @@ struct ContainsManaged { } fn main() { - let ordinary_unique = box() (-1, -2); + let ordinary_unique = box() (-1i, -2i); - let managed_within_unique = box ContainsManaged { x: -3, y: box(GC) -4 }; + let managed_within_unique = box ContainsManaged { x: -3, y: box(GC) -4i }; zzz(); } diff --git a/src/test/debuginfo/method-on-generic-struct.rs b/src/test/debuginfo/method-on-generic-struct.rs index 2f7b0c845ea..0bac86b1e66 100644 --- a/src/test/debuginfo/method-on-generic-struct.rs +++ b/src/test/debuginfo/method-on-generic-struct.rs @@ -91,7 +91,7 @@ fn main() { let _ = stack.self_by_ref(-1, -2); let _ = stack.self_by_val(-3, -4); - let owned = box Struct { x: 1234.5 }; + let owned = box Struct { x: 1234.5f64 }; let _ = owned.self_by_ref(-5, -6); let _ = owned.self_by_val(-7, -8); let _ = owned.self_owned(-9, -10); diff --git a/src/test/debuginfo/multiple-functions-equal-var-names.rs b/src/test/debuginfo/multiple-functions-equal-var-names.rs index 510718254d9..9e40f03c201 100644 --- a/src/test/debuginfo/multiple-functions-equal-var-names.rs +++ b/src/test/debuginfo/multiple-functions-equal-var-names.rs @@ -31,18 +31,18 @@ #![allow(unused_variable)] fn function_one() { - let abc = 10101; + let abc = 10101i; zzz(); } fn function_two() { - let abc = 20202; + let abc = 20202i; zzz(); } fn function_three() { - let abc = 30303; + let abc = 30303i; zzz(); } diff --git a/src/test/debuginfo/multiple-functions.rs b/src/test/debuginfo/multiple-functions.rs index 362a8a93dd1..ef1c69f9eb8 100644 --- a/src/test/debuginfo/multiple-functions.rs +++ b/src/test/debuginfo/multiple-functions.rs @@ -31,18 +31,18 @@ #![allow(unused_variable)] fn function_one() { - let a = 10101; + let a = 10101i; zzz(); } fn function_two() { - let b = 20202; + let b = 20202i; zzz(); } fn function_three() { - let c = 30303; + let c = 30303i; zzz(); } diff --git a/src/test/debuginfo/name-shadowing-and-scope-nesting.rs b/src/test/debuginfo/name-shadowing-and-scope-nesting.rs index f967ced38ec..8ee6d434016 100644 --- a/src/test/debuginfo/name-shadowing-and-scope-nesting.rs +++ b/src/test/debuginfo/name-shadowing-and-scope-nesting.rs @@ -63,25 +63,25 @@ fn main() { zzz(); sentinel(); - let x = 10; + let x = 10i; zzz(); sentinel(); - let x = 10.5; - let y = 20; + let x = 10.5f64; + let y = 20i; zzz(); sentinel(); { let x = true; - let y = 2220; + let y = 2220i; zzz(); sentinel(); - let x = 203203.5; + let x = 203203.5f64; zzz(); sentinel(); diff --git a/src/test/debuginfo/option-like-enum.rs b/src/test/debuginfo/option-like-enum.rs index 04cd7e13863..de6d6814308 100644 --- a/src/test/debuginfo/option-like-enum.rs +++ b/src/test/debuginfo/option-like-enum.rs @@ -72,18 +72,18 @@ struct NamedFieldsRepr<'a> { fn main() { - let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678) }); + let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678u) }); let none: Option<&u32> = None; - let full = Full(454545, unsafe { std::mem::transmute(0x87654321) }, 9988); + let full = Full(454545, unsafe { std::mem::transmute(0x87654321u) }, 9988); - let int_val = 0; + let int_val = 0i; let empty: &MoreFieldsRepr = unsafe { std::mem::transmute(&Empty) }; let droid = Droid { id: 675675, range: 10000001, - internals: unsafe { std::mem::transmute(0x43218765) } + internals: unsafe { std::mem::transmute(0x43218765u) } }; let void_droid: &NamedFieldsRepr = unsafe { std::mem::transmute(&Void) }; diff --git a/src/test/debuginfo/shadowed-argument.rs b/src/test/debuginfo/shadowed-argument.rs index 129263c0f76..c180d6b5bcf 100644 --- a/src/test/debuginfo/shadowed-argument.rs +++ b/src/test/debuginfo/shadowed-argument.rs @@ -39,13 +39,13 @@ fn a_function(x: bool, y: bool) { zzz(); sentinel(); - let x = 10; + let x = 10i; zzz(); sentinel(); - let x = 10.5; - let y = 20; + let x = 10.5f64; + let y = 20i; zzz(); sentinel(); diff --git a/src/test/debuginfo/shadowed-variable.rs b/src/test/debuginfo/shadowed-variable.rs index 825ecb9c0ca..88ef3c4879e 100644 --- a/src/test/debuginfo/shadowed-variable.rs +++ b/src/test/debuginfo/shadowed-variable.rs @@ -42,13 +42,13 @@ fn main() { zzz(); sentinel(); - let x = 10; + let x = 10i; zzz(); sentinel(); - let x = 10.5; - let y = 20; + let x = 10.5f64; + let y = 20i; zzz(); sentinel(); diff --git a/src/test/debuginfo/simple-lexical-scope.rs b/src/test/debuginfo/simple-lexical-scope.rs index 171e3eae659..107b64131e0 100644 --- a/src/test/debuginfo/simple-lexical-scope.rs +++ b/src/test/debuginfo/simple-lexical-scope.rs @@ -60,7 +60,7 @@ fn main() { zzz(); sentinel(); - let x = 10; + let x = 10i; zzz(); sentinel(); @@ -69,7 +69,7 @@ fn main() { zzz(); sentinel(); - let x = 10.5; + let x = 10.5f64; zzz(); sentinel(); diff --git a/src/test/debuginfo/vec.rs b/src/test/debuginfo/vec.rs index 11f317469a2..155865f415b 100644 --- a/src/test/debuginfo/vec.rs +++ b/src/test/debuginfo/vec.rs @@ -26,7 +26,7 @@ static mut VECT: [i32, ..3] = [1, 2, 3]; fn main() { - let a = [1, 2, 3]; + let a = [1i, 2, 3]; unsafe { VECT[0] = 4; diff --git a/src/test/pretty/block-disambig.rs b/src/test/pretty/block-disambig.rs index 20d634d0475..9433ddf1a1f 100644 --- a/src/test/pretty/block-disambig.rs +++ b/src/test/pretty/block-disambig.rs @@ -17,9 +17,9 @@ use std::cell::Cell; use std::gc::GC; -fn test1() { let val = box(GC) 0; { } *val; } +fn test1() { let val = box(GC) 0i; { } *val; } -fn test2() -> int { let val = box(GC) 0; { } *val } +fn test2() -> int { let val = box(GC) 0i; { } *val } struct S { eax: int } @@ -36,13 +36,13 @@ fn test5() -> (int, int) { { } (0, 1) } fn test6() -> bool { { } (true || false) && true } fn test7() -> uint { - let regs = box(GC) 0; + let regs = box(GC) 0i; match true { true => { } _ => { } } (*regs < 2) as uint } fn test8() -> int { - let val = box(GC) 0; + let val = box(GC) 0i; match true { true => { } _ => { } @@ -55,12 +55,12 @@ fn test8() -> int { } fn test9() { - let regs = box(GC) Cell::new(0); + let regs = box(GC) Cell::new(0i); match true { true => { } _ => { } } regs.set(regs.get() + 1); } fn test10() -> int { - let regs = box(GC) vec!(0); + let regs = box(GC) vec!(0i); match true { true => { } _ => { } } *(*regs).get(0) } diff --git a/src/test/pretty/issue-929.rs b/src/test/pretty/issue-929.rs index 636fac82b6b..85b71e4e86c 100644 --- a/src/test/pretty/issue-929.rs +++ b/src/test/pretty/issue-929.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f() { if (1 == fail!()) { } else { } } +fn f() { if (1i == fail!()) { } else { } } fn main() { } diff --git a/src/test/pretty/match-naked-expr-medium.rs b/src/test/pretty/match-naked-expr-medium.rs index 5cf6d838f25..c03ad499478 100644 --- a/src/test/pretty/match-naked-expr-medium.rs +++ b/src/test/pretty/match-naked-expr-medium.rs @@ -11,7 +11,7 @@ // pp-exact fn main() { - let x = Some(3); + let x = Some(3i); let _y = match x { Some(_) => diff --git a/src/test/pretty/match-naked-expr.rs b/src/test/pretty/match-naked-expr.rs index bb14a74fc18..67c389f7e1f 100644 --- a/src/test/pretty/match-naked-expr.rs +++ b/src/test/pretty/match-naked-expr.rs @@ -11,7 +11,7 @@ // pp-exact fn main() { - let x = Some(3); + let x = Some(3i); let _y = match x { Some(_) => "some(_)".to_string(), diff --git a/src/test/pretty/unary-op-disambig.rs b/src/test/pretty/unary-op-disambig.rs index 1592e010aaf..850904fe53e 100644 --- a/src/test/pretty/unary-op-disambig.rs +++ b/src/test/pretty/unary-op-disambig.rs @@ -18,10 +18,10 @@ fn block_nosemi() -> int { ({ 0 }) - 1 } fn if_semi() -> int { if true { f() } else { f() }; -1 } -fn if_nosemi() -> int { (if true { 0 } else { 0 }) - 1 } +fn if_nosemi() -> int { (if true { 0i } else { 0i }) - 1 } fn alt_semi() -> int { match true { true => { f() } _ => { } }; -1 } fn alt_no_semi() -> int { (match true { true => { 0 } _ => { 1 } }) - 1 } -fn stmt() { { f() }; -1; } +fn stmt() { { f() }; -1i; } diff --git a/src/test/pretty/vec-comments.pp b/src/test/pretty/vec-comments.pp index dc2dae1044d..401c63efbc4 100644 --- a/src/test/pretty/vec-comments.pp +++ b/src/test/pretty/vec-comments.pp @@ -15,25 +15,25 @@ fn main() { let _v1 = [ // Comment - 0, + 0i, // Comment - 1, + 1i, // Comment - 2]; + 2i]; let _v2 = - [0, // Comment - 1, // Comment - 2]; // Comment + [0i, // Comment + 1i, // Comment + 2i]; // Comment let _v3 = [ /* Comment */ - 0, + 0i, /* Comment */ - 1, + 1i, /* Comment */ - 2]; + 2i]; let _v4 = - [0, /* Comment */ - 1, /* Comment */ - 2]; /* Comment */ + [0i, /* Comment */ + 1i, /* Comment */ + 2i]; /* Comment */ } diff --git a/src/test/pretty/vec-comments.rs b/src/test/pretty/vec-comments.rs index dc2dae1044d..401c63efbc4 100644 --- a/src/test/pretty/vec-comments.rs +++ b/src/test/pretty/vec-comments.rs @@ -15,25 +15,25 @@ fn main() { let _v1 = [ // Comment - 0, + 0i, // Comment - 1, + 1i, // Comment - 2]; + 2i]; let _v2 = - [0, // Comment - 1, // Comment - 2]; // Comment + [0i, // Comment + 1i, // Comment + 2i]; // Comment let _v3 = [ /* Comment */ - 0, + 0i, /* Comment */ - 1, + 1i, /* Comment */ - 2]; + 2i]; let _v4 = - [0, /* Comment */ - 1, /* Comment */ - 2]; /* Comment */ + [0i, /* Comment */ + 1i, /* Comment */ + 2i]; /* Comment */ } diff --git a/src/test/run-fail/assert-as-macro.rs b/src/test/run-fail/assert-as-macro.rs index c52c11b1b91..fb069e61bd2 100644 --- a/src/test/run-fail/assert-as-macro.rs +++ b/src/test/run-fail/assert-as-macro.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:assertion failed: 1 == 2 +// error-pattern:assertion failed: 1i == 2 fn main() { - assert!(1 == 2); + assert!(1i == 2); } diff --git a/src/test/run-fail/bounds-check-no-overflow.rs b/src/test/run-fail/bounds-check-no-overflow.rs index be4ad0781f2..df9050e2186 100644 --- a/src/test/run-fail/bounds-check-no-overflow.rs +++ b/src/test/run-fail/bounds-check-no-overflow.rs @@ -14,6 +14,6 @@ use std::uint; use std::mem::size_of; fn main() { - let xs = [1, 2, 3]; + let xs = [1i, 2, 3]; xs[uint::MAX / size_of::<int>() + 1]; } diff --git a/src/test/run-fail/by-value-self-objects-fail.rs b/src/test/run-fail/by-value-self-objects-fail.rs new file mode 100644 index 00000000000..74889263cc8 --- /dev/null +++ b/src/test/run-fail/by-value-self-objects-fail.rs @@ -0,0 +1,51 @@ +// 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. + +// error-pattern:explicit failure + +trait Foo { + fn foo(self, x: int); +} + +struct S { + x: int, + y: int, + z: int, + s: String, +} + +impl Foo for S { + fn foo(self, x: int) { + fail!() + } +} + +impl Drop for S { + fn drop(&mut self) { + println!("bye 1!"); + } +} + +fn f() { + let s = S { + x: 2, + y: 3, + z: 4, + s: "hello".to_string(), + }; + let st = box s as Box<Foo>; + st.foo(5); +} + +fn main() { + f(); +} + + diff --git a/src/test/run-fail/divide-by-zero.rs b/src/test/run-fail/divide-by-zero.rs index de69b7b9fa6..c58d30f2729 100644 --- a/src/test/run-fail/divide-by-zero.rs +++ b/src/test/run-fail/divide-by-zero.rs @@ -10,6 +10,6 @@ // error-pattern:attempted to divide by zero fn main() { - let y = 0; - let _z = 1 / y; + let y = 0i; + let _z = 1i / y; } diff --git a/src/test/run-fail/explicit-fail-msg.rs b/src/test/run-fail/explicit-fail-msg.rs index f860fdffba1..4af9b82ec7e 100644 --- a/src/test/run-fail/explicit-fail-msg.rs +++ b/src/test/run-fail/explicit-fail-msg.rs @@ -13,7 +13,7 @@ // error-pattern:wooooo fn main() { - let mut a = 1; - if 1 == 1 { a = 2; } + let mut a = 1i; + if 1i == 1 { a = 2; } fail!(format!("woooo{}", "o")); } diff --git a/src/test/run-fail/expr-if-fail.rs b/src/test/run-fail/expr-if-fail.rs index 73259e6e140..55d86bc6493 100644 --- a/src/test/run-fail/expr-if-fail.rs +++ b/src/test/run-fail/expr-if-fail.rs @@ -12,4 +12,4 @@ // error-pattern:explicit failure -fn main() { let _x = if false { 0 } else if true { fail!() } else { 10 }; } +fn main() { let _x = if false { 0i } else if true { fail!() } else { 10i }; } diff --git a/src/test/run-fail/expr-match-fail.rs b/src/test/run-fail/expr-match-fail.rs index 075f6f5b4b1..d15ec3f7b48 100644 --- a/src/test/run-fail/expr-match-fail.rs +++ b/src/test/run-fail/expr-match-fail.rs @@ -12,4 +12,4 @@ // error-pattern:explicit failure -fn main() { let _x = match true { false => { 0 } true => { fail!() } }; } +fn main() { let _x = match true { false => { 0i } true => { fail!() } }; } diff --git a/src/test/run-fail/fail-task-name-none.rs b/src/test/run-fail/fail-task-name-none.rs index 3f662e6d0e3..75d23d0f4fd 100644 --- a/src/test/run-fail/fail-task-name-none.rs +++ b/src/test/run-fail/fail-task-name-none.rs @@ -13,8 +13,9 @@ use std::task; fn main() { - task::try(proc() { + let r: Result<int,_> = task::try(proc() { fail!("test"); - 1 - }).unwrap() + 1i + }); + assert!(r.is_ok()); } diff --git a/src/test/run-fail/fail-task-name-owned.rs b/src/test/run-fail/fail-task-name-owned.rs index ea643fd26d9..edb03b2d6b4 100644 --- a/src/test/run-fail/fail-task-name-owned.rs +++ b/src/test/run-fail/fail-task-name-owned.rs @@ -13,8 +13,10 @@ use std::task::TaskBuilder; fn main() { - TaskBuilder::new().named("owned name".to_string()).try(proc() { + let r: Result<int,_> = TaskBuilder::new().named("owned name".to_string()) + .try(proc() { fail!("test"); - 1 - }).unwrap() + 1i + }); + assert!(r.is_ok()); } diff --git a/src/test/run-fail/fail-task-name-send-str.rs b/src/test/run-fail/fail-task-name-send-str.rs index d99c805323f..0a740099778 100644 --- a/src/test/run-fail/fail-task-name-send-str.rs +++ b/src/test/run-fail/fail-task-name-send-str.rs @@ -11,8 +11,11 @@ // error-pattern:task 'send name' failed at 'test' fn main() { - ::std::task::TaskBuilder::new().named("send name".into_maybe_owned()).try(proc() { - fail!("test"); - 3 - }).unwrap() + let r: Result<int,_> = + ::std::task::TaskBuilder::new().named("send name".into_maybe_owned()) + .try(proc() { + fail!("test"); + 3i + }); + assert!(r.is_ok()); } diff --git a/src/test/run-fail/fail-task-name-static.rs b/src/test/run-fail/fail-task-name-static.rs index e0c98c5744e..0b2901889cb 100644 --- a/src/test/run-fail/fail-task-name-static.rs +++ b/src/test/run-fail/fail-task-name-static.rs @@ -11,7 +11,9 @@ // error-pattern:task 'static name' failed at 'test' fn main() { - ::std::task::TaskBuilder::new().named("static name").try(proc() { - fail!("test"); - }).unwrap() + let r: Result<int,_> = + ::std::task::TaskBuilder::new().named("static name").try(proc() { + fail!("test"); + }); + assert!(r.is_ok()); } diff --git a/src/test/run-fail/fail.rs b/src/test/run-fail/fail.rs index 42cf79af66e..54ccc98bcd9 100644 --- a/src/test/run-fail/fail.rs +++ b/src/test/run-fail/fail.rs @@ -11,5 +11,5 @@ -// error-pattern:1 == 2 -fn main() { assert!((1 == 2)); } +// error-pattern:1i == 2 +fn main() { assert!((1i == 2)); } diff --git a/src/test/run-fail/issue-3029.rs b/src/test/run-fail/issue-3029.rs index a57f4683df3..80e275019ce 100644 --- a/src/test/run-fail/issue-3029.rs +++ b/src/test/run-fail/issue-3029.rs @@ -16,7 +16,7 @@ // error-pattern:so long fn main() { let mut x = Vec::new(); - let y = vec!(3); + let y = vec!(3i); fail!("so long"); x.push_all_move(y); } diff --git a/src/test/run-fail/mod-zero.rs b/src/test/run-fail/mod-zero.rs index 76d4de7ecb0..54415051708 100644 --- a/src/test/run-fail/mod-zero.rs +++ b/src/test/run-fail/mod-zero.rs @@ -10,6 +10,6 @@ // error-pattern:attempted remainder with a divisor of zero fn main() { - let y = 0; - let _z = 1 % y; + let y = 0i; + let _z = 1i % y; } diff --git a/src/test/run-fail/native-failure.rs b/src/test/run-fail/native-failure.rs index 377057a75ff..ae3924ba935 100644 --- a/src/test/run-fail/native-failure.rs +++ b/src/test/run-fail/native-failure.rs @@ -14,7 +14,7 @@ extern crate native; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { native::start(argc, argv, proc() { fail!(); }) diff --git a/src/test/run-fail/str-overrun.rs b/src/test/run-fail/str-overrun.rs index 26c5a6988cf..c3ee76047d1 100644 --- a/src/test/run-fail/str-overrun.rs +++ b/src/test/run-fail/str-overrun.rs @@ -14,5 +14,5 @@ fn main() { let s: String = "hello".to_string(); // Bounds-check failure. - assert_eq!(s.as_slice()[5], 0x0 as u8); + assert_eq!(s.as_bytes()[5], 0x0 as u8); } diff --git a/src/test/run-fail/task-spawn-barefn.rs b/src/test/run-fail/task-spawn-barefn.rs index ae189889967..e7fd97f8d31 100644 --- a/src/test/run-fail/task-spawn-barefn.rs +++ b/src/test/run-fail/task-spawn-barefn.rs @@ -15,7 +15,10 @@ use std::task; fn main() { // the purpose of this test is to make sure that task::spawn() // works when provided with a bare function: - task::try(startfn).unwrap(); + let r = task::try(startfn); + if r.is_err() { + fail!() + } } fn startfn() { diff --git a/src/test/run-fail/unwind-assert.rs b/src/test/run-fail/unwind-assert.rs index 2f6bd9ad255..c4dd8802d8a 100644 --- a/src/test/run-fail/unwind-assert.rs +++ b/src/test/run-fail/unwind-assert.rs @@ -15,6 +15,6 @@ use std::gc::GC; fn main() { - let _a = box(GC) 0; + let _a = box(GC) 0i; assert!(false); } diff --git a/src/test/run-fail/unwind-box-res.rs b/src/test/run-fail/unwind-box-res.rs index ce24d265504..f80f25ec6eb 100644 --- a/src/test/run-fail/unwind-box-res.rs +++ b/src/test/run-fail/unwind-box-res.rs @@ -22,7 +22,7 @@ fn failfn() { } struct r { - v: *int, + v: *const int, } impl Drop for r { @@ -33,7 +33,7 @@ impl Drop for r { } } -fn r(v: *int) -> r { +fn r(v: *const int) -> r { r { v: v } @@ -41,7 +41,7 @@ fn r(v: *int) -> r { fn main() { unsafe { - let i1 = box 0; + let i1 = box 0i; let i1p = mem::transmute_copy(&i1); mem::forget(i1); let x = box(GC) r(i1p); diff --git a/src/test/run-fail/unwind-box.rs b/src/test/run-fail/unwind-box.rs index e31f66ed9fb..3647c553bf2 100644 --- a/src/test/run-fail/unwind-box.rs +++ b/src/test/run-fail/unwind-box.rs @@ -19,6 +19,6 @@ fn failfn() { } fn main() { - box(GC) 0; + box(GC) 0i; failfn(); } diff --git a/src/test/run-fail/unwind-fail.rs b/src/test/run-fail/unwind-fail.rs index 5dbfd73c1d7..e25fe1908ba 100644 --- a/src/test/run-fail/unwind-fail.rs +++ b/src/test/run-fail/unwind-fail.rs @@ -15,6 +15,6 @@ use std::gc::GC; fn main() { - box(GC) 0; + box(GC) 0i; fail!(); } diff --git a/src/test/run-fail/unwind-interleaved.rs b/src/test/run-fail/unwind-interleaved.rs index 6f2400ec4f0..f6a3aa48def 100644 --- a/src/test/run-fail/unwind-interleaved.rs +++ b/src/test/run-fail/unwind-interleaved.rs @@ -15,8 +15,8 @@ fn a() { } fn b() { fail!(); } fn main() { - let _x = vec!(0); + let _x = vec!(0i); a(); - let _y = vec!(0); + let _y = vec!(0i); b(); } diff --git a/src/test/run-fail/unwind-iter.rs b/src/test/run-fail/unwind-iter.rs index 8671758c423..d77a9f911b5 100644 --- a/src/test/run-fail/unwind-iter.rs +++ b/src/test/run-fail/unwind-iter.rs @@ -22,6 +22,6 @@ fn x(it: |int|) { } fn main() { - let a = box(GC) 0; + let a = box(GC) 0i; x(|_i| { } ); } diff --git a/src/test/run-fail/unwind-iter2.rs b/src/test/run-fail/unwind-iter2.rs index d7b950ad5c1..9f00c0bc8ba 100644 --- a/src/test/run-fail/unwind-iter2.rs +++ b/src/test/run-fail/unwind-iter2.rs @@ -15,7 +15,7 @@ use std::gc::{GC}; fn x(it: |int|) { - let _a = box(GC) 0; + let _a = box(GC) 0i; it(1); } diff --git a/src/test/run-fail/unwind-match.rs b/src/test/run-fail/unwind-match.rs index 4f1e454c39e..f256884b312 100644 --- a/src/test/run-fail/unwind-match.rs +++ b/src/test/run-fail/unwind-match.rs @@ -16,7 +16,7 @@ use std::gc::GC; fn test_box() { - box(GC) 0; + box(GC) 0i; } fn test_str() { let res = match false { true => { "happy".to_string() }, diff --git a/src/test/run-fail/unwind-nested.rs b/src/test/run-fail/unwind-nested.rs index b7a12f08c41..bebf06cf45a 100644 --- a/src/test/run-fail/unwind-nested.rs +++ b/src/test/run-fail/unwind-nested.rs @@ -15,9 +15,9 @@ use std::gc::GC; fn main() { - let _a = box(GC) 0; + let _a = box(GC) 0i; { - let _b = box(GC) 0; + let _b = box(GC) 0i; { fail!(); } diff --git a/src/test/run-fail/unwind-partial-box.rs b/src/test/run-fail/unwind-partial-box.rs index 2bd264d0e33..5912f8167bc 100644 --- a/src/test/run-fail/unwind-partial-box.rs +++ b/src/test/run-fail/unwind-partial-box.rs @@ -19,7 +19,7 @@ fn f() -> Vec<int> { fail!(); } // Voodoo. In unwind-alt we had to do this to trigger the bug. Might // have been to do with memory allocation patterns. fn prime() { - box(GC) 0; + box(GC) 0i; } fn partial() { diff --git a/src/test/run-fail/unwind-partial-unique.rs b/src/test/run-fail/unwind-partial-unique.rs index 4ea099e9c0f..2e6eee65738 100644 --- a/src/test/run-fail/unwind-partial-unique.rs +++ b/src/test/run-fail/unwind-partial-unique.rs @@ -19,7 +19,7 @@ fn f() -> Vec<int> { fail!(); } // Voodoo. In unwind-alt we had to do this to trigger the bug. Might // have been to do with memory allocation patterns. fn prime() { - box(GC) 0; + box(GC) 0i; } fn partial() { diff --git a/src/test/run-fail/unwind-partial-vec.rs b/src/test/run-fail/unwind-partial-vec.rs index e0e043f623b..7ad02fcd3d7 100644 --- a/src/test/run-fail/unwind-partial-vec.rs +++ b/src/test/run-fail/unwind-partial-vec.rs @@ -19,11 +19,11 @@ fn f() -> Vec<int> { fail!(); } // Voodoo. In unwind-alt we had to do this to trigger the bug. Might // have been to do with memory allocation patterns. fn prime() { - box(GC) 0; + box(GC) 0i; } fn partial() { - let _x = vec!(vec!(0), f(), vec!(0)); + let _x = vec!(vec!(0i), f(), vec!(0i)); } fn main() { diff --git a/src/test/run-fail/unwind-resource-fail.rs b/src/test/run-fail/unwind-resource-fail.rs index 498d3ee6b0b..8d0a14306d9 100644 --- a/src/test/run-fail/unwind-resource-fail.rs +++ b/src/test/run-fail/unwind-resource-fail.rs @@ -25,6 +25,6 @@ impl Drop for r { fn r(i: int) -> r { r { i: i } } fn main() { - box(GC) 0; + box(GC) 0i; let _r = r(0); } diff --git a/src/test/run-fail/unwind-stacked.rs b/src/test/run-fail/unwind-stacked.rs index da6205e9e37..97f4d974d8d 100644 --- a/src/test/run-fail/unwind-stacked.rs +++ b/src/test/run-fail/unwind-stacked.rs @@ -15,16 +15,16 @@ use std::gc::GC; fn f() { - let _a = box(GC) 0; + let _a = box(GC) 0i; fail!(); } fn g() { - let _b = box(GC) 0; + let _b = box(GC) 0i; f(); } fn main() { - let _a = box(GC) 0; + let _a = box(GC) 0i; g(); } diff --git a/src/test/run-fail/unwind-tup.rs b/src/test/run-fail/unwind-tup.rs index 08a22a7c355..4a7914c568a 100644 --- a/src/test/run-fail/unwind-tup.rs +++ b/src/test/run-fail/unwind-tup.rs @@ -19,5 +19,5 @@ fn fold_local() -> Gc<Vec<int>> { } fn main() { - let _lss = (fold_local(), 0); + let _lss = (fold_local(), 0i); } diff --git a/src/test/run-fail/unwind-uninitialized.rs b/src/test/run-fail/unwind-uninitialized.rs index acba93f7be3..29723b12729 100644 --- a/src/test/run-fail/unwind-uninitialized.rs +++ b/src/test/run-fail/unwind-uninitialized.rs @@ -20,5 +20,5 @@ fn f() { fn main() { f(); - let _a = box(GC) 0; + let _a = box(GC) 0i; } diff --git a/src/test/run-fail/unwind-unique.rs b/src/test/run-fail/unwind-unique.rs index af1e499d1f2..233d367c4b1 100644 --- a/src/test/run-fail/unwind-unique.rs +++ b/src/test/run-fail/unwind-unique.rs @@ -16,6 +16,6 @@ fn failfn() { } fn main() { - box 0; + box 0i; failfn(); } diff --git a/src/test/run-make/bootstrap-from-c-with-green/lib.rs b/src/test/run-make/bootstrap-from-c-with-green/lib.rs index bb68ba49168..69c65ef8b03 100644 --- a/src/test/run-make/bootstrap-from-c-with-green/lib.rs +++ b/src/test/run-make/bootstrap-from-c-with-green/lib.rs @@ -15,7 +15,7 @@ extern crate rustuv; extern crate green; #[no_mangle] // this needs to get called from C -pub extern "C" fn foo(argc: int, argv: **u8) -> int { +pub extern "C" fn foo(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, proc() { spawn(proc() { println!("hello"); diff --git a/src/test/run-make/bootstrap-from-c-with-native/lib.rs b/src/test/run-make/bootstrap-from-c-with-native/lib.rs index 7a78ec29a82..d211167626d 100644 --- a/src/test/run-make/bootstrap-from-c-with-native/lib.rs +++ b/src/test/run-make/bootstrap-from-c-with-native/lib.rs @@ -14,7 +14,7 @@ extern crate native; #[no_mangle] // this needs to get called from C -pub extern "C" fn foo(argc: int, argv: **u8) -> int { +pub extern "C" fn foo(argc: int, argv: *const *const u8) -> int { native::start(argc, argv, proc() { spawn(proc() { println!("hello"); diff --git a/src/test/run-make/graphviz-flowgraph/f01.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f01.dot-expected.dot index 9d8411cfc58..a5239a6cc66 100644 --- a/src/test/run-make/graphviz-flowgraph/f01.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f01.dot-expected.dot @@ -1,8 +1,8 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 1"]; - N3[label="block { 1; }"]; + N2[label="expr 1i"]; + N3[label="block { 1i; }"]; N0 -> N2; N2 -> N3; N3 -> N1; diff --git a/src/test/run-make/graphviz-flowgraph/f01.rs b/src/test/run-make/graphviz-flowgraph/f01.rs index 231aab69e50..f1f1a1d5472 100644 --- a/src/test/run-make/graphviz-flowgraph/f01.rs +++ b/src/test/run-make/graphviz-flowgraph/f01.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn lit_1() { - 1; + 1i; } diff --git a/src/test/run-make/graphviz-flowgraph/f03.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f03.dot-expected.dot index aff430459e8..43462862f6e 100644 --- a/src/test/run-make/graphviz-flowgraph/f03.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f03.dot-expected.dot @@ -1,10 +1,10 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 3"]; - N3[label="expr 33"]; - N4[label="expr 3 + 33"]; - N5[label="block { 3 + 33; }"]; + N2[label="expr 3i"]; + N3[label="expr 33i"]; + N4[label="expr 3i + 33i"]; + N5[label="block { 3i + 33i; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f03.rs b/src/test/run-make/graphviz-flowgraph/f03.rs index 8b172c0a105..1007225f2f2 100644 --- a/src/test/run-make/graphviz-flowgraph/f03.rs +++ b/src/test/run-make/graphviz-flowgraph/f03.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn expr_add_3() { - 3 + 33; + 3i + 33i; } diff --git a/src/test/run-make/graphviz-flowgraph/f04.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f04.dot-expected.dot index adcc582c733..26c858a0828 100644 --- a/src/test/run-make/graphviz-flowgraph/f04.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f04.dot-expected.dot @@ -1,9 +1,9 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 4"]; + N2[label="expr 4i"]; N3[label="local _x"]; - N4[label="block { let _x = 4; }"]; + N4[label="block { let _x = 4i; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f04.rs b/src/test/run-make/graphviz-flowgraph/f04.rs index 2a0ac8ac9e5..ed2f7e25dae 100644 --- a/src/test/run-make/graphviz-flowgraph/f04.rs +++ b/src/test/run-make/graphviz-flowgraph/f04.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn pat_id_4() { - let _x = 4; + let _x = 4i; } diff --git a/src/test/run-make/graphviz-flowgraph/f05.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f05.dot-expected.dot index 2d52c14da62..850d04f430f 100644 --- a/src/test/run-make/graphviz-flowgraph/f05.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f05.dot-expected.dot @@ -1,13 +1,13 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 5"]; - N3[label="expr 55"]; - N4[label="expr (5, 55)"]; + N2[label="expr 5i"]; + N3[label="expr 55i"]; + N4[label="expr (5i, 55i)"]; N5[label="local _x"]; N6[label="local _y"]; N7[label="pat (_x, _y)"]; - N8[label="block { let (_x, _y) = (5, 55); }"]; + N8[label="block { let (_x, _y) = (5i, 55i); }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f05.rs b/src/test/run-make/graphviz-flowgraph/f05.rs index 616d822bed0..b2591bdd08a 100644 --- a/src/test/run-make/graphviz-flowgraph/f05.rs +++ b/src/test/run-make/graphviz-flowgraph/f05.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn pat_tup_5() { - let (_x, _y) = (5, 55); + let (_x, _y) = (5i, 55i); } diff --git a/src/test/run-make/graphviz-flowgraph/f07.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f07.dot-expected.dot index c99af179149..251798fc7ed 100644 --- a/src/test/run-make/graphviz-flowgraph/f07.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f07.dot-expected.dot @@ -1,12 +1,12 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 7"]; - N3[label="expr 77"]; - N4[label="expr 777"]; - N5[label="expr 7777"]; - N6[label="expr [7, 77, 777, 7777]"]; - N7[label="expr match [7, 77, 777, 7777] { [x, y, ..] => x + y }"]; + N2[label="expr 7i"]; + N3[label="expr 77i"]; + N4[label="expr 777i"]; + N5[label="expr 7777i"]; + N6[label="expr [7i, 77i, 777i, 7777i]"]; + N7[label="expr match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y }"]; N8[label="local x"]; N9[label="local y"]; N10[label="pat .."]; @@ -14,7 +14,7 @@ digraph block { N12[label="expr x"]; N13[label="expr y"]; N14[label="expr x + y"]; - N15[label="block { match [7, 77, 777, 7777] { [x, y, ..] => x + y }; }"]; + N15[label="block { match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y }; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f07.rs b/src/test/run-make/graphviz-flowgraph/f07.rs index 39f71d309fd..fb3f2d24cdd 100644 --- a/src/test/run-make/graphviz-flowgraph/f07.rs +++ b/src/test/run-make/graphviz-flowgraph/f07.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn pat_vec_7() { - match [7, 77, 777, 7777] { + match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y }; } diff --git a/src/test/run-make/graphviz-flowgraph/f08.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f08.dot-expected.dot index 61a708cd9cc..f43beb025e3 100644 --- a/src/test/run-make/graphviz-flowgraph/f08.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f08.dot-expected.dot @@ -1,18 +1,18 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 8"]; + N2[label="expr 8i"]; N3[label="local x"]; N4[label="local _y"]; N5[label="expr x"]; - N6[label="expr 88"]; - N7[label="expr x > 88"]; - N8[label="expr 888"]; + N6[label="expr 88i"]; + N7[label="expr x > 88i"]; + N8[label="expr 888i"]; N9[label="expr _y"]; - N10[label="expr _y = 888"]; - N11[label="block { _y = 888; }"]; - N12[label="expr if x > 88 { _y = 888; }"]; - N13[label="block { let x = 8; let _y; if x > 88 { _y = 888; } }"]; + N10[label="expr _y = 888i"]; + N11[label="block { _y = 888i; }"]; + N12[label="expr if x > 88i { _y = 888i; }"]; + N13[label="block { let x = 8i; let _y; if x > 88i { _y = 888i; } }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f08.rs b/src/test/run-make/graphviz-flowgraph/f08.rs index 6ba7b03d54d..5d166e5ffcd 100644 --- a/src/test/run-make/graphviz-flowgraph/f08.rs +++ b/src/test/run-make/graphviz-flowgraph/f08.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn expr_if_onearm_8() { - let x = 8; let _y; - if x > 88 { - _y = 888; + let x = 8i; let _y; + if x > 88i { + _y = 888i; } } diff --git a/src/test/run-make/graphviz-flowgraph/f09.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f09.dot-expected.dot index 892b9fcd841..a3576b9c36b 100644 --- a/src/test/run-make/graphviz-flowgraph/f09.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f09.dot-expected.dot @@ -1,25 +1,25 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 91"]; + N2[label="expr 91i"]; N3[label="local x"]; N4[label="local _y"]; N5[label="expr x"]; - N6[label="expr 92"]; - N7[label="expr x > 92"]; - N8[label="expr 93"]; + N6[label="expr 92i"]; + N7[label="expr x > 92i"]; + N8[label="expr 93i"]; N9[label="expr _y"]; - N10[label="expr _y = 93"]; - N11[label="block { _y = 93; }"]; - N12[label="expr 94"]; - N13[label="expr 95"]; - N14[label="expr 94 + 95"]; + N10[label="expr _y = 93i"]; + N11[label="block { _y = 93i; }"]; + N12[label="expr 94i"]; + N13[label="expr 95i"]; + N14[label="expr 94i + 95i"]; N15[label="expr _y"]; - N16[label="expr _y = 94 + 95"]; - N17[label="block { _y = 94 + 95; }"]; - N18[label="expr { _y = 94 + 95; }"]; - N19[label="expr if x > 92 { _y = 93; } else { _y = 94 + 95; }"]; - N20[label="block { let x = 91; let _y; if x > 92 { _y = 93; } else { _y = 94 + 95; } }"]; + N16[label="expr _y = 94i + 95i"]; + N17[label="block { _y = 94i + 95i; }"]; + N18[label="expr { _y = 94i + 95i; }"]; + N19[label="expr if x > 92i { _y = 93i; } else { _y = 94i + 95i; }"]; + N20[label="block { let x = 91i; let _y; if x > 92i { _y = 93i; } else { _y = 94i + 95i; } }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f09.rs b/src/test/run-make/graphviz-flowgraph/f09.rs index a78ccb8a937..cfe5f4f37d6 100644 --- a/src/test/run-make/graphviz-flowgraph/f09.rs +++ b/src/test/run-make/graphviz-flowgraph/f09.rs @@ -9,10 +9,10 @@ // except according to those terms. pub fn expr_if_twoarm_9() { - let x = 91; let _y; - if x > 92 { - _y = 93; + let x = 91i; let _y; + if x > 92i { + _y = 93i; } else { - _y = 94+95; + _y = 94i+95i; } } diff --git a/src/test/run-make/graphviz-flowgraph/f10.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f10.dot-expected.dot index 2cef122104e..69b5bd6f58c 100644 --- a/src/test/run-make/graphviz-flowgraph/f10.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f10.dot-expected.dot @@ -1,18 +1,18 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 10"]; + N2[label="expr 10i"]; N3[label="local mut x"]; N4[label="(dummy_node)"]; N5[label="expr x"]; - N6[label="expr 0"]; - N7[label="expr x > 0"]; - N8[label="expr while x > 0 { x -= 1; }"]; - N9[label="expr 1"]; + N6[label="expr 0i"]; + N7[label="expr x > 0i"]; + N8[label="expr while x > 0i { x -= 1i; }"]; + N9[label="expr 1i"]; N10[label="expr x"]; - N11[label="expr x -= 1"]; - N12[label="block { x -= 1; }"]; - N13[label="block { let mut x = 10; while x > 0 { x -= 1; } }"]; + N11[label="expr x -= 1i"]; + N12[label="block { x -= 1i; }"]; + N13[label="block { let mut x = 10i; while x > 0i { x -= 1i; } }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f10.rs b/src/test/run-make/graphviz-flowgraph/f10.rs index 0ca7cc5ee86..af263f0cf10 100644 --- a/src/test/run-make/graphviz-flowgraph/f10.rs +++ b/src/test/run-make/graphviz-flowgraph/f10.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn expr_while_10() { - let mut x = 10; - while x > 0 { - x -= 1; + let mut x = 10i; + while x > 0i { + x -= 1i; } } diff --git a/src/test/run-make/graphviz-flowgraph/f11.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f11.dot-expected.dot index 59d65e5b8b7..44024cf76f3 100644 --- a/src/test/run-make/graphviz-flowgraph/f11.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f11.dot-expected.dot @@ -1,16 +1,16 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 11"]; + N2[label="expr 11i"]; N3[label="local mut _x"]; N4[label="(dummy_node)"]; - N5[label="expr loop { _x -= 1; }"]; - N6[label="expr 1"]; + N5[label="expr loop { _x -= 1i; }"]; + N6[label="expr 1i"]; N7[label="expr _x"]; - N8[label="expr _x -= 1"]; - N9[label="block { _x -= 1; }"]; + N8[label="expr _x -= 1i"]; + N9[label="block { _x -= 1i; }"]; N10[label="expr \"unreachable\""]; - N11[label="block { let mut _x = 11; loop { _x -= 1; } \"unreachable\"; }"]; + N11[label="block { let mut _x = 11i; loop { _x -= 1i; } \"unreachable\"; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f11.rs b/src/test/run-make/graphviz-flowgraph/f11.rs index d0f3452119e..95260c608ec 100644 --- a/src/test/run-make/graphviz-flowgraph/f11.rs +++ b/src/test/run-make/graphviz-flowgraph/f11.rs @@ -10,9 +10,9 @@ #[allow(unreachable_code)] pub fn expr_loop_11() { - let mut _x = 11; + let mut _x = 11i; loop { - _x -= 1; + _x -= 1i; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f12.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f12.dot-expected.dot index 9c0f25d5bec..ad257c19741 100644 --- a/src/test/run-make/graphviz-flowgraph/f12.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f12.dot-expected.dot @@ -1,23 +1,23 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 12"]; + N2[label="expr 12i"]; N3[label="local mut x"]; N4[label="(dummy_node)"]; - N5[label="expr loop { x -= 1; if x == 2 { break ; \"unreachable\"; } }"]; - N6[label="expr 1"]; + N5[label="expr loop { x -= 1i; if x == 2i { break ; \"unreachable\"; } }"]; + N6[label="expr 1i"]; N7[label="expr x"]; - N8[label="expr x -= 1"]; + N8[label="expr x -= 1i"]; N9[label="expr x"]; - N10[label="expr 2"]; - N11[label="expr x == 2"]; + N10[label="expr 2i"]; + N11[label="expr x == 2i"]; N12[label="expr break"]; N13[label="(dummy_node)"]; N14[label="expr \"unreachable\""]; N15[label="block { break ; \"unreachable\"; }"]; - N16[label="expr if x == 2 { break ; \"unreachable\"; }"]; - N17[label="block { x -= 1; if x == 2 { break ; \"unreachable\"; } }"]; - N18[label="block { let mut x = 12; loop { x -= 1; if x == 2 { break ; \"unreachable\"; } } }"]; + N16[label="expr if x == 2i { break ; \"unreachable\"; }"]; + N17[label="block { x -= 1i; if x == 2i { break ; \"unreachable\"; } }"]; + N18[label="block { let mut x = 12i; loop { x -= 1i; if x == 2i { break ; \"unreachable\"; } } }"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -28,7 +28,7 @@ digraph block { N9 -> N10; N10 -> N11; N11 -> N12; - N12 -> N5[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 2 { break ; \"unreachable\"; },\lexiting scope_4 block { x -= 1; if x == 2 { break ; \"unreachable\"; } }"]; + N12 -> N5[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 2i { break ; \"unreachable\"; },\lexiting scope_4 block { x -= 1i; if x == 2i { break ; \"unreachable\"; } }"]; N13 -> N14; N14 -> N15; N11 -> N16; diff --git a/src/test/run-make/graphviz-flowgraph/f12.rs b/src/test/run-make/graphviz-flowgraph/f12.rs index 90b146340b6..625dd8cb03e 100644 --- a/src/test/run-make/graphviz-flowgraph/f12.rs +++ b/src/test/run-make/graphviz-flowgraph/f12.rs @@ -10,9 +10,9 @@ #[allow(unreachable_code)] pub fn expr_loop_12() { - let mut x = 12; + let mut x = 12i; loop { - x -= 1; - if x == 2 { break; "unreachable"; } + x -= 1i; + if x == 2i { break; "unreachable"; } } } diff --git a/src/test/run-make/graphviz-flowgraph/f14.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f14.dot-expected.dot index 0fa4e9b44de..f8e4bd12bb0 100644 --- a/src/test/run-make/graphviz-flowgraph/f14.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f14.dot-expected.dot @@ -1,17 +1,17 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 14"]; + N2[label="expr 14i"]; N3[label="local x"]; N4[label="expr x"]; - N5[label="expr 1"]; - N6[label="expr x > 1"]; + N5[label="expr 1i"]; + N6[label="expr x > 1i"]; N7[label="expr return"]; N8[label="(dummy_node)"]; N9[label="expr \"unreachable\""]; N10[label="block { return; \"unreachable\"; }"]; - N11[label="expr if x > 1 { return; \"unreachable\"; }"]; - N12[label="block { let x = 14; if x > 1 { return; \"unreachable\"; } }"]; + N11[label="expr if x > 1i { return; \"unreachable\"; }"]; + N12[label="block { let x = 14i; if x > 1i { return; \"unreachable\"; } }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f14.rs b/src/test/run-make/graphviz-flowgraph/f14.rs index 98ff095c831..72616f31594 100644 --- a/src/test/run-make/graphviz-flowgraph/f14.rs +++ b/src/test/run-make/graphviz-flowgraph/f14.rs @@ -10,8 +10,8 @@ #[allow(unreachable_code)] pub fn expr_ret_14() { - let x = 14; - if x > 1 { + let x = 14i; + if x > 1i { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f15.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f15.dot-expected.dot index f0278fba311..bc47d9aff81 100644 --- a/src/test/run-make/graphviz-flowgraph/f15.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f15.dot-expected.dot @@ -1,42 +1,42 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 15"]; + N2[label="expr 15i"]; N3[label="local mut x"]; - N4[label="expr 151"]; + N4[label="expr 151i"]; N5[label="local mut y"]; N6[label="(dummy_node)"]; - N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l y -= 4;\l x -= 5;\l }\l"]; + N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l y -= 4i;\l x -= 5i;\l }\l"]; N8[label="(dummy_node)"]; - N9[label="expr \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l"]; + N9[label="expr \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l"]; N10[label="expr x"]; - N11[label="expr 1"]; - N12[label="expr x == 1"]; + N11[label="expr 1i"]; + N12[label="expr x == 1i"]; N13[label="expr break \'outer"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { break \'outer ; \"unreachable\" }"]; - N17[label="expr if x == 1 { break \'outer ; \"unreachable\" }"]; + N17[label="expr if x == 1i { break \'outer ; \"unreachable\" }"]; N18[label="expr y"]; - N19[label="expr 2"]; - N20[label="expr y >= 2"]; + N19[label="expr 2i"]; + N20[label="expr y >= 2i"]; N21[label="expr break"]; N22[label="(dummy_node)"]; N23[label="expr \"unreachable\""]; N24[label="block { break ; \"unreachable\" }"]; - N25[label="expr if y >= 2 { break ; \"unreachable\" }"]; - N26[label="expr 3"]; + N25[label="expr if y >= 2i { break ; \"unreachable\" }"]; + N26[label="expr 3i"]; N27[label="expr y"]; - N28[label="expr y -= 3"]; - N29[label="block {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l}\l"]; - N30[label="expr 4"]; + N28[label="expr y -= 3i"]; + N29[label="block {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l}\l"]; + N30[label="expr 4i"]; N31[label="expr y"]; - N32[label="expr y -= 4"]; - N33[label="expr 5"]; + N32[label="expr y -= 4i"]; + N33[label="expr 5i"]; N34[label="expr x"]; - N35[label="expr x -= 5"]; - N36[label="block {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l y -= 4;\l x -= 5;\l}\l"]; - N37[label="block {\l let mut x = 15;\l let mut y = 151;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l y -= 4;\l x -= 5;\l }\l}\l"]; + N35[label="expr x -= 5i"]; + N36[label="block {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l y -= 4i;\l x -= 5i;\l}\l"]; + N37[label="block {\l let mut x = 15i;\l let mut y = 151i;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l y -= 4i;\l x -= 5i;\l }\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -47,7 +47,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N7[label="exiting scope_0 expr break \'outer,\lexiting scope_1 stmt break \'outer ;,\lexiting scope_2 block { break \'outer ; \"unreachable\" },\lexiting scope_3 expr if x == 1 { break \'outer ; \"unreachable\" },\lexiting scope_4 stmt if x == 1 { break \'outer ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l }\l y -= 4;\l x -= 5;\l}\l"]; + N13 -> N7[label="exiting scope_0 expr break \'outer,\lexiting scope_1 stmt break \'outer ;,\lexiting scope_2 block { break \'outer ; \"unreachable\" },\lexiting scope_3 expr if x == 1i { break \'outer ; \"unreachable\" },\lexiting scope_4 stmt if x == 1i { break \'outer ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l }\l y -= 4i;\l x -= 5i;\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -56,7 +56,7 @@ digraph block { N18 -> N19; N19 -> N20; N20 -> N21; - N21 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\" },\lexiting scope_3 expr if y >= 2 { break ; \"unreachable\" },\lexiting scope_4 stmt if y >= 2 { break ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1 { break \'outer ; \"unreachable\" }\l if y >= 2 { break ; \"unreachable\" }\l y -= 3;\l}\l"]; + N21 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\" },\lexiting scope_3 expr if y >= 2i { break ; \"unreachable\" },\lexiting scope_4 stmt if y >= 2i { break ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1i { break \'outer ; \"unreachable\" }\l if y >= 2i { break ; \"unreachable\" }\l y -= 3i;\l}\l"]; N22 -> N23; N23 -> N24; N20 -> N25; diff --git a/src/test/run-make/graphviz-flowgraph/f15.rs b/src/test/run-make/graphviz-flowgraph/f15.rs index 44c038d643b..e5ca1de3f2d 100644 --- a/src/test/run-make/graphviz-flowgraph/f15.rs +++ b/src/test/run-make/graphviz-flowgraph/f15.rs @@ -10,21 +10,21 @@ #[allow(unreachable_code)] pub fn expr_break_label_15() { - let mut x = 15; - let mut y = 151; + let mut x = 15i; + let mut y = 151i; 'outer: loop { 'inner: loop { - if x == 1 { + if x == 1i { break 'outer; "unreachable" } - if y >= 2 { + if y >= 2i { break; "unreachable" } - y -= 3; + y -= 3i; } - y -= 4; - x -= 5; + y -= 4i; + x -= 5i; } } diff --git a/src/test/run-make/graphviz-flowgraph/f16.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f16.dot-expected.dot index 3f999ae3781..9c60e19f8b0 100644 --- a/src/test/run-make/graphviz-flowgraph/f16.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f16.dot-expected.dot @@ -1,43 +1,43 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 16"]; + N2[label="expr 16i"]; N3[label="local mut x"]; - N4[label="expr 16"]; + N4[label="expr 16i"]; N5[label="local mut y"]; N6[label="(dummy_node)"]; - N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l y -= 1;\l x -= 1;\l }\l"]; + N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l y -= 1i;\l x -= 1i;\l }\l"]; N8[label="(dummy_node)"]; - N9[label="expr \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l"]; + N9[label="expr \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l"]; N10[label="expr x"]; - N11[label="expr 1"]; - N12[label="expr x == 1"]; + N11[label="expr 1i"]; + N12[label="expr x == 1i"]; N13[label="expr continue \'outer"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { continue \'outer ; \"unreachable\" }"]; - N17[label="expr if x == 1 { continue \'outer ; \"unreachable\" }"]; + N17[label="expr if x == 1i { continue \'outer ; \"unreachable\" }"]; N18[label="expr y"]; - N19[label="expr 1"]; - N20[label="expr y >= 1"]; + N19[label="expr 1i"]; + N20[label="expr y >= 1i"]; N21[label="expr break"]; N22[label="(dummy_node)"]; N23[label="expr \"unreachable\""]; N24[label="block { break ; \"unreachable\" }"]; - N25[label="expr if y >= 1 { break ; \"unreachable\" }"]; - N26[label="expr 1"]; + N25[label="expr if y >= 1i { break ; \"unreachable\" }"]; + N26[label="expr 1i"]; N27[label="expr y"]; - N28[label="expr y -= 1"]; - N29[label="block {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l}\l"]; - N30[label="expr 1"]; + N28[label="expr y -= 1i"]; + N29[label="block {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l}\l"]; + N30[label="expr 1i"]; N31[label="expr y"]; - N32[label="expr y -= 1"]; - N33[label="expr 1"]; + N32[label="expr y -= 1i"]; + N33[label="expr 1i"]; N34[label="expr x"]; - N35[label="expr x -= 1"]; - N36[label="block {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l y -= 1;\l x -= 1;\l}\l"]; + N35[label="expr x -= 1i"]; + N36[label="block {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l y -= 1i;\l x -= 1i;\l}\l"]; N37[label="expr \"unreachable\""]; - N38[label="block {\l let mut x = 16;\l let mut y = 16;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l y -= 1;\l x -= 1;\l }\l \"unreachable\";\l}\l"]; + N38[label="block {\l let mut x = 16i;\l let mut y = 16i;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l y -= 1i;\l x -= 1i;\l }\l \"unreachable\";\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -48,7 +48,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N6[label="exiting scope_0 expr continue \'outer,\lexiting scope_1 stmt continue \'outer ;,\lexiting scope_2 block { continue \'outer ; \"unreachable\" },\lexiting scope_3 expr if x == 1 { continue \'outer ; \"unreachable\" },\lexiting scope_4 stmt if x == 1 { continue \'outer ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l }\l y -= 1;\l x -= 1;\l}\l"]; + N13 -> N6[label="exiting scope_0 expr continue \'outer,\lexiting scope_1 stmt continue \'outer ;,\lexiting scope_2 block { continue \'outer ; \"unreachable\" },\lexiting scope_3 expr if x == 1i { continue \'outer ; \"unreachable\" },\lexiting scope_4 stmt if x == 1i { continue \'outer ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l }\l y -= 1i;\l x -= 1i;\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -57,7 +57,7 @@ digraph block { N18 -> N19; N19 -> N20; N20 -> N21; - N21 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\" },\lexiting scope_3 expr if y >= 1 { break ; \"unreachable\" },\lexiting scope_4 stmt if y >= 1 { break ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1 { continue \'outer ; \"unreachable\" }\l if y >= 1 { break ; \"unreachable\" }\l y -= 1;\l}\l"]; + N21 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\" },\lexiting scope_3 expr if y >= 1i { break ; \"unreachable\" },\lexiting scope_4 stmt if y >= 1i { break ; \"unreachable\" },\lexiting scope_5 block {\l if x == 1i { continue \'outer ; \"unreachable\" }\l if y >= 1i { break ; \"unreachable\" }\l y -= 1i;\l}\l"]; N22 -> N23; N23 -> N24; N20 -> N25; diff --git a/src/test/run-make/graphviz-flowgraph/f16.rs b/src/test/run-make/graphviz-flowgraph/f16.rs index f4f23a65c93..78de99d28fc 100644 --- a/src/test/run-make/graphviz-flowgraph/f16.rs +++ b/src/test/run-make/graphviz-flowgraph/f16.rs @@ -10,22 +10,22 @@ #[allow(unreachable_code)] pub fn expr_continue_label_16() { - let mut x = 16; - let mut y = 16; + let mut x = 16i; + let mut y = 16i; 'outer: loop { 'inner: loop { - if x == 1 { + if x == 1i { continue 'outer; "unreachable" } - if y >= 1 { + if y >= 1i { break; "unreachable" } - y -= 1; + y -= 1i; } - y -= 1; - x -= 1; + y -= 1i; + x -= 1i; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f17.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f17.dot-expected.dot index e9bccdab81b..d3e098a71f2 100644 --- a/src/test/run-make/graphviz-flowgraph/f17.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f17.dot-expected.dot @@ -1,12 +1,12 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 1"]; - N3[label="expr 7"]; - N4[label="expr 17"]; - N5[label="expr [1, 7, 17]"]; + N2[label="expr 1i"]; + N3[label="expr 7i"]; + N4[label="expr 17i"]; + N5[label="expr [1i, 7i, 17i]"]; N6[label="local _v"]; - N7[label="block { let _v = [1, 7, 17]; }"]; + N7[label="block { let _v = [1i, 7i, 17i]; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f17.rs b/src/test/run-make/graphviz-flowgraph/f17.rs index 23f5bb8a1eb..23ce212c0af 100644 --- a/src/test/run-make/graphviz-flowgraph/f17.rs +++ b/src/test/run-make/graphviz-flowgraph/f17.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn expr_vec_17() { - let _v = [1, 7, 17]; + let _v = [1i, 7i, 17i]; } diff --git a/src/test/run-make/graphviz-flowgraph/f20.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f20.dot-expected.dot index 593ad6f91ea..716ec469fb0 100644 --- a/src/test/run-make/graphviz-flowgraph/f20.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f20.dot-expected.dot @@ -1,15 +1,15 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 2"]; - N3[label="expr 0"]; - N4[label="expr 20"]; - N5[label="expr [2, 0, 20]"]; + N2[label="expr 2u"]; + N3[label="expr 0u"]; + N4[label="expr 20u"]; + N5[label="expr [2u, 0u, 20u]"]; N6[label="local v"]; N7[label="expr v"]; - N8[label="expr 20"]; - N9[label="expr v[20]"]; - N10[label="block { let v = [2, 0, 20]; v[20]; }"]; + N8[label="expr 20u"]; + N9[label="expr v[20u]"]; + N10[label="block { let v = [2u, 0u, 20u]; v[20u]; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f20.rs b/src/test/run-make/graphviz-flowgraph/f20.rs index d7349932355..7110ebe2b54 100644 --- a/src/test/run-make/graphviz-flowgraph/f20.rs +++ b/src/test/run-make/graphviz-flowgraph/f20.rs @@ -9,6 +9,6 @@ // except according to those terms. pub fn expr_index_20() { - let v = [2, 0, 20]; - v[20]; + let v = [2u, 0u, 20u]; + v[20u]; } diff --git a/src/test/run-make/graphviz-flowgraph/f21.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f21.dot-expected.dot index 0798c4a01c0..2bbc3e7e5c8 100644 --- a/src/test/run-make/graphviz-flowgraph/f21.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f21.dot-expected.dot @@ -1,40 +1,40 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 15"]; + N2[label="expr 15i"]; N3[label="local mut x"]; - N4[label="expr 151"]; + N4[label="expr 151i"]; N5[label="local mut y"]; N6[label="(dummy_node)"]; - N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l \"unreachable\";\l }\l"]; + N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l \"unreachable\";\l }\l"]; N8[label="(dummy_node)"]; - N9[label="expr \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l"]; + N9[label="expr \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l"]; N10[label="expr x"]; - N11[label="expr 1"]; - N12[label="expr x == 1"]; + N11[label="expr 1i"]; + N12[label="expr x == 1i"]; N13[label="expr break \'outer"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { break \'outer ; \"unreachable\"; }"]; - N17[label="expr if x == 1 { break \'outer ; \"unreachable\"; }"]; + N17[label="expr if x == 1i { break \'outer ; \"unreachable\"; }"]; N18[label="expr y"]; - N19[label="expr 2"]; - N20[label="expr y >= 2"]; + N19[label="expr 2i"]; + N20[label="expr y >= 2i"]; N21[label="expr return"]; N22[label="(dummy_node)"]; N23[label="expr \"unreachable\""]; N24[label="block { return; \"unreachable\"; }"]; - N25[label="expr if y >= 2 { return; \"unreachable\"; }"]; - N26[label="expr 3"]; + N25[label="expr if y >= 2i { return; \"unreachable\"; }"]; + N26[label="expr 3i"]; N27[label="expr y"]; - N28[label="expr y -= 3"]; - N29[label="expr 5"]; + N28[label="expr y -= 3i"]; + N29[label="expr 5i"]; N30[label="expr x"]; - N31[label="expr x -= 5"]; - N32[label="block {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l}\l"]; + N31[label="expr x -= 5i"]; + N32[label="block {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l}\l"]; N33[label="expr \"unreachable\""]; - N34[label="block {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l \"unreachable\";\l}\l"]; - N35[label="block {\l let mut x = 15;\l let mut y = 151;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l \"unreachable\";\l }\l}\l"]; + N34[label="block {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l \"unreachable\";\l}\l"]; + N35[label="block {\l let mut x = 15i;\l let mut y = 151i;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l \"unreachable\";\l }\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -45,7 +45,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N7[label="exiting scope_0 expr break \'outer,\lexiting scope_1 stmt break \'outer ;,\lexiting scope_2 block { break \'outer ; \"unreachable\"; },\lexiting scope_3 expr if x == 1 { break \'outer ; \"unreachable\"; },\lexiting scope_4 stmt if x == 1 { break \'outer ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l \"unreachable\";\l}\l"]; + N13 -> N7[label="exiting scope_0 expr break \'outer,\lexiting scope_1 stmt break \'outer ;,\lexiting scope_2 block { break \'outer ; \"unreachable\"; },\lexiting scope_3 expr if x == 1i { break \'outer ; \"unreachable\"; },\lexiting scope_4 stmt if x == 1i { break \'outer ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l \"unreachable\";\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -54,7 +54,7 @@ digraph block { N18 -> N19; N19 -> N20; N20 -> N21; - N21 -> N1[label="exiting scope_0 expr \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l,\lexiting scope_1 expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { break \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l y -= 3;\l x -= 5;\l }\l \"unreachable\";\l }\l"]; + N21 -> N1[label="exiting scope_0 expr \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l,\lexiting scope_1 expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { break \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l y -= 3i;\l x -= 5i;\l }\l \"unreachable\";\l }\l"]; N22 -> N23; N23 -> N24; N20 -> N25; diff --git a/src/test/run-make/graphviz-flowgraph/f21.rs b/src/test/run-make/graphviz-flowgraph/f21.rs index 70083ed8312..bff2da25061 100644 --- a/src/test/run-make/graphviz-flowgraph/f21.rs +++ b/src/test/run-make/graphviz-flowgraph/f21.rs @@ -10,20 +10,20 @@ #[allow(unreachable_code)] pub fn expr_break_label_21() { - let mut x = 15; - let mut y = 151; + let mut x = 15i; + let mut y = 151i; 'outer: loop { 'inner: loop { - if x == 1 { + if x == 1i { break 'outer; "unreachable"; } - if y >= 2 { + if y >= 2i { return; "unreachable"; } - y -= 3; - x -= 5; + y -= 3i; + x -= 5i; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f22.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f22.dot-expected.dot index 9ad731bc756..8ecddba21fc 100644 --- a/src/test/run-make/graphviz-flowgraph/f22.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f22.dot-expected.dot @@ -1,41 +1,41 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 15"]; + N2[label="expr 15i"]; N3[label="local mut x"]; - N4[label="expr 151"]; + N4[label="expr 151i"]; N5[label="local mut y"]; N6[label="(dummy_node)"]; - N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l \"unreachable\";\l }\l"]; + N7[label="expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l \"unreachable\";\l }\l"]; N8[label="(dummy_node)"]; - N9[label="expr \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l"]; + N9[label="expr \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l"]; N10[label="expr x"]; - N11[label="expr 1"]; - N12[label="expr x == 1"]; + N11[label="expr 1i"]; + N12[label="expr x == 1i"]; N13[label="expr continue \'outer"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { continue \'outer ; \"unreachable\"; }"]; - N17[label="expr if x == 1 { continue \'outer ; \"unreachable\"; }"]; + N17[label="expr if x == 1i { continue \'outer ; \"unreachable\"; }"]; N18[label="expr y"]; - N19[label="expr 2"]; - N20[label="expr y >= 2"]; + N19[label="expr 2i"]; + N20[label="expr y >= 2i"]; N21[label="expr return"]; N22[label="(dummy_node)"]; N23[label="expr \"unreachable\""]; N24[label="block { return; \"unreachable\"; }"]; - N25[label="expr if y >= 2 { return; \"unreachable\"; }"]; - N26[label="expr 1"]; + N25[label="expr if y >= 2i { return; \"unreachable\"; }"]; + N26[label="expr 1i"]; N27[label="expr x"]; - N28[label="expr x -= 1"]; - N29[label="expr 3"]; + N28[label="expr x -= 1i"]; + N29[label="expr 3i"]; N30[label="expr y"]; - N31[label="expr y -= 3"]; - N32[label="block {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l}\l"]; + N31[label="expr y -= 3i"]; + N32[label="block {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l}\l"]; N33[label="expr \"unreachable\""]; - N34[label="block {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l \"unreachable\";\l}\l"]; + N34[label="block {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l \"unreachable\";\l}\l"]; N35[label="expr \"unreachable\""]; - N36[label="block {\l let mut x = 15;\l let mut y = 151;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l \"unreachable\";\l }\l \"unreachable\";\l}\l"]; + N36[label="block {\l let mut x = 15i;\l let mut y = 151i;\l \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l \"unreachable\";\l }\l \"unreachable\";\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -46,7 +46,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N6[label="exiting scope_0 expr continue \'outer,\lexiting scope_1 stmt continue \'outer ;,\lexiting scope_2 block { continue \'outer ; \"unreachable\"; },\lexiting scope_3 expr if x == 1 { continue \'outer ; \"unreachable\"; },\lexiting scope_4 stmt if x == 1 { continue \'outer ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l \"unreachable\";\l}\l"]; + N13 -> N6[label="exiting scope_0 expr continue \'outer,\lexiting scope_1 stmt continue \'outer ;,\lexiting scope_2 block { continue \'outer ; \"unreachable\"; },\lexiting scope_3 expr if x == 1i { continue \'outer ; \"unreachable\"; },\lexiting scope_4 stmt if x == 1i { continue \'outer ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l}\l,\lexiting scope_6 expr \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l,\lexiting scope_7 stmt \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l,\lexiting scope_8 block {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l \"unreachable\";\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -55,7 +55,7 @@ digraph block { N18 -> N19; N19 -> N20; N20 -> N21; - N21 -> N1[label="exiting scope_0 expr \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l,\lexiting scope_1 expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1 { continue \'outer ; \"unreachable\"; }\l if y >= 2 { return; \"unreachable\"; }\l x -= 1;\l y -= 3;\l }\l \"unreachable\";\l }\l"]; + N21 -> N1[label="exiting scope_0 expr \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l,\lexiting scope_1 expr \'outer:\l loop {\l \'inner:\l loop {\l if x == 1i { continue \'outer ; \"unreachable\"; }\l if y >= 2i { return; \"unreachable\"; }\l x -= 1i;\l y -= 3i;\l }\l \"unreachable\";\l }\l"]; N22 -> N23; N23 -> N24; N20 -> N25; diff --git a/src/test/run-make/graphviz-flowgraph/f22.rs b/src/test/run-make/graphviz-flowgraph/f22.rs index b35aac9ec42..a6e3d571deb 100644 --- a/src/test/run-make/graphviz-flowgraph/f22.rs +++ b/src/test/run-make/graphviz-flowgraph/f22.rs @@ -10,20 +10,20 @@ #[allow(unreachable_code)] pub fn expr_break_label_21() { - let mut x = 15; - let mut y = 151; + let mut x = 15i; + let mut y = 151i; 'outer: loop { 'inner: loop { - if x == 1 { + if x == 1i { continue 'outer; "unreachable"; } - if y >= 2 { + if y >= 2i { return; "unreachable"; } - x -= 1; - y -= 3; + x -= 1i; + y -= 3i; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f23.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f23.dot-expected.dot index 876957a0689..718d4687ef9 100644 --- a/src/test/run-make/graphviz-flowgraph/f23.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f23.dot-expected.dot @@ -1,48 +1,48 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 23"]; + N2[label="expr 23i"]; N3[label="local mut x"]; - N4[label="expr 23"]; + N4[label="expr 23i"]; N5[label="local mut y"]; - N6[label="expr 23"]; + N6[label="expr 23i"]; N7[label="local mut z"]; N8[label="(dummy_node)"]; N9[label="expr x"]; - N10[label="expr 0"]; - N11[label="expr x > 0"]; - N12[label="expr while x > 0 {\l x -= 1;\l while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; - N13[label="expr 1"]; + N10[label="expr 0i"]; + N11[label="expr x > 0i"]; + N12[label="expr while x > 0i {\l x -= 1i;\l while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; + N13[label="expr 1i"]; N14[label="expr x"]; - N15[label="expr x -= 1"]; + N15[label="expr x -= 1i"]; N16[label="(dummy_node)"]; N17[label="expr y"]; - N18[label="expr 0"]; - N19[label="expr y > 0"]; - N20[label="expr while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l"]; - N21[label="expr 1"]; + N18[label="expr 0i"]; + N19[label="expr y > 0i"]; + N20[label="expr while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l"]; + N21[label="expr 1i"]; N22[label="expr y"]; - N23[label="expr y -= 1"]; + N23[label="expr y -= 1i"]; N24[label="(dummy_node)"]; N25[label="expr z"]; - N26[label="expr 0"]; - N27[label="expr z > 0"]; - N28[label="expr while z > 0 { z -= 1; }"]; - N29[label="expr 1"]; + N26[label="expr 0i"]; + N27[label="expr z > 0i"]; + N28[label="expr while z > 0i { z -= 1i; }"]; + N29[label="expr 1i"]; N30[label="expr z"]; - N31[label="expr z -= 1"]; - N32[label="block { z -= 1; }"]; + N31[label="expr z -= 1i"]; + N32[label="block { z -= 1i; }"]; N33[label="expr x"]; - N34[label="expr 10"]; - N35[label="expr x > 10"]; + N34[label="expr 10i"]; + N35[label="expr x > 10i"]; N36[label="expr return"]; N37[label="(dummy_node)"]; N38[label="expr \"unreachable\""]; N39[label="block { return; \"unreachable\"; }"]; - N40[label="expr if x > 10 { return; \"unreachable\"; }"]; - N41[label="block { y -= 1; while z > 0 { z -= 1; } if x > 10 { return; \"unreachable\"; } }"]; - N42[label="block {\l x -= 1;\l while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; - N43[label="block {\l let mut x = 23;\l let mut y = 23;\l let mut z = 23;\l while x > 0 {\l x -= 1;\l while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l }\l}\l"]; + N40[label="expr if x > 10i { return; \"unreachable\"; }"]; + N41[label="block { y -= 1i; while z > 0i { z -= 1i; } if x > 10i { return; \"unreachable\"; } }"]; + N42[label="block {\l x -= 1i;\l while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; + N43[label="block {\l let mut x = 23i;\l let mut y = 23i;\l let mut z = 23i;\l while x > 0i {\l x -= 1i;\l while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l }\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -79,7 +79,7 @@ digraph block { N33 -> N34; N34 -> N35; N35 -> N36; - N36 -> N1[label="exiting scope_0 expr while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l,\lexiting scope_1 expr while x > 0 {\l x -= 1;\l while y > 0 {\l y -= 1;\l while z > 0 { z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; + N36 -> N1[label="exiting scope_0 expr while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l,\lexiting scope_1 expr while x > 0i {\l x -= 1i;\l while y > 0i {\l y -= 1i;\l while z > 0i { z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; N37 -> N38; N38 -> N39; N35 -> N40; diff --git a/src/test/run-make/graphviz-flowgraph/f23.rs b/src/test/run-make/graphviz-flowgraph/f23.rs index 52341a3fbd4..73bcc288ca7 100644 --- a/src/test/run-make/graphviz-flowgraph/f23.rs +++ b/src/test/run-make/graphviz-flowgraph/f23.rs @@ -10,19 +10,19 @@ #[allow(unreachable_code)] pub fn expr_while_23() { - let mut x = 23; - let mut y = 23; - let mut z = 23; + let mut x = 23i; + let mut y = 23i; + let mut z = 23i; - while x > 0 { - x -= 1; + while x > 0i { + x -= 1i; - while y > 0 { - y -= 1; + while y > 0i { + y -= 1i; - while z > 0 { z -= 1; } + while z > 0i { z -= 1i; } - if x > 10 { + if x > 10i { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f24.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f24.dot-expected.dot index 2558998be6e..646d98a54a7 100644 --- a/src/test/run-make/graphviz-flowgraph/f24.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f24.dot-expected.dot @@ -1,63 +1,63 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 24"]; + N2[label="expr 24i"]; N3[label="local mut x"]; - N4[label="expr 24"]; + N4[label="expr 24i"]; N5[label="local mut y"]; - N6[label="expr 24"]; + N6[label="expr 24i"]; N7[label="local mut z"]; N8[label="(dummy_node)"]; - N9[label="expr loop {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; + N9[label="expr loop {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; N10[label="expr x"]; - N11[label="expr 0"]; - N12[label="expr x == 0"]; + N11[label="expr 0i"]; + N12[label="expr x == 0i"]; N13[label="expr break"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { break ; \"unreachable\"; }"]; - N17[label="expr if x == 0 { break ; \"unreachable\"; }"]; - N18[label="expr 1"]; + N17[label="expr if x == 0i { break ; \"unreachable\"; }"]; + N18[label="expr 1i"]; N19[label="expr x"]; - N20[label="expr x -= 1"]; + N20[label="expr x -= 1i"]; N21[label="(dummy_node)"]; - N22[label="expr loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l"]; + N22[label="expr loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l"]; N23[label="expr y"]; - N24[label="expr 0"]; - N25[label="expr y == 0"]; + N24[label="expr 0i"]; + N25[label="expr y == 0i"]; N26[label="expr break"]; N27[label="(dummy_node)"]; N28[label="expr \"unreachable\""]; N29[label="block { break ; \"unreachable\"; }"]; - N30[label="expr if y == 0 { break ; \"unreachable\"; }"]; - N31[label="expr 1"]; + N30[label="expr if y == 0i { break ; \"unreachable\"; }"]; + N31[label="expr 1i"]; N32[label="expr y"]; - N33[label="expr y -= 1"]; + N33[label="expr y -= 1i"]; N34[label="(dummy_node)"]; - N35[label="expr loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N35[label="expr loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N36[label="expr z"]; - N37[label="expr 0"]; - N38[label="expr z == 0"]; + N37[label="expr 0i"]; + N38[label="expr z == 0i"]; N39[label="expr break"]; N40[label="(dummy_node)"]; N41[label="expr \"unreachable\""]; N42[label="block { break ; \"unreachable\"; }"]; - N43[label="expr if z == 0 { break ; \"unreachable\"; }"]; - N44[label="expr 1"]; + N43[label="expr if z == 0i { break ; \"unreachable\"; }"]; + N44[label="expr 1i"]; N45[label="expr z"]; - N46[label="expr z -= 1"]; - N47[label="block { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N46[label="expr z -= 1i"]; + N47[label="block { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N48[label="expr x"]; - N49[label="expr 10"]; - N50[label="expr x > 10"]; + N49[label="expr 10i"]; + N50[label="expr x > 10i"]; N51[label="expr return"]; N52[label="(dummy_node)"]; N53[label="expr \"unreachable\""]; N54[label="block { return; \"unreachable\"; }"]; - N55[label="expr if x > 10 { return; \"unreachable\"; }"]; - N56[label="block {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l"]; - N57[label="block {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; - N58[label="block {\l let mut x = 24;\l let mut y = 24;\l let mut z = 24;\l loop {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l }\l}\l"]; + N55[label="expr if x > 10i { return; \"unreachable\"; }"]; + N56[label="block {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l"]; + N57[label="block {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; + N58[label="block {\l let mut x = 24i;\l let mut y = 24i;\l let mut z = 24i;\l loop {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l }\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -69,7 +69,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if x == 0 { break ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; + N13 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if x == 0i { break ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -82,7 +82,7 @@ digraph block { N23 -> N24; N24 -> N25; N25 -> N26; - N26 -> N22[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if y == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if y == 0 { break ; \"unreachable\"; },\lexiting scope_5 block {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l"]; + N26 -> N22[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if y == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if y == 0i { break ; \"unreachable\"; },\lexiting scope_5 block {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l"]; N27 -> N28; N28 -> N29; N25 -> N30; @@ -95,7 +95,7 @@ digraph block { N36 -> N37; N37 -> N38; N38 -> N39; - N39 -> N35[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if z == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if z == 0 { break ; \"unreachable\"; },\lexiting scope_5 block { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N39 -> N35[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if z == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if z == 0i { break ; \"unreachable\"; },\lexiting scope_5 block { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N40 -> N41; N41 -> N42; N38 -> N43; @@ -109,7 +109,7 @@ digraph block { N48 -> N49; N49 -> N50; N50 -> N51; - N51 -> N1[label="exiting scope_0 expr loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l}\l,\lexiting scope_1 expr loop {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { return; \"unreachable\"; }\l }\l}\l"]; + N51 -> N1[label="exiting scope_0 expr loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l}\l,\lexiting scope_1 expr loop {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { return; \"unreachable\"; }\l }\l}\l"]; N52 -> N53; N53 -> N54; N50 -> N55; diff --git a/src/test/run-make/graphviz-flowgraph/f24.rs b/src/test/run-make/graphviz-flowgraph/f24.rs index f796d660a18..afba1d202c9 100644 --- a/src/test/run-make/graphviz-flowgraph/f24.rs +++ b/src/test/run-make/graphviz-flowgraph/f24.rs @@ -10,24 +10,24 @@ #[allow(unreachable_code)] pub fn expr_while_24() { - let mut x = 24; - let mut y = 24; - let mut z = 24; + let mut x = 24i; + let mut y = 24i; + let mut z = 24i; loop { - if x == 0 { break; "unreachable"; } - x -= 1; + if x == 0i { break; "unreachable"; } + x -= 1i; loop { - if y == 0 { break; "unreachable"; } - y -= 1; + if y == 0i { break; "unreachable"; } + y -= 1i; loop { - if z == 0 { break; "unreachable"; } - z -= 1; + if z == 0i { break; "unreachable"; } + z -= 1i; } - if x > 10 { + if x > 10i { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f25.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f25.dot-expected.dot index c393b63546c..11b9c7ef05e 100644 --- a/src/test/run-make/graphviz-flowgraph/f25.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f25.dot-expected.dot @@ -1,63 +1,63 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="expr 25"]; + N2[label="expr 25i"]; N3[label="local mut x"]; - N4[label="expr 25"]; + N4[label="expr 25i"]; N5[label="local mut y"]; - N6[label="expr 25"]; + N6[label="expr 25i"]; N7[label="local mut z"]; N8[label="(dummy_node)"]; - N9[label="expr \'a:\l loop {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l \'a:\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l }\l }\l"]; + N9[label="expr \'a:\l loop {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l \'a:\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l }\l }\l"]; N10[label="expr x"]; - N11[label="expr 0"]; - N12[label="expr x == 0"]; + N11[label="expr 0i"]; + N12[label="expr x == 0i"]; N13[label="expr break"]; N14[label="(dummy_node)"]; N15[label="expr \"unreachable\""]; N16[label="block { break ; \"unreachable\"; }"]; - N17[label="expr if x == 0 { break ; \"unreachable\"; }"]; - N18[label="expr 1"]; + N17[label="expr if x == 0i { break ; \"unreachable\"; }"]; + N18[label="expr 1i"]; N19[label="expr x"]; - N20[label="expr x -= 1"]; + N20[label="expr x -= 1i"]; N21[label="(dummy_node)"]; - N22[label="expr \'a:\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l }\l"]; + N22[label="expr \'a:\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l }\l"]; N23[label="expr y"]; - N24[label="expr 0"]; - N25[label="expr y == 0"]; + N24[label="expr 0i"]; + N25[label="expr y == 0i"]; N26[label="expr break"]; N27[label="(dummy_node)"]; N28[label="expr \"unreachable\""]; N29[label="block { break ; \"unreachable\"; }"]; - N30[label="expr if y == 0 { break ; \"unreachable\"; }"]; - N31[label="expr 1"]; + N30[label="expr if y == 0i { break ; \"unreachable\"; }"]; + N31[label="expr 1i"]; N32[label="expr y"]; - N33[label="expr y -= 1"]; + N33[label="expr y -= 1i"]; N34[label="(dummy_node)"]; - N35[label="expr \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N35[label="expr \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N36[label="expr z"]; - N37[label="expr 0"]; - N38[label="expr z == 0"]; + N37[label="expr 0i"]; + N38[label="expr z == 0i"]; N39[label="expr break"]; N40[label="(dummy_node)"]; N41[label="expr \"unreachable\""]; N42[label="block { break ; \"unreachable\"; }"]; - N43[label="expr if z == 0 { break ; \"unreachable\"; }"]; - N44[label="expr 1"]; + N43[label="expr if z == 0i { break ; \"unreachable\"; }"]; + N44[label="expr 1i"]; N45[label="expr z"]; - N46[label="expr z -= 1"]; - N47[label="block { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N46[label="expr z -= 1i"]; + N47[label="block { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N48[label="expr x"]; - N49[label="expr 10"]; - N50[label="expr x > 10"]; + N49[label="expr 10i"]; + N50[label="expr x > 10i"]; N51[label="expr continue \'a"]; N52[label="(dummy_node)"]; N53[label="expr \"unreachable\""]; N54[label="block { continue \'a ; \"unreachable\"; }"]; - N55[label="expr if x > 10 { continue \'a ; \"unreachable\"; }"]; - N56[label="block {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l}\l"]; - N57[label="block {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l \'a:\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l }\l}\l"]; - N58[label="block {\l let mut x = 25;\l let mut y = 25;\l let mut z = 25;\l \'a:\l loop {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l \'a:\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l }\l }\l}\l"]; + N55[label="expr if x > 10i { continue \'a ; \"unreachable\"; }"]; + N56[label="block {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l}\l"]; + N57[label="block {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l \'a:\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l }\l}\l"]; + N58[label="block {\l let mut x = 25i;\l let mut y = 25i;\l let mut z = 25i;\l \'a:\l loop {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l \'a:\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a:\l loop {\l if z == 0i { break ; \"unreachable\"; }\l z -= 1i;\l }\l if x > 10i { continue \'a ; \"unreachable\"; }\l }\l }\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; @@ -69,7 +69,7 @@ digraph block { N10 -> N11; N11 -> N12; N12 -> N13; - N13 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if x == 0 { break ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 0 { break ; \"unreachable\"; }\l x -= 1;\l \'a:\l loop {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l }\l}\l"]; + N13 -> N9[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if x == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if x == 0i { break ; \"unreachable\"; },\lexiting scope_5 block {\l if x == 0i { break ; \"unreachable\"; }\l x -= 1i;\l \'a:\l loop {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l }\l}\l"]; N14 -> N15; N15 -> N16; N12 -> N17; @@ -82,7 +82,7 @@ digraph block { N23 -> N24; N24 -> N25; N25 -> N26; - N26 -> N22[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if y == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if y == 0 { break ; \"unreachable\"; },\lexiting scope_5 block {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l}\l"]; + N26 -> N22[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if y == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if y == 0i { break ; \"unreachable\"; },\lexiting scope_5 block {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l}\l"]; N27 -> N28; N28 -> N29; N25 -> N30; @@ -95,7 +95,7 @@ digraph block { N36 -> N37; N37 -> N38; N38 -> N39; - N39 -> N35[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if z == 0 { break ; \"unreachable\"; },\lexiting scope_4 stmt if z == 0 { break ; \"unreachable\"; },\lexiting scope_5 block { if z == 0 { break ; \"unreachable\"; } z -= 1; }"]; + N39 -> N35[label="exiting scope_0 expr break,\lexiting scope_1 stmt break ;,\lexiting scope_2 block { break ; \"unreachable\"; },\lexiting scope_3 expr if z == 0i { break ; \"unreachable\"; },\lexiting scope_4 stmt if z == 0i { break ; \"unreachable\"; },\lexiting scope_5 block { if z == 0i { break ; \"unreachable\"; } z -= 1i; }"]; N40 -> N41; N41 -> N42; N38 -> N43; @@ -109,7 +109,7 @@ digraph block { N48 -> N49; N49 -> N50; N50 -> N51; - N51 -> N21[label="exiting scope_0 expr continue \'a,\lexiting scope_1 stmt continue \'a ;,\lexiting scope_2 block { continue \'a ; \"unreachable\"; },\lexiting scope_3 expr if x > 10 { continue \'a ; \"unreachable\"; },\lexiting scope_4 block {\l if y == 0 { break ; \"unreachable\"; }\l y -= 1;\l \'a: loop { if z == 0 { break ; \"unreachable\"; } z -= 1; }\l if x > 10 { continue \'a ; \"unreachable\"; }\l}\l"]; + N51 -> N21[label="exiting scope_0 expr continue \'a,\lexiting scope_1 stmt continue \'a ;,\lexiting scope_2 block { continue \'a ; \"unreachable\"; },\lexiting scope_3 expr if x > 10i { continue \'a ; \"unreachable\"; },\lexiting scope_4 block {\l if y == 0i { break ; \"unreachable\"; }\l y -= 1i;\l \'a: loop { if z == 0i { break ; \"unreachable\"; } z -= 1i; }\l if x > 10i { continue \'a ; \"unreachable\"; }\l}\l"]; N52 -> N53; N53 -> N54; N50 -> N55; diff --git a/src/test/run-make/graphviz-flowgraph/f25.rs b/src/test/run-make/graphviz-flowgraph/f25.rs index 2ee2e48fd10..933f95f228c 100644 --- a/src/test/run-make/graphviz-flowgraph/f25.rs +++ b/src/test/run-make/graphviz-flowgraph/f25.rs @@ -10,24 +10,24 @@ #[allow(unreachable_code)] pub fn expr_while_25() { - let mut x = 25; - let mut y = 25; - let mut z = 25; + let mut x = 25i; + let mut y = 25i; + let mut z = 25i; 'a: loop { - if x == 0 { break; "unreachable"; } - x -= 1; + if x == 0i { break; "unreachable"; } + x -= 1i; 'a: loop { - if y == 0 { break; "unreachable"; } - y -= 1; + if y == 0i { break; "unreachable"; } + y -= 1i; 'a: loop { - if z == 0 { break; "unreachable"; } - z -= 1; + if z == 0i { break; "unreachable"; } + z -= 1i; } - if x > 10 { + if x > 10i { continue 'a; "unreachable"; } diff --git a/src/test/run-make/static-unwinding/main.rs b/src/test/run-make/static-unwinding/main.rs index 08777490f21..9fe78cc2553 100644 --- a/src/test/run-make/static-unwinding/main.rs +++ b/src/test/run-make/static-unwinding/main.rs @@ -25,7 +25,7 @@ fn main() { task::try(proc() { let _a = A; lib::callback(|| fail!()); - 1 + 1i }); unsafe { diff --git a/src/test/run-pass/attr-start.rs b/src/test/run-pass/attr-start.rs index 35a0da4dcf3..3bea7e84807 100644 --- a/src/test/run-pass/attr-start.rs +++ b/src/test/run-pass/attr-start.rs @@ -10,6 +10,6 @@ #[start] -fn start(_argc: int, _argv: **u8) -> int { +fn start(_argc: int, _argv: *const *const u8) -> int { return 0; } diff --git a/src/test/run-pass/auto-instantiate.rs b/src/test/run-pass/auto-instantiate.rs index f1fe1e94587..5167764dd28 100644 --- a/src/test/run-pass/auto-instantiate.rs +++ b/src/test/run-pass/auto-instantiate.rs @@ -16,6 +16,6 @@ struct Triple { x: int, y: int, z: int } fn f<T,U>(x: T, y: U) -> Pair<T, U> { return Pair {a: x, b: y}; } pub fn main() { - println!("{:?}", f(Triple {x: 3, y: 4, z: 5}, 4).a.x); + println!("{:?}", f(Triple {x: 3, y: 4, z: 5}, 4i).a.x); println!("{:?}", f(5i, 6i).a); } diff --git a/src/test/run-pass/backtrace.rs b/src/test/run-pass/backtrace.rs index 3b74ec4add3..97862844030 100644 --- a/src/test/run-pass/backtrace.rs +++ b/src/test/run-pass/backtrace.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 // ignore-win32 FIXME #13259 extern crate native; @@ -18,7 +18,9 @@ use std::finally::Finally; use std::str; #[start] -fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, main) } +fn start(argc: int, argv: *const *const u8) -> int { + native::start(argc, argv, main) +} #[inline(never)] fn foo() { diff --git a/src/test/run-pass/binops.rs b/src/test/run-pass/binops.rs index ff4dcc18bb4..21824700860 100644 --- a/src/test/run-pass/binops.rs +++ b/src/test/run-pass/binops.rs @@ -52,9 +52,9 @@ fn test_box() { fn test_ptr() { unsafe { - let p1: *u8 = ::std::mem::transmute(0u); - let p2: *u8 = ::std::mem::transmute(0u); - let p3: *u8 = ::std::mem::transmute(1u); + let p1: *const u8 = ::std::mem::transmute(0u); + let p2: *const u8 = ::std::mem::transmute(0u); + let p3: *const u8 = ::std::mem::transmute(1u); assert_eq!(p1, p2); assert!(p1 != p3); @@ -86,8 +86,8 @@ fn test_class() { unsafe { println!("q = {:x}, r = {:x}", - (::std::mem::transmute::<*p, uint>(&q)), - (::std::mem::transmute::<*p, uint>(&r))); + (::std::mem::transmute::<*const p, uint>(&q)), + (::std::mem::transmute::<*const p, uint>(&r))); } assert_eq!(q, r); r.y = 17; diff --git a/src/test/run-pass/borrowck-borrow-from-expr-block.rs b/src/test/run-pass/borrowck-borrow-from-expr-block.rs index dd1224929c7..c9e1c2c8d42 100644 --- a/src/test/run-pass/borrowck-borrow-from-expr-block.rs +++ b/src/test/run-pass/borrowck-borrow-from-expr-block.rs @@ -18,8 +18,8 @@ fn borrow(x: &int, f: |x: &int|) { fn test1(x: Gc<Box<int>>) { borrow(&*(*x).clone(), |p| { - let x_a = &**x as *int; - assert!((x_a as uint) != (p as *int as uint)); + let x_a = &**x as *const int; + assert!((x_a as uint) != (p as *const int as uint)); assert_eq!(unsafe{*x_a}, *p); }) } diff --git a/src/test/run-pass/builtin-superkinds-self-type.rs b/src/test/run-pass/builtin-superkinds-self-type.rs index d0ccfe0e21d..1c156f6551c 100644 --- a/src/test/run-pass/builtin-superkinds-self-type.rs +++ b/src/test/run-pass/builtin-superkinds-self-type.rs @@ -21,6 +21,6 @@ impl <T: Send> Foo for T { } pub fn main() { let (tx, rx) = channel(); - 1193182.foo(tx); - assert!(rx.recv() == 1193182); + 1193182i.foo(tx); + assert!(rx.recv() == 1193182i); } diff --git a/src/test/run-pass/by-value-self-objects.rs b/src/test/run-pass/by-value-self-objects.rs new file mode 100644 index 00000000000..3a588367a97 --- /dev/null +++ b/src/test/run-pass/by-value-self-objects.rs @@ -0,0 +1,77 @@ +// 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. + +static mut destructor_count: uint = 0; + +trait Foo { + fn foo(self, x: int); +} + +struct S { + x: int, + y: int, + z: int, + s: String, +} + +impl Foo for S { + fn foo(self, x: int) { + assert!(self.x == 2); + assert!(self.y == 3); + assert!(self.z == 4); + assert!(self.s.as_slice() == "hello"); + assert!(x == 5); + } +} + +impl Drop for S { + fn drop(&mut self) { + println!("bye 1!"); + unsafe { + destructor_count += 1; + } + } +} + +impl Foo for int { + fn foo(self, x: int) { + println!("{}", x * x); + } +} + +fn f() { + let s = S { + x: 2, + y: 3, + z: 4, + s: "hello".to_string(), + }; + let st = box s as Box<Foo>; + st.foo(5); + println!("bye 2!"); +} + +fn g() { + let s = 2i; + let st = box s as Box<Foo>; + st.foo(3); + println!("bye 3!"); +} + +fn main() { + f(); + + unsafe { + assert!(destructor_count == 1); + } + + g(); +} + diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index 540a00d3a31..597e067b8b6 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -16,8 +16,8 @@ mod mlibc { use libc::{c_char, c_long, c_longlong}; extern { - pub fn atol(x: *c_char) -> c_long; - pub fn atoll(x: *c_char) -> c_longlong; + pub fn atol(x: *const c_char) -> c_long; + pub fn atoll(x: *const c_char) -> c_longlong; } } diff --git a/src/test/run-pass/capturing-logging.rs b/src/test/run-pass/capturing-logging.rs index 23607e16795..19186f4b46b 100644 --- a/src/test/run-pass/capturing-logging.rs +++ b/src/test/run-pass/capturing-logging.rs @@ -31,7 +31,7 @@ impl Logger for MyWriter { } #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { native::start(argc, argv, proc() { main(); }) diff --git a/src/test/run-pass/cast-region-to-uint.rs b/src/test/run-pass/cast-region-to-uint.rs index eacdd8f3978..a298a08a1b7 100644 --- a/src/test/run-pass/cast-region-to-uint.rs +++ b/src/test/run-pass/cast-region-to-uint.rs @@ -10,5 +10,5 @@ pub fn main() { let x = 3; - println!("&x={:x}", (&x as *int as uint)); + println!("&x={:x}", (&x as *const int as uint)); } diff --git a/src/test/run-pass/class-poly-methods.rs b/src/test/run-pass/class-poly-methods.rs index 4f94673a2c0..d94547a4dda 100644 --- a/src/test/run-pass/class-poly-methods.rs +++ b/src/test/run-pass/class-poly-methods.rs @@ -36,7 +36,7 @@ pub fn main() { let mut kitty = cat(1000u, 2, vec!("tabby".to_string())); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); - nyan.speak(vec!(1,2,3)); + nyan.speak(vec!(1i,2,3)); assert_eq!(nyan.meow_count(), 55u); kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string())); assert_eq!(kitty.meow_count(), 1004u); diff --git a/src/test/run-pass/cleanup-auto-borrow-obj.rs b/src/test/run-pass/cleanup-auto-borrow-obj.rs new file mode 100644 index 00000000000..23142082a8c --- /dev/null +++ b/src/test/run-pass/cleanup-auto-borrow-obj.rs @@ -0,0 +1,38 @@ +// 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. + + +// This would previously leak the Box<Trait> because we wouldn't +// schedule cleanups when auto borrowing trait objects. +// This program should be valgrind clean. + + +static mut DROP_RAN: bool = false; + +struct Foo; +impl Drop for Foo { + fn drop(&mut self) { + unsafe { DROP_RAN = true; } + } +} + + +trait Trait {} +impl Trait for Foo {} + +pub fn main() { + { + let _x: &Trait = box Foo as Box<Trait>; + } + unsafe { + assert!(DROP_RAN); + } +} + diff --git a/src/test/run-pass/cleanup-rvalue-scopes.rs b/src/test/run-pass/cleanup-rvalue-scopes.rs index 470e16b4888..35c69705925 100644 --- a/src/test/run-pass/cleanup-rvalue-scopes.rs +++ b/src/test/run-pass/cleanup-rvalue-scopes.rs @@ -110,7 +110,7 @@ pub fn main() { end_of_block!(ref _x, AddFlags(1)); end_of_block!(AddFlags { bits: ref _x }, AddFlags(1)); end_of_block!(&AddFlags { bits }, &AddFlags(1)); - end_of_block!((_, ref _y), (AddFlags(1), 22)); + end_of_block!((_, ref _y), (AddFlags(1), 22i)); end_of_block!(box ref _x, box AddFlags(1)); end_of_block!(box _x, box AddFlags(1)); end_of_block!(_, { { check_flags(0); &AddFlags(1) } }); @@ -120,7 +120,7 @@ pub fn main() { // LHS does not create a ref binding, so temporary lives as long // as statement, and we do not move the AddFlags out: end_of_stmt!(_, AddFlags(1)); - end_of_stmt!((_, _), (AddFlags(1), 22)); + end_of_stmt!((_, _), (AddFlags(1), 22i)); // `&` operator appears inside an arg to a function, // so it is not prolonged: diff --git a/src/test/run-pass/cmp-default.rs b/src/test/run-pass/cmp-default.rs index 7805a2bb49e..cfba87c3f69 100644 --- a/src/test/run-pass/cmp-default.rs +++ b/src/test/run-pass/cmp-default.rs @@ -31,10 +31,10 @@ impl PartialEq for Int { } impl PartialOrd for Int { - fn lt(&self, other: &Int) -> bool { + fn partial_cmp(&self, other: &Int) -> Option<Ordering> { let Int(this) = *self; let Int(other) = *other; - this < other + this.partial_cmp(&other) } } @@ -49,10 +49,10 @@ impl PartialEq for RevInt { } impl PartialOrd for RevInt { - fn lt(&self, other: &RevInt) -> bool { + fn partial_cmp(&self, other: &RevInt) -> Option<Ordering> { let RevInt(this) = *self; let RevInt(other) = *other; - this > other + other.partial_cmp(&this) } } diff --git a/src/test/run-pass/const-binops.rs b/src/test/run-pass/const-binops.rs index be186a95a77..c14f430e709 100644 --- a/src/test/run-pass/const-binops.rs +++ b/src/test/run-pass/const-binops.rs @@ -53,28 +53,28 @@ static V: int = 1 << 3; static W: int = 1024 >> 4; static X: uint = 1024 >> 4; -static Y: bool = 1 == 1; -static Z: bool = 1.0 == 1.0; +static Y: bool = 1i == 1; +static Z: bool = 1.0f64 == 1.0; -static AA: bool = 1 <= 2; -static AB: bool = -1 <= 2; -static AC: bool = 1.0 <= 2.0; +static AA: bool = 1i <= 2; +static AB: bool = -1i <= 2; +static AC: bool = 1.0f64 <= 2.0; -static AD: bool = 1 < 2; -static AE: bool = -1 < 2; -static AF: bool = 1.0 < 2.0; +static AD: bool = 1i < 2; +static AE: bool = -1i < 2; +static AF: bool = 1.0f64 < 2.0; -static AG: bool = 1 != 2; -static AH: bool = -1 != 2; -static AI: bool = 1.0 != 2.0; +static AG: bool = 1i != 2; +static AH: bool = -1i != 2; +static AI: bool = 1.0f64 != 2.0; -static AJ: bool = 2 >= 1; -static AK: bool = 2 >= -2; -static AL: bool = 1.0 >= -2.0; +static AJ: bool = 2i >= 1; +static AK: bool = 2i >= -2; +static AL: bool = 1.0f64 >= -2.0; -static AM: bool = 2 > 1; -static AN: bool = 2 > -2; -static AO: bool = 1.0 > -2.0; +static AM: bool = 2i > 1; +static AN: bool = 2i > -2; +static AO: bool = 1.0f64 > -2.0; pub fn main() { assert_eq!(A, -1); diff --git a/src/test/run-pass/const-block.rs b/src/test/run-pass/const-block.rs index feac6e68e48..01eccc53427 100644 --- a/src/test/run-pass/const-block.rs +++ b/src/test/run-pass/const-block.rs @@ -13,7 +13,7 @@ struct Foo { a: uint, - b: *() + b: *const () } fn foo<T>(a: T) -> T { @@ -25,7 +25,7 @@ static BLOCK_EXPLICIT_UNIT: () = { () }; static BLOCK_IMPLICIT_UNIT: () = { }; static BLOCK_FLOAT: f64 = { 1.0 }; static BLOCK_ENUM: Option<uint> = { Some(100) }; -static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *() } }; +static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *const () } }; static BLOCK_UNSAFE: uint = unsafe { 1000 }; // FIXME: #13970 @@ -50,7 +50,7 @@ pub fn main() { assert_eq!(BLOCK_IMPLICIT_UNIT, ()); assert_eq!(BLOCK_FLOAT, 1.0_f64); assert_eq!(BLOCK_STRUCT.a, 12); - assert_eq!(BLOCK_STRUCT.b, 0 as *()); + assert_eq!(BLOCK_STRUCT.b, 0 as *const ()); assert_eq!(BLOCK_ENUM, Some(100)); assert_eq!(BLOCK_UNSAFE, 1000); diff --git a/src/test/run-pass/const-bound.rs b/src/test/run-pass/const-bound.rs index 7ca4e25a74d..08912419b5c 100644 --- a/src/test/run-pass/const-bound.rs +++ b/src/test/run-pass/const-bound.rs @@ -23,5 +23,5 @@ pub fn main() { foo(F{field: 42}); foo((1, 2u)); foo(@1);*/ - foo(box 1); + foo(box 1i); } diff --git a/src/test/run-pass/const-cast-ptr-int.rs b/src/test/run-pass/const-cast-ptr-int.rs index 88ab70f596a..e4734fc3e55 100644 --- a/src/test/run-pass/const-cast-ptr-int.rs +++ b/src/test/run-pass/const-cast-ptr-int.rs @@ -10,7 +10,7 @@ use std::ptr; -static a: *u8 = 0 as *u8; +static a: *const u8 = 0 as *const u8; pub fn main() { assert_eq!(a, ptr::null()); diff --git a/src/test/run-pass/const-cast.rs b/src/test/run-pass/const-cast.rs index 7b17b578b82..87a4fd1153f 100644 --- a/src/test/run-pass/const-cast.rs +++ b/src/test/run-pass/const-cast.rs @@ -13,11 +13,11 @@ extern crate libc; extern fn foo() {} static x: extern "C" fn() = foo; -static y: *libc::c_void = x as *libc::c_void; +static y: *const libc::c_void = x as *const libc::c_void; static a: &'static int = &10; -static b: *int = a as *int; +static b: *const int = a as *const int; pub fn main() { - assert_eq!(x as *libc::c_void, y); - assert_eq!(a as *int, b); + assert_eq!(x as *const libc::c_void, y); + assert_eq!(a as *const int, b); } diff --git a/src/test/run-pass/const-region-ptrs-noncopy.rs b/src/test/run-pass/const-region-ptrs-noncopy.rs index 87363c0e55e..36fe021b97e 100644 --- a/src/test/run-pass/const-region-ptrs-noncopy.rs +++ b/src/test/run-pass/const-region-ptrs-noncopy.rs @@ -14,5 +14,5 @@ static x: &'static Big = &([13, 14, 10, 13, 11, 14, 14, 15]); static y: &'static Pair<'static> = &Pair {a: 15, b: x}; pub fn main() { - assert_eq!(x as *Big, y.b as *Big); + assert_eq!(x as *const Big, y.b as *const Big); } diff --git a/src/test/run-pass/const-str-ptr.rs b/src/test/run-pass/const-str-ptr.rs index 77c7a08f4ca..6790e237e26 100644 --- a/src/test/run-pass/const-str-ptr.rs +++ b/src/test/run-pass/const-str-ptr.rs @@ -12,18 +12,18 @@ use std::str; static A: [u8, ..2] = ['h' as u8, 'i' as u8]; static B: &'static [u8, ..2] = &A; -static C: *u8 = B as *u8; +static C: *const u8 = B as *const u8; pub fn main() { unsafe { - let foo = &A as *u8; + let foo = &A as *const u8; assert_eq!(str::raw::from_utf8(A), "hi"); assert_eq!(str::raw::from_buf_len(foo, A.len()), "hi".to_string()); assert_eq!(str::raw::from_buf_len(C, B.len()), "hi".to_string()); assert!(*C == A[0]); - assert!(*(&B[0] as *u8) == A[0]); + assert!(*(&B[0] as *const u8) == A[0]); let bar = str::raw::from_utf8(A).to_c_str(); - assert_eq!(bar.with_ref(|buf| str::raw::from_c_str(buf)), "hi".to_string()); + assert_eq!(str::raw::from_c_str(bar.as_ptr()), "hi".to_string()); } } diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index a0d4785d8d2..8e84278c10e 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -54,7 +54,7 @@ macro_rules! iotest ( ) #[cfg(test)] #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, __test::main) } diff --git a/src/test/run-pass/deriving-cmp-generic-enum.rs b/src/test/run-pass/deriving-cmp-generic-enum.rs index 4a9324dd201..ccd0d967a51 100644 --- a/src/test/run-pass/deriving-cmp-generic-enum.rs +++ b/src/test/run-pass/deriving-cmp-generic-enum.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #[deriving(PartialEq, Eq, PartialOrd, Ord)] enum E<T> { diff --git a/src/test/run-pass/deriving-cmp-generic-struct-enum.rs b/src/test/run-pass/deriving-cmp-generic-struct-enum.rs index b21c95d7b50..2abdf4c7c7e 100644 --- a/src/test/run-pass/deriving-cmp-generic-struct-enum.rs +++ b/src/test/run-pass/deriving-cmp-generic-struct-enum.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #![feature(struct_variant)] diff --git a/src/test/run-pass/deriving-cmp-generic-struct.rs b/src/test/run-pass/deriving-cmp-generic-struct.rs index e2b8e1b6b82..d1610978e2e 100644 --- a/src/test/run-pass/deriving-cmp-generic-struct.rs +++ b/src/test/run-pass/deriving-cmp-generic-struct.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #[deriving(PartialEq, Eq, PartialOrd, Ord)] struct S<T> { diff --git a/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs b/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs index c07f124a08d..25f62e85ba6 100644 --- a/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs +++ b/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 #[deriving(PartialEq, Eq, PartialOrd, Ord)] struct TS<T>(T,T); diff --git a/src/test/run-pass/deriving-cmp-shortcircuit.rs b/src/test/run-pass/deriving-cmp-shortcircuit.rs index 69ee47fd1d9..df5c58ff04b 100644 --- a/src/test/run-pass/deriving-cmp-shortcircuit.rs +++ b/src/test/run-pass/deriving-cmp-shortcircuit.rs @@ -18,7 +18,7 @@ impl PartialEq for FailCmp { } impl PartialOrd for FailCmp { - fn lt(&self, _: &FailCmp) -> bool { fail!("lt") } + fn partial_cmp(&self, _: &FailCmp) -> Option<Ordering> { fail!("partial_cmp") } } impl Eq for FailCmp {} diff --git a/src/test/run-pass/drop-trait-generic.rs b/src/test/run-pass/drop-trait-generic.rs index 4ba3aa70dfc..9a93873f538 100644 --- a/src/test/run-pass/drop-trait-generic.rs +++ b/src/test/run-pass/drop-trait-generic.rs @@ -22,5 +22,5 @@ impl<T> ::std::ops::Drop for S<T> { } pub fn main() { - let _x = S { x: 1 }; + let _x = S { x: 1i }; } diff --git a/src/test/run-pass/drop-with-type-ascription-1.rs b/src/test/run-pass/drop-with-type-ascription-1.rs new file mode 100644 index 00000000000..c4ea169cb79 --- /dev/null +++ b/src/test/run-pass/drop-with-type-ascription-1.rs @@ -0,0 +1,17 @@ +// Copyright 2012 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 foo = "hello".to_string(); + let foo: Vec<&str> = foo.as_slice().words().collect(); + let invalid_string = foo.get(0); + assert_eq!(*invalid_string, "hello"); +} + diff --git a/src/test/run-pass/drop-with-type-ascription-2.rs b/src/test/run-pass/drop-with-type-ascription-2.rs new file mode 100644 index 00000000000..634b1004e53 --- /dev/null +++ b/src/test/run-pass/drop-with-type-ascription-2.rs @@ -0,0 +1,17 @@ +// Copyright 2012 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 args = vec!("foobie", "asdf::asdf"); + let arr: Vec<&str> = args.get(1).as_slice().split_str("::").collect(); + assert_eq!(*arr.get(0), "asdf"); + assert_eq!(*arr.get(0), "asdf"); +} + diff --git a/src/test/run-pass/early-ret-binop-add.rs b/src/test/run-pass/early-ret-binop-add.rs index 97e873e9aff..b9efdeb3bed 100644 --- a/src/test/run-pass/early-ret-binop-add.rs +++ b/src/test/run-pass/early-ret-binop-add.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn wsucc(n: int) -> int { 0 + { return n + 1 } } +fn wsucc(n: int) -> int { 0i + { return n + 1 } } pub fn main() { } diff --git a/src/test/run-pass/else-if.rs b/src/test/run-pass/else-if.rs index 476d3f42d6e..63f32ae702b 100644 --- a/src/test/run-pass/else-if.rs +++ b/src/test/run-pass/else-if.rs @@ -11,20 +11,20 @@ pub fn main() { - if 1 == 2 { + if 1i == 2 { assert!((false)); - } else if 2 == 3 { + } else if 2i == 3 { assert!((false)); - } else if 3 == 4 { assert!((false)); } else { assert!((true)); } - if 1 == 2 { assert!((false)); } else if 2 == 2 { assert!((true)); } - if 1 == 2 { + } else if 3i == 4 { assert!((false)); } else { assert!((true)); } + if 1i == 2 { assert!((false)); } else if 2i == 2 { assert!((true)); } + if 1i == 2 { assert!((false)); - } else if 2 == 2 { - if 1 == 1 { + } else if 2i == 2 { + if 1i == 1 { assert!((true)); - } else { if 2 == 1 { assert!((false)); } else { assert!((false)); } } + } else { if 2i == 1 { assert!((false)); } else { assert!((false)); } } } - if 1 == 2 { + if 1i == 2 { assert!((false)); - } else { if 1 == 2 { assert!((false)); } else { assert!((true)); } } + } else { if 1i == 2 { assert!((false)); } else { assert!((true)); } } } diff --git a/src/test/run-pass/enum-alignment.rs b/src/test/run-pass/enum-alignment.rs index 2a8293fcba8..a1ef12a7657 100644 --- a/src/test/run-pass/enum-alignment.rs +++ b/src/test/run-pass/enum-alignment.rs @@ -11,7 +11,7 @@ use std::mem; fn addr_of<T>(ptr: &T) -> uint { - ptr as *T as uint + ptr as *const T as uint } fn is_aligned<T>(ptr: &T) -> bool { diff --git a/src/test/run-pass/enum-discr.rs b/src/test/run-pass/enum-discr.rs index 1d7ec0aa1bc..5fe8bb27e15 100644 --- a/src/test/run-pass/enum-discr.rs +++ b/src/test/run-pass/enum-discr.rs @@ -9,10 +9,10 @@ // except according to those terms. enum Animal { - Cat = 0u, - Dog = 1u, - Horse = 2u, - Snake = 3u + Cat = 0, + Dog = 1, + Horse = 2, + Snake = 3, } enum Hero { diff --git a/src/test/run-pass/enum-discrim-width-stuff.rs b/src/test/run-pass/enum-discrim-width-stuff.rs index 814e2cca97c..ccbc5d12191 100644 --- a/src/test/run-pass/enum-discrim-width-stuff.rs +++ b/src/test/run-pass/enum-discrim-width-stuff.rs @@ -23,8 +23,8 @@ macro_rules! check { static C: E = V; pub fn check() { assert_eq!(size_of::<E>(), size_of::<$t>()); - assert_eq!(V as $t, $v); - assert_eq!(C as $t, $v); + assert_eq!(V as $t, $v as $t); + assert_eq!(C as $t, $v as $t); assert_eq!(format!("{:?}", V), "V".to_string()); assert_eq!(format!("{:?}", C), "V".to_string()); } @@ -40,8 +40,6 @@ pub fn main() { check!(d, u16, 0xe8d8); check!(e, u32, 0x17273747); check!(f, u32, 0xe8d8c8b8); - check!(g, u64, 0x1727374757677787u64); - check!(h, u64, 0xe8d8c8b8a8988878u64); check!(z, i8, 0x17); check!(y, i8, -0x17); @@ -49,8 +47,6 @@ pub fn main() { check!(w, i16, -0x1727); check!(v, i32, 0x17273747); check!(u, i32, -0x17273747); - check!(t, i64, 0x1727374757677787); - check!(s, i64, -0x1727374757677787); enum Simple { A, B } assert_eq!(::std::mem::size_of::<Simple>(), 1); diff --git a/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs b/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs index 4ddff8d899a..da35ffb5295 100644 --- a/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs +++ b/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs @@ -20,8 +20,8 @@ use std::gc::{Gc, GC}; enum List<X> { Nil, Cons(X, Gc<List<X>>) } pub fn main() { - match Cons(10, box(GC) Nil) { - Cons(10, _) => {} + match Cons(10i, box(GC) Nil) { + Cons(10i, _) => {} Nil => {} _ => fail!() } diff --git a/src/test/run-pass/enum-vec-initializer.rs b/src/test/run-pass/enum-vec-initializer.rs index a55b5eebefb..b04f5e11042 100644 --- a/src/test/run-pass/enum-vec-initializer.rs +++ b/src/test/run-pass/enum-vec-initializer.rs @@ -16,9 +16,9 @@ static BAR:uint = Bunny as uint; static BAR2:uint = BAR; pub fn main() { - let _v = [0, .. Bunny as uint]; - let _v = [0, .. BAR]; - let _v = [0, .. BAR2]; + let _v = [0i, .. Bunny as uint]; + let _v = [0i, .. BAR]; + let _v = [0i, .. BAR2]; static BAR3:uint = BAR2; - let _v = [0, .. BAR3]; + let _v = [0i, .. BAR3]; } diff --git a/src/test/run-pass/estr-slice.rs b/src/test/run-pass/estr-slice.rs index 3d6b6ba626d..5364cdc627f 100644 --- a/src/test/run-pass/estr-slice.rs +++ b/src/test/run-pass/estr-slice.rs @@ -17,8 +17,8 @@ pub fn main() { println!("{}", x); println!("{}", y); - assert_eq!(x[0], 'h' as u8); - assert_eq!(x[4], 'o' as u8); + assert_eq!(x.as_bytes()[0], 'h' as u8); + assert_eq!(x.as_bytes()[4], 'o' as u8); let z : &str = "thing"; assert_eq!(v, x); diff --git a/src/test/run-pass/estr-uniq.rs b/src/test/run-pass/estr-uniq.rs index 1652016b51b..b562558822c 100644 --- a/src/test/run-pass/estr-uniq.rs +++ b/src/test/run-pass/estr-uniq.rs @@ -15,6 +15,6 @@ pub fn main() { let _y : String = "there".to_string(); let mut z = "thing".to_string(); z = x; - assert_eq!(z.as_slice()[0], ('h' as u8)); - assert_eq!(z.as_slice()[4], ('o' as u8)); + assert_eq!(z.as_bytes()[0], ('h' as u8)); + assert_eq!(z.as_bytes()[4], ('o' as u8)); } diff --git a/src/test/run-pass/expr-block-box.rs b/src/test/run-pass/expr-block-box.rs index b9d005d945f..5652cdea879 100644 --- a/src/test/run-pass/expr-block-box.rs +++ b/src/test/run-pass/expr-block-box.rs @@ -12,4 +12,4 @@ use std::gc::GC; -pub fn main() { let x = { box(GC) 100 }; assert!((*x == 100)); } +pub fn main() { let x = { box(GC) 100i }; assert!((*x == 100)); } diff --git a/src/test/run-pass/expr-block-ref.rs b/src/test/run-pass/expr-block-ref.rs index df7ea0c943b..050ecebb2a1 100644 --- a/src/test/run-pass/expr-block-ref.rs +++ b/src/test/run-pass/expr-block-ref.rs @@ -13,4 +13,4 @@ use std::gc::GC; // Regression test for issue #388 -pub fn main() { let _x = { { box(GC) 10 } }; } +pub fn main() { let _x = { { box(GC) 10i } }; } diff --git a/src/test/run-pass/expr-block-unique.rs b/src/test/run-pass/expr-block-unique.rs index 12777bce710..0dff989002f 100644 --- a/src/test/run-pass/expr-block-unique.rs +++ b/src/test/run-pass/expr-block-unique.rs @@ -11,4 +11,4 @@ -pub fn main() { let x = { box 100 }; assert!((*x == 100)); } +pub fn main() { let x = { box 100i }; assert!((*x == 100)); } diff --git a/src/test/run-pass/expr-empty-ret.rs b/src/test/run-pass/expr-empty-ret.rs index afc7dfaf9b4..7b08251967e 100644 --- a/src/test/run-pass/expr-empty-ret.rs +++ b/src/test/run-pass/expr-empty-ret.rs @@ -12,7 +12,7 @@ fn f() { let _x = match true { - true => { 10 } + true => { 10i } false => { return } }; } diff --git a/src/test/run-pass/expr-if-fail-all.rs b/src/test/run-pass/expr-if-fail-all.rs index a34620d2e1b..8e56011e6dc 100644 --- a/src/test/run-pass/expr-if-fail-all.rs +++ b/src/test/run-pass/expr-if-fail-all.rs @@ -12,7 +12,7 @@ // expression results in fail. pub fn main() { let _x = if true { - 10 + 10i } else { if true { fail!() } else { fail!() } }; diff --git a/src/test/run-pass/expr-if-fail.rs b/src/test/run-pass/expr-if-fail.rs index 023ba508ae5..e9f116fcdd4 100644 --- a/src/test/run-pass/expr-if-fail.rs +++ b/src/test/run-pass/expr-if-fail.rs @@ -8,7 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); } +fn test_if_fail() { + let x = if false { fail!() } else { 10i }; + assert!((x == 10)); +} fn test_else_fail() { let x = if true { 10i } else { fail!() }; @@ -16,7 +19,7 @@ fn test_else_fail() { } fn test_elseif_fail() { - let x = if false { 0 } else if false { fail!() } else { 10i }; + let x = if false { 0i } else if false { fail!() } else { 10i }; assert_eq!(x, 10i); } diff --git a/src/test/run-pass/expr-match-fail-all.rs b/src/test/run-pass/expr-match-fail-all.rs index 5c83e81d8be..0d23098d8fc 100644 --- a/src/test/run-pass/expr-match-fail-all.rs +++ b/src/test/run-pass/expr-match-fail-all.rs @@ -16,7 +16,7 @@ pub fn main() { let _x = match true { - true => { 10 } + true => { 10i } false => { match true { true => { fail!() } false => { fail!() } } } }; } diff --git a/src/test/run-pass/extern-pub.rs b/src/test/run-pass/extern-pub.rs index 28025728472..cefc266b5c7 100644 --- a/src/test/run-pass/extern-pub.rs +++ b/src/test/run-pass/extern-pub.rs @@ -9,7 +9,7 @@ // except according to those terms. extern { - pub fn free(p: *u8); + pub fn free(p: *const u8); } pub fn main() { diff --git a/src/test/run-pass/floatlits.rs b/src/test/run-pass/floatlits.rs index d1300e7f30c..09df423d2da 100644 --- a/src/test/run-pass/floatlits.rs +++ b/src/test/run-pass/floatlits.rs @@ -11,10 +11,10 @@ pub fn main() { - let f = 4.999999999999; - assert!((f > 4.90)); - assert!((f < 5.0)); - let g = 4.90000000001e-10; - assert!((g > 5e-11)); - assert!((g < 5e-9)); + let f = 4.999999999999f64; + assert!((f > 4.90f64)); + assert!((f < 5.0f64)); + let g = 4.90000000001e-10f64; + assert!((g > 5e-11f64)); + assert!((g < 5e-9f64)); } diff --git a/src/test/run-pass/fn-type-infer.rs b/src/test/run-pass/fn-type-infer.rs index 34417891197..80d3527736f 100644 --- a/src/test/run-pass/fn-type-infer.rs +++ b/src/test/run-pass/fn-type-infer.rs @@ -13,6 +13,6 @@ pub fn main() { // We should be able to type infer inside of ||s. let _f = || { - let i = 10; + let i = 10i; }; } diff --git a/src/test/run-pass/foreach-external-iterators-break.rs b/src/test/run-pass/foreach-external-iterators-break.rs index 87ed7826fed..d9d3e320260 100644 --- a/src/test/run-pass/foreach-external-iterators-break.rs +++ b/src/test/run-pass/foreach-external-iterators-break.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn main() { - let x = [1,..100]; - let mut y = 0; + let x = [1i,..100]; + let mut y = 0i; for i in x.iter() { if y > 10 { break; diff --git a/src/test/run-pass/foreach-external-iterators-nested.rs b/src/test/run-pass/foreach-external-iterators-nested.rs index 78aba778421..f4d38dfcfc3 100644 --- a/src/test/run-pass/foreach-external-iterators-nested.rs +++ b/src/test/run-pass/foreach-external-iterators-nested.rs @@ -9,10 +9,10 @@ // except according to those terms. pub fn main() { - let x = [1,..100]; - let y = [2,..100]; - let mut p = 0; - let mut q = 0; + let x = [1i,..100]; + let y = [2i,..100]; + let mut p = 0i; + let mut q = 0i; for i in x.iter() { for j in y.iter() { p += *j; diff --git a/src/test/run-pass/foreach-external-iterators.rs b/src/test/run-pass/foreach-external-iterators.rs index 593a996d8df..684a9b81fb2 100644 --- a/src/test/run-pass/foreach-external-iterators.rs +++ b/src/test/run-pass/foreach-external-iterators.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn main() { - let x = [1,..100]; - let mut y = 0; + let x = [1i,..100]; + let mut y = 0i; for i in x.iter() { y += *i } diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index bd4c89eb8ab..9dd52dfb6da 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -22,7 +22,7 @@ extern { pub fn main() { unsafe { Thread::start(proc() { - let i = &100; + let i = &100i; rust_dbg_call(callback, mem::transmute(i)); }).join(); } @@ -30,7 +30,7 @@ pub fn main() { extern fn callback(data: libc::uintptr_t) { unsafe { - let data: *int = mem::transmute(data); - assert_eq!(*data, 100); + let data: *const int = mem::transmute(data); + assert_eq!(*data, 100i); } } diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index 890f5158a65..750c0c8ed68 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -18,7 +18,7 @@ mod mlibc { extern { #[link_name = "strlen"] - pub fn my_strlen(str: *c_char) -> size_t; + pub fn my_strlen(str: *const c_char) -> size_t; } } diff --git a/src/test/run-pass/foreign2.rs b/src/test/run-pass/foreign2.rs index 3c7e878c318..ce2f8955664 100644 --- a/src/test/run-pass/foreign2.rs +++ b/src/test/run-pass/foreign2.rs @@ -24,7 +24,7 @@ mod mlibc { use libc::{c_int, c_void, size_t, ssize_t}; extern { - pub fn write(fd: c_int, buf: *c_void, count: size_t) -> ssize_t; + pub fn write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t; } } diff --git a/src/test/run-pass/func-arg-incomplete-pattern.rs b/src/test/run-pass/func-arg-incomplete-pattern.rs index 5ab3930e7a3..6d06c12c450 100644 --- a/src/test/run-pass/func-arg-incomplete-pattern.rs +++ b/src/test/run-pass/func-arg-incomplete-pattern.rs @@ -17,14 +17,14 @@ struct Foo { y: Box<uint>, } -fn foo(Foo {x, ..}: Foo) -> *uint { - let addr: *uint = &*x; +fn foo(Foo {x, ..}: Foo) -> *const uint { + let addr: *const uint = &*x; addr } pub fn main() { let obj = box 1; - let objptr: *uint = &*obj; + let objptr: *const uint = &*obj; let f = Foo {x: obj, y: box 2}; let xptr = foo(f); assert_eq!(objptr, xptr); diff --git a/src/test/run-pass/func-arg-ref-pattern.rs b/src/test/run-pass/func-arg-ref-pattern.rs index bb4be948a5e..5eeace65054 100644 --- a/src/test/run-pass/func-arg-ref-pattern.rs +++ b/src/test/run-pass/func-arg-ref-pattern.rs @@ -15,8 +15,8 @@ // pattern. -fn getaddr(box ref x: Box<uint>) -> *uint { - let addr: *uint = &*x; +fn getaddr(box ref x: Box<uint>) -> *const uint { + let addr: *const uint = &*x; addr } @@ -26,7 +26,7 @@ fn checkval(box ref x: Box<uint>) -> uint { pub fn main() { let obj = box 1; - let objptr: *uint = &*obj; + let objptr: *const uint = &*obj; let xptr = getaddr(obj); assert_eq!(objptr, xptr); diff --git a/src/test/run-pass/generic-ivec-leak.rs b/src/test/run-pass/generic-ivec-leak.rs index f879e195292..ac97a2aa9e8 100644 --- a/src/test/run-pass/generic-ivec-leak.rs +++ b/src/test/run-pass/generic-ivec-leak.rs @@ -10,4 +10,4 @@ enum wrapper<T> { wrapped(T), } -pub fn main() { let _w = wrapped(vec!(1, 2, 3, 4, 5)); } +pub fn main() { let _w = wrapped(vec!(1i, 2, 3, 4, 5)); } diff --git a/src/test/run-pass/generic-ivec.rs b/src/test/run-pass/generic-ivec.rs index 18d1b7f03a1..4402dd35d09 100644 --- a/src/test/run-pass/generic-ivec.rs +++ b/src/test/run-pass/generic-ivec.rs @@ -13,4 +13,4 @@ use std::gc::{Gc, GC}; fn f<T>(_v: Gc<T>) { } -pub fn main() { f(box(GC) vec!(1, 2, 3, 4, 5)); } +pub fn main() { f(box(GC) vec!(1i, 2, 3, 4, 5)); } diff --git a/src/test/run-pass/generic-tag-local.rs b/src/test/run-pass/generic-tag-local.rs index fb8140790e3..7d011e57671 100644 --- a/src/test/run-pass/generic-tag-local.rs +++ b/src/test/run-pass/generic-tag-local.rs @@ -12,4 +12,4 @@ enum clam<T> { a(T), } -pub fn main() { let _c = a(3); } +pub fn main() { let _c = a(3i); } diff --git a/src/test/run-pass/guards.rs b/src/test/run-pass/guards.rs index 450620767e3..5bfbe4bf5a0 100644 --- a/src/test/run-pass/guards.rs +++ b/src/test/run-pass/guards.rs @@ -12,14 +12,14 @@ struct Pair { x: int, y: int } pub fn main() { let a: int = - match 10 { x if x < 7 => { 1 } x if x < 11 => { 2 } 10 => { 3 } _ => { 4 } }; + match 10i { x if x < 7 => { 1i } x if x < 11 => { 2i } 10 => { 3i } _ => { 4i } }; assert_eq!(a, 2); let b: int = match (Pair {x: 10, y: 20}) { - x if x.x < 5 && x.y < 5 => { 1 } - Pair {x: x, y: y} if x == 10 && y == 20 => { 2 } - Pair {x: _x, y: _y} => { 3 } + x if x.x < 5 && x.y < 5 => { 1i } + Pair {x: x, y: y} if x == 10 && y == 20 => { 2i } + Pair {x: _x, y: _y} => { 3i } }; assert_eq!(b, 2); } diff --git a/src/test/run-pass/hygiene-dodging-1.rs b/src/test/run-pass/hygiene-dodging-1.rs index 3969394a26b..eb81f82a146 100644 --- a/src/test/run-pass/hygiene-dodging-1.rs +++ b/src/test/run-pass/hygiene-dodging-1.rs @@ -14,7 +14,7 @@ mod x { pub fn main(){ // should *not* shadow the module x: - let x = 9; + let x = 9i; // use it to avoid warnings: x+3; assert_eq!(x::g(),14); diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index 4b678d78834..e349f91a309 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -69,7 +69,7 @@ pub fn main() { t!(format!("{:X}", 10u), "A"); t!(format!("{:s}", "foo"), "foo"); t!(format!("{:s}", "foo".to_string()), "foo"); - t!(format!("{:p}", 0x1234 as *int), "0x1234"); + t!(format!("{:p}", 0x1234 as *const int), "0x1234"); t!(format!("{:p}", 0x1234 as *mut int), "0x1234"); t!(format!("{:d}", A), "aloha"); t!(format!("{:d}", B), "adios"); @@ -81,6 +81,9 @@ pub fn main() { t!(format!("{foo_bar}", foo_bar=1i), "1"); t!(format!("{:d}", 5i + 5i), "10"); + let a: &fmt::Show = &1i; + t!(format!("{}", a), "1"); + // Formatting strings and their arguments t!(format!("{:s}", "a"), "a"); t!(format!("{:4s}", "a"), "a "); diff --git a/src/test/run-pass/ignore-all-the-things.rs b/src/test/run-pass/ignore-all-the-things.rs index b176254a878..27c63d425bf 100644 --- a/src/test/run-pass/ignore-all-the-things.rs +++ b/src/test/run-pass/ignore-all-the-things.rs @@ -21,28 +21,28 @@ pub fn main() { //let (a, b, ..) = (5, 5, 5, 5); //let (.., c, d) = (5, 5, 5, 5); let Bar{b: b, ..} = Bar{a: 5, b: 5, c: 5, d: 5}; - match [5, 5, 5, 5] { + match [5i, 5, 5, 5] { [..] => { } } - match [5, 5, 5, 5] { + match [5i, 5, 5, 5] { [a, ..] => { } } - match [5, 5, 5, 5] { + match [5i, 5, 5, 5] { [.., b] => { } } - match [5, 5, 5, 5] { + match [5i, 5, 5, 5] { [a, .., b] => { } } - match [5, 5, 5] { + match [5i, 5, 5] { [..] => { } } - match [5, 5, 5] { + match [5i, 5, 5] { [a, ..] => { } } - match [5, 5, 5] { + match [5i, 5, 5] { [.., a] => { } } - match [5, 5, 5] { + match [5i, 5, 5] { [a, .., b] => { } } } diff --git a/src/test/run-pass/import-in-block.rs b/src/test/run-pass/import-in-block.rs index 24196c22571..19300569d20 100644 --- a/src/test/run-pass/import-in-block.rs +++ b/src/test/run-pass/import-in-block.rs @@ -12,11 +12,11 @@ pub fn main() { use std::mem::replace; - let mut x = 5; + let mut x = 5i; replace(&mut x, 6); { use std::mem::*; - let mut y = 6; + let mut y = 6i; swap(&mut x, &mut y); } } diff --git a/src/test/run-pass/import4.rs b/src/test/run-pass/import4.rs index 44f6b6140fb..0639d732089 100644 --- a/src/test/run-pass/import4.rs +++ b/src/test/run-pass/import4.rs @@ -16,4 +16,4 @@ mod zed { pub fn bar() { println!("bar"); } } -pub fn main() { let _zed = 42; bar(); } +pub fn main() { let _zed = 42i; bar(); } diff --git a/src/test/run-pass/inferred-suffix-in-pattern-range.rs b/src/test/run-pass/inferred-suffix-in-pattern-range.rs index b2b16c4ef84..a7b2a46f0c3 100644 --- a/src/test/run-pass/inferred-suffix-in-pattern-range.rs +++ b/src/test/run-pass/inferred-suffix-in-pattern-range.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let x = 2; + let x = 2i; let x_message = match x { 0 .. 1 => { "not many".to_string() } _ => { "lots".to_string() } diff --git a/src/test/run-pass/init-res-into-things.rs b/src/test/run-pass/init-res-into-things.rs index 5e0aeeb6bed..5d4f6458cf9 100644 --- a/src/test/run-pass/init-res-into-things.rs +++ b/src/test/run-pass/init-res-into-things.rs @@ -36,7 +36,7 @@ fn r(i: Gc<Cell<int>>) -> r { } fn test_box() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { let _a = box(GC) r(i); } @@ -44,7 +44,7 @@ fn test_box() { } fn test_rec() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { let _a = Box {x: r(i)}; } @@ -56,7 +56,7 @@ fn test_tag() { t0(r), } - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { let _a = t0(r(i)); } @@ -64,15 +64,15 @@ fn test_tag() { } fn test_tup() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { - let _a = (r(i), 0); + let _a = (r(i), 0i); } assert_eq!(i.get(), 1); } fn test_unique() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { let _a = box r(i); } @@ -80,7 +80,7 @@ fn test_unique() { } fn test_box_rec() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); { let _a = box(GC) Box { x: r(i) diff --git a/src/test/run-pass/instantiable.rs b/src/test/run-pass/instantiable.rs index 41ddce7a96e..35897d5b823 100644 --- a/src/test/run-pass/instantiable.rs +++ b/src/test/run-pass/instantiable.rs @@ -14,7 +14,7 @@ use std::ptr; // even though it would be if the nxt field had type @foo: struct foo(X); -struct X { x: uint, nxt: *foo } +struct X { x: uint, nxt: *const foo } pub fn main() { let _x = foo(X {x: 0, nxt: ptr::null()}); diff --git a/src/test/run-pass/intrinsic-atomics.rs b/src/test/run-pass/intrinsic-atomics.rs index f28ba7b8bc0..3b81943000b 100644 --- a/src/test/run-pass/intrinsic-atomics.rs +++ b/src/test/run-pass/intrinsic-atomics.rs @@ -16,8 +16,8 @@ mod rusti { pub fn atomic_cxchg_acq<T>(dst: *mut T, old: T, src: T) -> T; pub fn atomic_cxchg_rel<T>(dst: *mut T, old: T, src: T) -> T; - pub fn atomic_load<T>(src: *T) -> T; - pub fn atomic_load_acq<T>(src: *T) -> T; + pub fn atomic_load<T>(src: *const T) -> T; + pub fn atomic_load_acq<T>(src: *const T) -> T; pub fn atomic_store<T>(dst: *mut T, val: T); pub fn atomic_store_rel<T>(dst: *mut T, val: T); diff --git a/src/test/run-pass/intrinsic-move-val.rs b/src/test/run-pass/intrinsic-move-val.rs index 4375c63a1b8..f1bbf353f71 100644 --- a/src/test/run-pass/intrinsic-move-val.rs +++ b/src/test/run-pass/intrinsic-move-val.rs @@ -23,7 +23,7 @@ pub fn main() { unsafe { let x = box 1i; let mut y = rusti::init(); - let mut z: *uint = transmute(&x); + let mut z: *const uint = transmute(&x); rusti::move_val_init(&mut y, x); assert_eq!(*y, 1); assert_eq!(*z, 0); // `x` is nulled out, not directly visible diff --git a/src/test/run-pass/issue-10638.rs b/src/test/run-pass/issue-10638.rs index bc77b4c5343..a4ef77df311 100644 --- a/src/test/run-pass/issue-10638.rs +++ b/src/test/run-pass/issue-10638.rs @@ -13,6 +13,6 @@ pub fn main() { ////////////////// still not a doc comment /////**** nope, me neither */ /*** And neither am I! */ - 5; + 5i; /*****! certainly not I */ } diff --git a/src/test/run-pass/issue-11205.rs b/src/test/run-pass/issue-11205.rs new file mode 100644 index 00000000000..5b52bc34d2b --- /dev/null +++ b/src/test/run-pass/issue-11205.rs @@ -0,0 +1,92 @@ +// 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. + +#![allow(dead_code)] + +trait Foo {} +impl Foo for int {} +fn foo(_: [&Foo, ..2]) {} +fn foos(_: &[&Foo]) {} +fn foog<T>(_: &[T], _: &[T]) {} + +fn bar(_: [Box<Foo>, ..2]) {} +fn bars(_: &[Box<Foo>]) {} + +fn main() { + let x: [&Foo, ..2] = [&1i, &2i]; + foo(x); + foo([&1i, &2i]); + + let r = &1i; + let x: [&Foo, ..2] = [r, ..2]; + foo(x); + foo([&1i, ..2]); + + let x: &[&Foo] = &[&1i, &2i]; + foos(x); + foos(&[&1i, &2i]); + + let x: &[&Foo] = &[&1i, &2i]; + let r = &1i; + foog(x, &[r]); + + let x: [Box<Foo>, ..2] = [box 1i, box 2i]; + bar(x); + bar([box 1i, box 2i]); + + let x: &[Box<Foo>] = &[box 1i, box 2i]; + bars(x); + bars(&[box 1i, box 2i]); + + let x: &[Box<Foo>] = &[box 1i, box 2i]; + foog(x, &[box 1i]); + + struct T<'a> { + t: [&'a Foo, ..2] + } + let _n = T { + t: [&1i, &2i] + }; + let r = &1i; + let _n = T { + t: [r, ..2] + }; + let x: [&Foo, ..2] = [&1i, &2i]; + let _n = T { + t: x + }; + + struct F<'b> { + t: &'b [&'b Foo] + } + let _n = F { + t: &[&1i, &2i] + }; + let r = &1i; + let r: [&Foo, ..2] = [r, ..2]; + let _n = F { + t: r + }; + let x: [&Foo, ..2] = [&1i, &2i]; + let _n = F { + t: x + }; + + struct M<'a> { + t: &'a [Box<Foo>] + } + let _n = M { + t: &[box 1i, box 2i] + }; + let x: [Box<Foo>, ..2] = [box 1i, box 2i]; + let _n = M { + t: x + }; +} diff --git a/src/test/run-pass/issue-1257.rs b/src/test/run-pass/issue-1257.rs index 7d5bd9d6a74..ad3a050dde9 100644 --- a/src/test/run-pass/issue-1257.rs +++ b/src/test/run-pass/issue-1257.rs @@ -10,7 +10,7 @@ pub fn main () { let mut line = "".to_string(); - let mut i = 0; + let mut i = 0i; while line != "exit".to_string() { line = if i == 9 { "exit".to_string() } else { "notexit".to_string() }; i += 1; diff --git a/src/test/run-pass/issue-12684.rs b/src/test/run-pass/issue-12684.rs index 009a0783b58..37e675b52eb 100644 --- a/src/test/run-pass/issue-12684.rs +++ b/src/test/run-pass/issue-12684.rs @@ -14,7 +14,7 @@ extern crate green; extern crate rustuv; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/run-pass/issue-12699.rs b/src/test/run-pass/issue-12699.rs index 02790dab7b9..c24128f97e3 100644 --- a/src/test/run-pass/issue-12699.rs +++ b/src/test/run-pass/issue-12699.rs @@ -14,7 +14,7 @@ extern crate native; use std::io::timer; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { native::start(argc, argv, main) } diff --git a/src/test/run-pass/issue-13027.rs b/src/test/run-pass/issue-13027.rs index 8acaa889a04..e1634e44847 100644 --- a/src/test/run-pass/issue-13027.rs +++ b/src/test/run-pass/issue-13027.rs @@ -27,80 +27,80 @@ pub fn main() { } fn lit_shadow_range() { - assert_eq!(2i, match 1 { - 1 if false => 1, + assert_eq!(2i, match 1i { + 1 if false => 1i, 1..2 => 2, _ => 3 }); let x = 0i; assert_eq!(2i, match x+1 { - 0 => 0, + 0 => 0i, 1 if false => 1, 1..2 => 2, _ => 3 }); assert_eq!(2i, match val() { - 1 if false => 1, + 1 if false => 1i, 1..2 => 2, _ => 3 }); assert_eq!(2i, match CONST { - 0 => 0, + 0 => 0i, 1 if false => 1, 1..2 => 2, _ => 3 }); // value is out of the range of second arm, should match wildcard pattern - assert_eq!(3i, match 3 { - 1 if false => 1, + assert_eq!(3i, match 3i { + 1 if false => 1i, 1..2 => 2, _ => 3 }); } fn range_shadow_lit() { - assert_eq!(2i, match 1 { - 1..2 if false => 1, + assert_eq!(2i, match 1i { + 1..2 if false => 1i, 1 => 2, _ => 3 }); let x = 0i; assert_eq!(2i, match x+1 { - 0 => 0, + 0 => 0i, 1..2 if false => 1, 1 => 2, _ => 3 }); assert_eq!(2i, match val() { - 1..2 if false => 1, + 1..2 if false => 1i, 1 => 2, _ => 3 }); assert_eq!(2i, match CONST { - 0 => 0, + 0 => 0i, 1..2 if false => 1, 1 => 2, _ => 3 }); // ditto - assert_eq!(3i, match 3 { - 1..2 if false => 1, + assert_eq!(3i, match 3i { + 1..2 if false => 1i, 1 => 2, _ => 3 }); } fn range_shadow_range() { - assert_eq!(2i, match 1 { - 0..2 if false => 1, + assert_eq!(2i, match 1i { + 0..2 if false => 1i, 1..3 => 2, _ => 3, }); @@ -127,16 +127,16 @@ fn range_shadow_range() { }); // ditto - assert_eq!(3i, match 5 { - 0..2 if false => 1, + assert_eq!(3i, match 5i { + 0..2 if false => 1i, 1..3 => 2, _ => 3, }); } fn multi_pats_shadow_lit() { - assert_eq!(2i, match 1 { - 100 => 0, + assert_eq!(2i, match 1i { + 100 => 0i, 0 | 1..10 if false => 1, 1 => 2, _ => 3, @@ -144,8 +144,8 @@ fn multi_pats_shadow_lit() { } fn multi_pats_shadow_range() { - assert_eq!(2i, match 1 { - 100 => 0, + assert_eq!(2i, match 1i { + 100 => 0i, 0 | 1..10 if false => 1, 1..3 => 2, _ => 3, @@ -153,8 +153,8 @@ fn multi_pats_shadow_range() { } fn lit_shadow_multi_pats() { - assert_eq!(2i, match 1 { - 100 => 0, + assert_eq!(2i, match 1i { + 100 => 0i, 1 if false => 1, 0 | 1..10 => 2, _ => 3, @@ -162,8 +162,8 @@ fn lit_shadow_multi_pats() { } fn range_shadow_multi_pats() { - assert_eq!(2i, match 1 { - 100 => 0, + assert_eq!(2i, match 1i { + 100 => 0i, 1..3 if false => 1, 0 | 1..10 => 2, _ => 3, @@ -182,5 +182,5 @@ fn misc() { [Bar(_, pred)] if !pred => 2i, _ => 0i, }; - assert_eq!(2, r); + assert_eq!(2i, r); } diff --git a/src/test/run-pass/issue-13304.rs b/src/test/run-pass/issue-13304.rs index 37df74031ac..6ca605742ef 100644 --- a/src/test/run-pass/issue-13304.rs +++ b/src/test/run-pass/issue-13304.rs @@ -19,7 +19,7 @@ use std::io; use std::str; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/run-pass/issue-13494.rs b/src/test/run-pass/issue-13494.rs index a4f88d7c04c..d8f8b979ad0 100644 --- a/src/test/run-pass/issue-13494.rs +++ b/src/test/run-pass/issue-13494.rs @@ -16,7 +16,7 @@ extern crate rustuv; extern crate native; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } @@ -29,9 +29,9 @@ fn helper(rx: Receiver<Sender<()>>) { fn test() { let (tx, rx) = channel(); spawn(proc() { helper(rx) }); - let (snd, rcv) = channel(); + let (snd, rcv) = channel::<int>(); for _ in range(1i, 100000i) { - snd.send(1); + snd.send(1i); let (tx2, rx2) = channel(); tx.send(tx2); select! { diff --git a/src/test/run-pass/issue-14254.rs b/src/test/run-pass/issue-14254.rs index a3ead0a6685..160828d42fc 100644 --- a/src/test/run-pass/issue-14254.rs +++ b/src/test/run-pass/issue-14254.rs @@ -25,11 +25,11 @@ impl BarTy { } // If these fail, it's necessary to update middle::resolve and the cfail tests. -impl Foo for *BarTy { +impl Foo for *const BarTy { fn bar(&self) { self.baz(); BarTy::a(); - Foo::bah(None::<*BarTy>); + Foo::bah(None::<*const BarTy>); } } @@ -66,10 +66,10 @@ impl Foo for Box<BarTy> { } // If these fail, it's necessary to update middle::resolve and the cfail tests. -impl Foo for *int { +impl Foo for *const int { fn bar(&self) { self.baz(); - Foo::bah(None::<*int>); + Foo::bah(None::<*const int>); } } diff --git a/src/test/run-pass/issue-1460.rs b/src/test/run-pass/issue-1460.rs index 44465fe5f80..8176262abd9 100644 --- a/src/test/run-pass/issue-1460.rs +++ b/src/test/run-pass/issue-1460.rs @@ -10,5 +10,5 @@ pub fn main() { - {|i| if 1 == i { }}; + {|i| if 1i == i { }}; } diff --git a/src/test/run-pass/issue-15221.rs b/src/test/run-pass/issue-15221.rs new file mode 100644 index 00000000000..378fd4a222e --- /dev/null +++ b/src/test/run-pass/issue-15221.rs @@ -0,0 +1,23 @@ +// 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. + +#![feature(macro_rules)] + +macro_rules! inner ( + ($e:pat ) => ($e)) + +macro_rules! outer ( + ($e:pat ) => (inner!($e))) + +fn main() { + let outer!(g1) = 13i; + g1; +} + diff --git a/src/test/run-pass/issue-1866.rs b/src/test/run-pass/issue-1866.rs index 037c7b80cc8..10ae2749a09 100644 --- a/src/test/run-pass/issue-1866.rs +++ b/src/test/run-pass/issue-1866.rs @@ -13,7 +13,7 @@ mod a { pub mod rustrt { use super::rust_task; extern { - pub fn rust_task_is_unwinding(rt: *rust_task) -> bool; + pub fn rust_task_is_unwinding(rt: *const rust_task) -> bool; } } } @@ -23,7 +23,7 @@ mod b { pub mod rustrt { use super::rust_task; extern { - pub fn rust_task_is_unwinding(rt: *rust_task) -> bool; + pub fn rust_task_is_unwinding(rt: *const rust_task) -> bool; } } } diff --git a/src/test/run-pass/issue-2216.rs b/src/test/run-pass/issue-2216.rs index 7276b11b181..d9d4120d4f4 100644 --- a/src/test/run-pass/issue-2216.rs +++ b/src/test/run-pass/issue-2216.rs @@ -16,7 +16,7 @@ pub fn main() { 'foo: loop { 'bar: loop { 'quux: loop { - if 1 == 2 { + if 1i == 2 { break 'foo; } else { diff --git a/src/test/run-pass/issue-2383.rs b/src/test/run-pass/issue-2383.rs index 5cdda4e5548..41cf3eaf7e3 100644 --- a/src/test/run-pass/issue-2383.rs +++ b/src/test/run-pass/issue-2383.rs @@ -15,5 +15,5 @@ use std::collections::Deque; pub fn main() { let mut q = RingBuf::new(); - q.push_back(10); + q.push_back(10i); } diff --git a/src/test/run-pass/issue-2428.rs b/src/test/run-pass/issue-2428.rs index 4e73be8d84e..8c8b9d5df13 100644 --- a/src/test/run-pass/issue-2428.rs +++ b/src/test/run-pass/issue-2428.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let _foo = 100; + let _foo = 100i; static quux: int = 5; enum Stuff { diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index 5eb9453134d..b4807964d46 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -42,9 +42,9 @@ pub mod pipes { payload: Option<T> } - pub fn packet<T:Send>() -> *packet<T> { + pub fn packet<T:Send>() -> *const packet<T> { unsafe { - let p: *packet<T> = mem::transmute(box Stuff{ + let p: *const packet<T> = mem::transmute(box Stuff{ state: empty, blocked_task: None::<Task>, payload: None::<T> @@ -61,7 +61,7 @@ pub mod pipes { // We should consider moving this to ::std::unsafe, although I // suspect graydon would want us to use void pointers instead. - pub unsafe fn uniquify<T>(x: *T) -> Box<T> { + pub unsafe fn uniquify<T>(x: *const T) -> Box<T> { mem::transmute(x) } @@ -123,7 +123,7 @@ pub mod pipes { } } - pub fn sender_terminate<T:Send>(p: *packet<T>) { + pub fn sender_terminate<T:Send>(p: *const packet<T>) { let mut p = unsafe { uniquify(p) }; match swap_state_rel(&mut (*p).state, terminated) { empty | blocked => { @@ -140,7 +140,7 @@ pub mod pipes { } } - pub fn receiver_terminate<T:Send>(p: *packet<T>) { + pub fn receiver_terminate<T:Send>(p: *const packet<T>) { let mut p = unsafe { uniquify(p) }; match swap_state_rel(&mut (*p).state, terminated) { empty => { @@ -158,7 +158,7 @@ pub mod pipes { } pub struct send_packet<T> { - p: Option<*packet<T>>, + p: Option<*const packet<T>>, } #[unsafe_destructor] @@ -166,7 +166,7 @@ pub mod pipes { fn drop(&mut self) { unsafe { if self.p != None { - let self_p: &mut Option<*packet<T>> = + let self_p: &mut Option<*const packet<T>> = mem::transmute(&self.p); let p = replace(self_p, None); sender_terminate(p.unwrap()) @@ -176,19 +176,19 @@ pub mod pipes { } impl<T:Send> send_packet<T> { - pub fn unwrap(&mut self) -> *packet<T> { + pub fn unwrap(&mut self) -> *const packet<T> { replace(&mut self.p, None).unwrap() } } - pub fn send_packet<T:Send>(p: *packet<T>) -> send_packet<T> { + pub fn send_packet<T:Send>(p: *const packet<T>) -> send_packet<T> { send_packet { p: Some(p) } } pub struct recv_packet<T> { - p: Option<*packet<T>>, + p: Option<*const packet<T>>, } #[unsafe_destructor] @@ -196,7 +196,7 @@ pub mod pipes { fn drop(&mut self) { unsafe { if self.p != None { - let self_p: &mut Option<*packet<T>> = + let self_p: &mut Option<*const packet<T>> = mem::transmute(&self.p); let p = replace(self_p, None); receiver_terminate(p.unwrap()) @@ -206,12 +206,12 @@ pub mod pipes { } impl<T:Send> recv_packet<T> { - pub fn unwrap(&mut self) -> *packet<T> { + pub fn unwrap(&mut self) -> *const packet<T> { replace(&mut self.p, None).unwrap() } } - pub fn recv_packet<T:Send>(p: *packet<T>) -> recv_packet<T> { + pub fn recv_packet<T:Send>(p: *const packet<T>) -> recv_packet<T> { recv_packet { p: Some(p) } @@ -231,7 +231,7 @@ pub mod pingpong { pub fn liberate_ping(p: ping) -> ::pipes::send_packet<pong> { unsafe { - let _addr : *::pipes::send_packet<pong> = match &p { + let _addr : *const ::pipes::send_packet<pong> = match &p { &ping(ref x) => { mem::transmute(x) } }; fail!() @@ -240,7 +240,7 @@ pub mod pingpong { pub fn liberate_pong(p: pong) -> ::pipes::send_packet<ping> { unsafe { - let _addr : *::pipes::send_packet<ping> = match &p { + let _addr : *const ::pipes::send_packet<ping> = match &p { &pong(ref x) => { mem::transmute(x) } }; fail!() diff --git a/src/test/run-pass/issue-2734.rs b/src/test/run-pass/issue-2734.rs index e331173a158..11ebf014bc6 100644 --- a/src/test/run-pass/issue-2734.rs +++ b/src/test/run-pass/issue-2734.rs @@ -21,5 +21,5 @@ fn deadcode() { } pub fn main() { - let _ = perform_hax(box 42); + let _ = perform_hax(box 42i); } diff --git a/src/test/run-pass/issue-2735.rs b/src/test/run-pass/issue-2735.rs index 622b35b93ae..1a5b175cffc 100644 --- a/src/test/run-pass/issue-2735.rs +++ b/src/test/run-pass/issue-2735.rs @@ -21,5 +21,5 @@ fn deadcode() { } pub fn main() { - perform_hax(box 42); + perform_hax(box 42i); } diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index beba39602de..a0a800e0890 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -22,11 +22,11 @@ enum object { int_value(i64), } -fn lookup(table: Box<json::Object>, key: String, default: String) -> String +fn lookup(table: json::Object, key: String, default: String) -> String { match table.find(&key.to_string()) { option::Some(&json::String(ref s)) => { - (*s).to_string() + s.to_string() } option::Some(value) => { println!("{} was expected to be a string but is a {:?}", key, value); @@ -42,7 +42,7 @@ fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, { match &data { &json::Object(ref interface) => { - let name = lookup((*interface).clone(), + let name = lookup(interface.clone(), "ifDescr".to_string(), "".to_string()); let label = format!("{}-{}", managed_ip, name); diff --git a/src/test/run-pass/issue-333.rs b/src/test/run-pass/issue-333.rs index 1217f32826f..ef49d0a170f 100644 --- a/src/test/run-pass/issue-333.rs +++ b/src/test/run-pass/issue-333.rs @@ -12,4 +12,4 @@ fn quux<T>(x: T) -> T { let f = id::<T>; return f(x); } fn id<T>(x: T) -> T { return x; } -pub fn main() { assert!((quux(10) == 10)); } +pub fn main() { assert!((quux(10i) == 10i)); } diff --git a/src/test/run-pass/issue-3500.rs b/src/test/run-pass/issue-3500.rs index 99def5476f9..eb422c9a8b9 100644 --- a/src/test/run-pass/issue-3500.rs +++ b/src/test/run-pass/issue-3500.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let x = &Some(1); + let x = &Some(1i); match x { &Some(_) => (), &None => (), diff --git a/src/test/run-pass/issue-3656.rs b/src/test/run-pass/issue-3656.rs index 6d70b15c621..8fd603781ba 100644 --- a/src/test/run-pass/issue-3656.rs +++ b/src/test/run-pass/issue-3656.rs @@ -18,7 +18,7 @@ use libc::{c_uint, uint32_t, c_void}; struct KEYGEN { hash_algorithm: [c_uint, ..2], count: uint32_t, - salt: *c_void, + salt: *const c_void, salt_size: uint32_t, } diff --git a/src/test/run-pass/issue-3878.rs b/src/test/run-pass/issue-3878.rs index 1b09889c887..063b2d70301 100644 --- a/src/test/run-pass/issue-3878.rs +++ b/src/test/run-pass/issue-3878.rs @@ -11,6 +11,6 @@ #![allow(path_statement)] pub fn main() { - let y = box 1; + let y = box 1i; y; } diff --git a/src/test/run-pass/issue-4387.rs b/src/test/run-pass/issue-4387.rs index f2973256199..447bf3b4b26 100644 --- a/src/test/run-pass/issue-4387.rs +++ b/src/test/run-pass/issue-4387.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - let _foo = [0, ..2*4]; + let _foo = [0i, ..2*4]; } diff --git a/src/test/run-pass/issue-4735.rs b/src/test/run-pass/issue-4735.rs index d96568df63a..7730d75a3a9 100644 --- a/src/test/run-pass/issue-4735.rs +++ b/src/test/run-pass/issue-4735.rs @@ -15,17 +15,17 @@ extern crate libc; use std::mem::transmute; use libc::c_void; -struct NonCopyable(*c_void); +struct NonCopyable(*const c_void); impl Drop for NonCopyable { fn drop(&mut self) { let NonCopyable(p) = *self; - let _v = unsafe { transmute::<*c_void, Box<int>>(p) }; + let _v = unsafe { transmute::<*const c_void, Box<int>>(p) }; } } pub fn main() { let t = box 0; - let p = unsafe { transmute::<Box<int>, *c_void>(t) }; + let p = unsafe { transmute::<Box<int>, *const c_void>(t) }; let _z = NonCopyable(p); } diff --git a/src/test/run-pass/issue-5791.rs b/src/test/run-pass/issue-5791.rs index 1bda73a16c9..468f420624a 100644 --- a/src/test/run-pass/issue-5791.rs +++ b/src/test/run-pass/issue-5791.rs @@ -12,9 +12,9 @@ extern crate libc; extern { #[link_name = "malloc"] - fn malloc1(len: libc::c_int) -> *libc::c_void; + fn malloc1(len: libc::c_int) -> *const libc::c_void; #[link_name = "malloc"] - fn malloc2(len: libc::c_int, foo: libc::c_int) -> *libc::c_void; + fn malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void; } pub fn main () {} diff --git a/src/test/run-pass/issue-6117.rs b/src/test/run-pass/issue-6117.rs index 80727b569de..e1ecf47e926 100644 --- a/src/test/run-pass/issue-6117.rs +++ b/src/test/run-pass/issue-6117.rs @@ -15,7 +15,7 @@ use std::gc::GC; enum Either<T, U> { Left(T), Right(U) } pub fn main() { - match Left(box(GC) 17) { + match Left(box(GC) 17i) { Right(()) => {} _ => {} } diff --git a/src/test/run-pass/issue-6318.rs b/src/test/run-pass/issue-6318.rs index 4eb005f3397..6512db3b1c5 100644 --- a/src/test/run-pass/issue-6318.rs +++ b/src/test/run-pass/issue-6318.rs @@ -21,7 +21,7 @@ impl Foo for Struct {} pub fn main() { match A(box Struct as Box<Foo>) { - A(_a) => 0, + A(_a) => 0i, }; } diff --git a/src/test/run-pass/issue-6470.rs b/src/test/run-pass/issue-6470.rs index 860b23849c6..ef164150804 100644 --- a/src/test/run-pass/issue-6470.rs +++ b/src/test/run-pass/issue-6470.rs @@ -14,7 +14,7 @@ pub mod Bar { } extern { - pub fn foo(v: *Foo) -> Foo; + pub fn foo(v: *const Foo) -> Foo; } } diff --git a/src/test/run-pass/issue-8044.rs b/src/test/run-pass/issue-8044.rs index 06f41e9cb7a..e5949e23467 100644 --- a/src/test/run-pass/issue-8044.rs +++ b/src/test/run-pass/issue-8044.rs @@ -14,5 +14,5 @@ extern crate minimal = "issue-8044"; use minimal::{BTree, leaf}; pub fn main() { - BTree::<int> { node: leaf(1) }; + BTree::<int> { node: leaf(1i) }; } diff --git a/src/test/run-pass/issue-8498.rs b/src/test/run-pass/issue-8498.rs index 770de8f5346..e4f4db6ea63 100644 --- a/src/test/run-pass/issue-8498.rs +++ b/src/test/run-pass/issue-8498.rs @@ -9,14 +9,14 @@ // except according to those terms. pub fn main() { - match &[(box 5,box 7)] { + match &[(box 5i,box 7i)] { ps => { let (ref y, _) = ps[0]; assert!(**y == 5); } } - match Some(&[(box 5,)]) { + match Some(&[(box 5i,)]) { Some(ps) => { let (ref y,) = ps[0]; assert!(**y == 5); @@ -24,7 +24,7 @@ pub fn main() { None => () } - match Some(&[(box 5,box 7)]) { + match Some(&[(box 5i,box 7i)]) { Some(ps) => { let (ref y, ref z) = ps[0]; assert!(**y == 5); diff --git a/src/test/run-pass/issue-868.rs b/src/test/run-pass/issue-868.rs index 12dcc4ecd2c..99ab83ec620 100644 --- a/src/test/run-pass/issue-868.rs +++ b/src/test/run-pass/issue-868.rs @@ -11,7 +11,7 @@ fn f<T>(g: || -> T) -> T { g() } pub fn main() { - let _x = f( | | { 10 }); + let _x = f( | | { 10i }); // used to be: cannot determine a type for this expression f(| | { }); // ditto diff --git a/src/test/run-pass/issue-8851.rs b/src/test/run-pass/issue-8851.rs index 62970369579..21037120569 100644 --- a/src/test/run-pass/issue-8851.rs +++ b/src/test/run-pass/issue-8851.rs @@ -10,23 +10,28 @@ #![feature(macro_rules)] +// after fixing #9384 and implementing hygiene for match bindings, +// this now fails because the insertion of the 'y' into the match +// doesn't cause capture. Making this macro hygienic (as I've done) +// could very well make this test case completely pointless.... + enum T { A(int), B(uint) } macro_rules! test( - ($e:expr) => ( + ($id:ident, $e:expr) => ( fn foo(t: T) -> int { match t { - A(y) => $e, - B(y) => $e + A($id) => $e, + B($id) => $e } } ) ) -test!(10 + (y as int)) +test!(y, 10 + (y as int)) pub fn main() { foo(A(20)); diff --git a/src/test/run-pass/issue-8860.rs b/src/test/run-pass/issue-8860.rs index c665c1da3fc..d775f23bab4 100644 --- a/src/test/run-pass/issue-8860.rs +++ b/src/test/run-pass/issue-8860.rs @@ -16,7 +16,7 @@ static mut DROP_S: int = 0i; static mut DROP_T: int = 0i; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { let ret = green::start(argc, argv, green::basic::event_loop, main); unsafe { assert_eq!(2, DROP); diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index 84e9de9b924..e787962bb81 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -19,7 +19,7 @@ fn assert_repr_eq<T>(obj : T, expected : String) { } pub fn main() { - let abc = [1, 2, 3]; + let abc = [1i, 2, 3]; let tf = [true, false]; let x = [(), ()]; let slice = x.slice(0,1); diff --git a/src/test/run-pass/issue-8983.rs b/src/test/run-pass/issue-8983.rs index 9f6b281810e..2fb96f593ef 100644 --- a/src/test/run-pass/issue-8983.rs +++ b/src/test/run-pass/issue-8983.rs @@ -16,6 +16,6 @@ fn main() { fn f(_: proc()) {} fn eat<T>(_: T) {} - let x = box(GC) 1; + let x = box(GC) 1i; f(proc() { eat(x) }); } diff --git a/src/test/run-pass/issue-9906.rs b/src/test/run-pass/issue-9906.rs index 6b8e250ea74..dd12ea8b765 100644 --- a/src/test/run-pass/issue-9906.rs +++ b/src/test/run-pass/issue-9906.rs @@ -14,5 +14,5 @@ extern crate testmod = "issue-9906"; pub fn main() { testmod::foo(); - testmod::FooBar::new(1); + testmod::FooBar::new(1i); } diff --git a/src/test/run-pass/issue-9942.rs b/src/test/run-pass/issue-9942.rs index 7864f4fbdd6..aa86f488906 100644 --- a/src/test/run-pass/issue-9942.rs +++ b/src/test/run-pass/issue-9942.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - static S: uint = 23 as uint; [0, ..S]; () + static S: uint = 23 as uint; [0i, ..S]; () } diff --git a/src/test/run-pass/keyword-changes-2012-07-31.rs b/src/test/run-pass/keyword-changes-2012-07-31.rs index ff568b77f08..885f266ca3d 100644 --- a/src/test/run-pass/keyword-changes-2012-07-31.rs +++ b/src/test/run-pass/keyword-changes-2012-07-31.rs @@ -19,7 +19,7 @@ mod foo { } fn bar() -> int { - match 0 { - _ => { 0 } + match 0i { + _ => { 0i } } } diff --git a/src/test/run-pass/lang-item-public.rs b/src/test/run-pass/lang-item-public.rs index 23e48b97427..6330e1bf3c1 100644 --- a/src/test/run-pass/lang-item-public.rs +++ b/src/test/run-pass/lang-item-public.rs @@ -33,6 +33,6 @@ extern {} extern {} #[start] -fn main(_: int, _: **u8) -> int { +fn main(_: int, _: *const *const u8) -> int { 1 % 1 } diff --git a/src/test/run-pass/lazy-and-or.rs b/src/test/run-pass/lazy-and-or.rs index c4f37ccf88a..366b3c41328 100644 --- a/src/test/run-pass/lazy-and-or.rs +++ b/src/test/run-pass/lazy-and-or.rs @@ -13,7 +13,7 @@ extern crate debug; fn incr(x: &mut int) -> bool { *x += 1; assert!((false)); return false; } pub fn main() { - let x = 1 == 2 || 3 == 3; + let x = 1i == 2 || 3i == 3; assert!((x)); let mut y: int = 10; println!("{:?}", x || incr(&mut y)); diff --git a/src/test/run-pass/lazy-init.rs b/src/test/run-pass/lazy-init.rs index 60f7689ecfa..cd8be550d51 100644 --- a/src/test/run-pass/lazy-init.rs +++ b/src/test/run-pass/lazy-init.rs @@ -12,4 +12,4 @@ fn foo(x: int) { println!("{}", x); } -pub fn main() { let mut x: int; if 1 > 2 { x = 12; } else { x = 10; } foo(x); } +pub fn main() { let mut x: int; if 1i > 2 { x = 12; } else { x = 10; } foo(x); } diff --git a/src/test/run-pass/linear-for-loop.rs b/src/test/run-pass/linear-for-loop.rs index 640ed3883eb..e9e2a753469 100644 --- a/src/test/run-pass/linear-for-loop.rs +++ b/src/test/run-pass/linear-for-loop.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 extern crate debug; diff --git a/src/test/run-pass/linkage1.rs b/src/test/run-pass/linkage1.rs index 2eafd34afca..2ab1e911180 100644 --- a/src/test/run-pass/linkage1.rs +++ b/src/test/run-pass/linkage1.rs @@ -19,7 +19,7 @@ extern crate other = "linkage1"; extern { #[linkage = "extern_weak"] - static foo: *int; + static foo: *const int; #[linkage = "extern_weak"] static something_that_should_never_exist: *mut int; } diff --git a/src/test/run-pass/long-while.rs b/src/test/run-pass/long-while.rs index cbe26844708..7d30b22867c 100644 --- a/src/test/run-pass/long-while.rs +++ b/src/test/run-pass/long-while.rs @@ -14,6 +14,6 @@ pub fn main() { let mut i: int = 0; while i < 1000000 { i += 1; - let x = 3; + let x = 3i; } } diff --git a/src/test/run-pass/loop-diverges.rs b/src/test/run-pass/loop-diverges.rs index 9c46ba2cb9b..4fe73188b45 100644 --- a/src/test/run-pass/loop-diverges.rs +++ b/src/test/run-pass/loop-diverges.rs @@ -16,5 +16,5 @@ fn forever() -> ! { } pub fn main() { - if (1 == 2) { forever(); } + if (1i == 2) { forever(); } } diff --git a/src/test/run-pass/loop-label-shadowing.rs b/src/test/run-pass/loop-label-shadowing.rs index cfe51fe7758..46d4fa460fe 100644 --- a/src/test/run-pass/loop-label-shadowing.rs +++ b/src/test/run-pass/loop-label-shadowing.rs @@ -12,7 +12,7 @@ fn main() { let mut foo = Vec::new(); - 'foo: for i in [1, 2, 3].iter() { + 'foo: for i in [1i, 2, 3].iter() { foo.push(i); } } diff --git a/src/test/run-pass/loop-no-reinit-needed-post-bot.rs b/src/test/run-pass/loop-no-reinit-needed-post-bot.rs index 8b775002250..14aee4c3be8 100644 --- a/src/test/run-pass/loop-no-reinit-needed-post-bot.rs +++ b/src/test/run-pass/loop-no-reinit-needed-post-bot.rs @@ -17,7 +17,7 @@ fn my_fail() -> ! { loop {} } pub fn step(f: bool) { let mut g = S; - let mut i = 0; + let mut i = 0i; loop { if i > 10 { break; } else { i += 1; } diff --git a/src/test/run-pass/match-bot-2.rs b/src/test/run-pass/match-bot-2.rs index ba897bd92c0..f3c299bd1f9 100644 --- a/src/test/run-pass/match-bot-2.rs +++ b/src/test/run-pass/match-bot-2.rs @@ -9,5 +9,5 @@ // except according to those terms. // n.b. This was only ever failing with optimization disabled. -fn a() -> int { match return 1 { 2 => 3, _ => fail!() } } +fn a() -> int { match return 1i { 2i => 3i, _ => fail!() } } pub fn main() { a(); } diff --git a/src/test/run-pass/match-naked-record-expr.rs b/src/test/run-pass/match-naked-record-expr.rs index 433cf23626b..170a3513a1a 100644 --- a/src/test/run-pass/match-naked-record-expr.rs +++ b/src/test/run-pass/match-naked-record-expr.rs @@ -11,7 +11,7 @@ struct X { x: int } pub fn main() { - let _x = match 0 { + let _x = match 0i { _ => X { x: 0 }.x diff --git a/src/test/run-pass/match-naked-record.rs b/src/test/run-pass/match-naked-record.rs index fe12b7c1585..21c31b62183 100644 --- a/src/test/run-pass/match-naked-record.rs +++ b/src/test/run-pass/match-naked-record.rs @@ -11,7 +11,7 @@ struct X { x: int } pub fn main() { - let _x = match 0 { + let _x = match 0i { _ => X { x: 0 } diff --git a/src/test/run-pass/match-pipe-binding.rs b/src/test/run-pass/match-pipe-binding.rs index 52d966a12d7..2169e996577 100644 --- a/src/test/run-pass/match-pipe-binding.rs +++ b/src/test/run-pass/match-pipe-binding.rs @@ -10,7 +10,7 @@ fn test1() { // from issue 6338 - match ((1, "a".to_string()), (2, "b".to_string())) { + match ((1i, "a".to_string()), (2i, "b".to_string())) { ((1, a), (2, b)) | ((2, b), (1, a)) => { assert_eq!(a, "a".to_string()); assert_eq!(b, "b".to_string()); diff --git a/src/test/run-pass/match-range.rs b/src/test/run-pass/match-range.rs index 6b02b21a084..7421ae95884 100644 --- a/src/test/run-pass/match-range.rs +++ b/src/test/run-pass/match-range.rs @@ -26,15 +26,15 @@ pub fn main() { 'a'..'z' => {} _ => fail!("should suppport char ranges") } - match -3 { + match -3i { -7..5 => {} _ => fail!("should match signed range") } - match 3.0 { + match 3.0f64 { 1.0..5.0 => {} _ => fail!("should match float range") } - match -1.5 { + match -1.5f64 { -3.6..3.6 => {} _ => fail!("should match negative float range") } diff --git a/src/test/run-pass/multi-let.rs b/src/test/run-pass/multi-let.rs index eb1444be378..201abeba073 100644 --- a/src/test/run-pass/multi-let.rs +++ b/src/test/run-pass/multi-let.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let x = 10; + let x = 10i; let y = x; assert!((y == 10)); } diff --git a/src/test/run-pass/native-always-waits.rs b/src/test/run-pass/native-always-waits.rs index 94a4308ab08..ea3eb299648 100644 --- a/src/test/run-pass/native-always-waits.rs +++ b/src/test/run-pass/native-always-waits.rs @@ -15,7 +15,7 @@ extern crate native; static mut set: bool = false; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { // make sure that native::start always waits for all children to finish native::start(argc, argv, proc() { spawn(proc() { diff --git a/src/test/run-pass/native-print-no-runtime.rs b/src/test/run-pass/native-print-no-runtime.rs index bf1a97f84b6..a7937efd66f 100644 --- a/src/test/run-pass/native-print-no-runtime.rs +++ b/src/test/run-pass/native-print-no-runtime.rs @@ -10,7 +10,7 @@ #[start] -pub fn main(_: int, _: **u8) -> int { +pub fn main(_: int, _: *const *const u8) -> int { println!("hello"); 0 } diff --git a/src/test/run-pass/negative.rs b/src/test/run-pass/negative.rs index d92496c4b7b..148c1c9f0cf 100644 --- a/src/test/run-pass/negative.rs +++ b/src/test/run-pass/negative.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - match -5 { + match -5i { -5 => {} _ => { fail!() } } diff --git a/src/test/run-pass/new-box-syntax.rs b/src/test/run-pass/new-box-syntax.rs index 0150120e1db..b16bef3fc99 100644 --- a/src/test/run-pass/new-box-syntax.rs +++ b/src/test/run-pass/new-box-syntax.rs @@ -22,15 +22,15 @@ struct Structure { } pub fn main() { - let x: Box<int> = box(HEAP) 2; - let y: Box<int> = box 2; - let z: Gc<int> = box(GC) 2; + let x: Box<int> = box(HEAP) 2i; + let y: Box<int> = box 2i; + let z: Gc<int> = box(GC) 2i; let a: Gc<Structure> = box(GC) Structure { x: 10, y: 20, }; - let b: Box<int> = box()(1 + 2); - let c = box()(3 + 4); - let d = box(GC)(5 + 6); + let b: Box<int> = box()(1i + 2); + let c = box()(3i + 4); + let d = box(GC)(5i + 6); } diff --git a/src/test/run-pass/operator-associativity.rs b/src/test/run-pass/operator-associativity.rs index bee6d23a27d..8d45b8ecb08 100644 --- a/src/test/run-pass/operator-associativity.rs +++ b/src/test/run-pass/operator-associativity.rs @@ -12,4 +12,4 @@ // Testcase for issue #130, operator associativity. -pub fn main() { assert!((3 * 5 / 2 == 7)); } +pub fn main() { assert!((3i * 5i / 2i == 7i)); } diff --git a/src/test/run-pass/out-of-stack.rs b/src/test/run-pass/out-of-stack.rs index 1566b9ed6f1..19d1635a9a5 100644 --- a/src/test/run-pass/out-of-stack.rs +++ b/src/test/run-pass/out-of-stack.rs @@ -21,7 +21,7 @@ use std::str; pub fn black_box<T>(dummy: T) { unsafe { asm!("" : : "r"(&dummy)) } } fn silent_recurse() { - let buf = [0, ..1000]; + let buf = [0i, ..1000]; black_box(buf); silent_recurse(); } diff --git a/src/test/run-pass/owned-implies-static.rs b/src/test/run-pass/owned-implies-static.rs index d1e9fb270d7..498b81d307e 100644 --- a/src/test/run-pass/owned-implies-static.rs +++ b/src/test/run-pass/owned-implies-static.rs @@ -11,5 +11,5 @@ fn f<T: 'static>(_x: T) {} pub fn main() { - f(box 5); + f(box 5i); } diff --git a/src/test/run-pass/paren-free.rs b/src/test/run-pass/paren-free.rs index d9669812d2a..569023c4439 100644 --- a/src/test/run-pass/paren-free.rs +++ b/src/test/run-pass/paren-free.rs @@ -10,6 +10,6 @@ pub fn main() { let x = true; - if x { let mut i = 10; while i > 0 { i -= 1; } } + if x { let mut i = 10i; while i > 0 { i -= 1; } } match x { true => { println!("right"); } false => { println!("wrong"); } } } diff --git a/src/test/run-pass/process-detach.rs b/src/test/run-pass/process-detach.rs index 44ff58c151e..69ff9fca6ce 100644 --- a/src/test/run-pass/process-detach.rs +++ b/src/test/run-pass/process-detach.rs @@ -28,7 +28,7 @@ use std::io::process::Command; use std::io::signal::{Listener, Interrupt}; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/run-pass/pub-extern-privacy.rs b/src/test/run-pass/pub-extern-privacy.rs index 26bf06794ca..16f5a06b886 100644 --- a/src/test/run-pass/pub-extern-privacy.rs +++ b/src/test/run-pass/pub-extern-privacy.rs @@ -12,12 +12,12 @@ use std::mem::transmute; mod a { extern { - pub fn free(x: *u8); + pub fn free(x: *const u8); } } pub fn main() { unsafe { - a::free(transmute(0)); + a::free(transmute(0u)); } } diff --git a/src/test/run-pass/reflect-visit-type.rs b/src/test/run-pass/reflect-visit-type.rs index 9757db9df4c..a8a9afc6156 100644 --- a/src/test/run-pass/reflect-visit-type.rs +++ b/src/test/run-pass/reflect-visit-type.rs @@ -66,44 +66,44 @@ impl TyVisitor for MyVisitor { _sz: uint, _sz2: uint, _align: uint) -> bool { true } - fn visit_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } - fn visit_uniq(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } - fn visit_ptr(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } - fn visit_rptr(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } + fn visit_box(&mut self, _mtbl: uint, _inner: *const TyDesc) -> bool { true } + fn visit_uniq(&mut self, _mtbl: uint, _inner: *const TyDesc) -> bool { true } + fn visit_ptr(&mut self, _mtbl: uint, _inner: *const TyDesc) -> bool { true } + fn visit_rptr(&mut self, _mtbl: uint, _inner: *const TyDesc) -> bool { true } - fn visit_evec_slice(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true } + fn visit_evec_slice(&mut self, _mtbl: uint, _inner: *const TyDesc) -> bool { true } fn visit_evec_fixed(&mut self, _n: uint, _sz: uint, _align: uint, - _mtbl: uint, _inner: *TyDesc) -> bool { true } + _mtbl: uint, _inner: *const TyDesc) -> bool { true } fn visit_enter_rec(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_rec_field(&mut self, _i: uint, _name: &str, - _mtbl: uint, _inner: *TyDesc) -> bool { true } + _mtbl: uint, _inner: *const TyDesc) -> bool { true } fn visit_leave_rec(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_class(&mut self, _name: &str, _named_fields: bool, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_class_field(&mut self, _i: uint, _name: &str, _named: bool, - _mtbl: uint, _inner: *TyDesc) -> bool { true } + _mtbl: uint, _inner: *const TyDesc) -> bool { true } fn visit_leave_class(&mut self, _name: &str, _named_fields: bool, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_tup(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } - fn visit_tup_field(&mut self, _i: uint, _inner: *TyDesc) -> bool { true } + fn visit_tup_field(&mut self, _i: uint, _inner: *const TyDesc) -> bool { true } fn visit_leave_tup(&mut self, _n_fields: uint, _sz: uint, _align: uint) -> bool { true } fn visit_enter_enum(&mut self, _n_variants: uint, - _get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + _get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, _sz: uint, _align: uint) -> bool { true } fn visit_enter_enum_variant(&mut self, _variant: uint, _disr_val: Disr, _n_fields: uint, _name: &str) -> bool { true } - fn visit_enum_variant_field(&mut self, _i: uint, _offset: uint, _inner: *TyDesc) + fn visit_enum_variant_field(&mut self, _i: uint, _offset: uint, _inner: *const TyDesc) -> bool { true } fn visit_leave_enum_variant(&mut self, _variant: uint, @@ -112,13 +112,13 @@ impl TyVisitor for MyVisitor { _name: &str) -> bool { true } fn visit_leave_enum(&mut self, _n_variants: uint, - _get_disr: unsafe extern fn(ptr: *Opaque) -> Disr, + _get_disr: unsafe extern fn(ptr: *const Opaque) -> Disr, _sz: uint, _align: uint) -> bool { true } fn visit_enter_fn(&mut self, _purity: uint, _proto: uint, _n_inputs: uint, _retstyle: uint) -> bool { true } - fn visit_fn_input(&mut self, _i: uint, _mode: uint, _inner: *TyDesc) -> bool { true } - fn visit_fn_output(&mut self, _retstyle: uint, _variadic: bool, _inner: *TyDesc) + fn visit_fn_input(&mut self, _i: uint, _mode: uint, _inner: *const TyDesc) -> bool { true } + fn visit_fn_output(&mut self, _retstyle: uint, _variadic: bool, _inner: *const TyDesc) -> bool { true } fn visit_leave_fn(&mut self, _purity: uint, _proto: uint, _n_inputs: uint, _retstyle: uint) -> bool { true } diff --git a/src/test/run-pass/regions-infer-borrow-scope-view.rs b/src/test/run-pass/regions-infer-borrow-scope-view.rs index 1342c2e77f2..13200d619d0 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-view.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-view.rs @@ -12,7 +12,7 @@ fn view<'r, T>(x: &'r [T]) -> &'r [T] {x} pub fn main() { - let v = vec!(1, 2, 3); + let v = vec!(1i, 2, 3); let x = view(v.as_slice()); let y = view(x.as_slice()); assert!((*v.get(0) == x[0]) && (*v.get(0) == y[0])); diff --git a/src/test/run-pass/rename-directory.rs b/src/test/run-pass/rename-directory.rs index bf7a8fabff3..e0609782a0a 100644 --- a/src/test/run-pass/rename-directory.rs +++ b/src/test/run-pass/rename-directory.rs @@ -37,7 +37,7 @@ fn rename_directory() { assert!((ostream as uint != 0u)); let s = "hello".to_string(); "hello".with_c_str(|buf| { - let write_len = libc::fwrite(buf as *libc::c_void, + let write_len = libc::fwrite(buf as *const libc::c_void, 1u as libc::size_t, (s.len() + 1u) as libc::size_t, ostream); diff --git a/src/test/run-pass/resource-assign-is-not-copy.rs b/src/test/run-pass/resource-assign-is-not-copy.rs index dc6dac15bb2..9dc3b7a0f80 100644 --- a/src/test/run-pass/resource-assign-is-not-copy.rs +++ b/src/test/run-pass/resource-assign-is-not-copy.rs @@ -33,11 +33,11 @@ fn r(i: Gc<Cell<int>>) -> r { } pub fn main() { - let i = box(GC) Cell::new(0); + let i = box(GC) Cell::new(0i); // Even though these look like copies, they are guaranteed not to be { let a = r(i); - let b = (a, 10); + let b = (a, 10i); let (c, _d) = b; println!("{:?}", c); } diff --git a/src/test/run-pass/running-with-no-runtime.rs b/src/test/run-pass/running-with-no-runtime.rs index 0ef48c99782..44435dc2398 100644 --- a/src/test/run-pass/running-with-no-runtime.rs +++ b/src/test/run-pass/running-with-no-runtime.rs @@ -18,7 +18,7 @@ use std::rt::unwind::try; local_data_key!(foo: int) #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { if argc > 1 { unsafe { match **argv.offset(1) { diff --git a/src/test/run-pass/self-re-assign.rs b/src/test/run-pass/self-re-assign.rs index e613a83737e..75fb98f8e24 100644 --- a/src/test/run-pass/self-re-assign.rs +++ b/src/test/run-pass/self-re-assign.rs @@ -14,11 +14,11 @@ use std::rc::Rc; pub fn main() { - let mut x = box 3; + let mut x = box 3i; x = x; assert!(*x == 3); - let mut x = Rc::new(3); + let mut x = Rc::new(3i); x = x; assert!(*x == 3); } diff --git a/src/test/run-pass/shadow.rs b/src/test/run-pass/shadow.rs index a65e44166e9..96a12494b2f 100644 --- a/src/test/run-pass/shadow.rs +++ b/src/test/run-pass/shadow.rs @@ -19,7 +19,7 @@ fn foo(c: Vec<int> ) { some::<int>(_) => { for _i in c.iter() { println!("{:?}", a); - let a = 17; + let a = 17i; b.push(a); } } @@ -29,4 +29,4 @@ fn foo(c: Vec<int> ) { enum t<T> { none, some(T), } -pub fn main() { let x = 10; let x = x + 20; assert!((x == 30)); foo(Vec::new()); } +pub fn main() { let x = 10i; let x = x + 20; assert!((x == 30)); foo(Vec::new()); } diff --git a/src/test/run-pass/smallest-hello-world.rs b/src/test/run-pass/smallest-hello-world.rs index bdba5aa9cfe..4f1a3817fab 100644 --- a/src/test/run-pass/smallest-hello-world.rs +++ b/src/test/run-pass/smallest-hello-world.rs @@ -17,7 +17,7 @@ extern crate libc; -extern { fn puts(s: *u8); } +extern { fn puts(s: *const u8); } extern "rust-intrinsic" { fn transmute<T, U>(t: T) -> U; } #[lang = "stack_exhausted"] extern fn stack_exhausted() {} @@ -25,9 +25,9 @@ extern "rust-intrinsic" { fn transmute<T, U>(t: T) -> U; } #[start] #[no_split_stack] -fn main(_: int, _: **u8) -> int { +fn main(_: int, _: *const *const u8) -> int { unsafe { - let (ptr, _): (*u8, uint) = transmute("Hello!\0"); + let (ptr, _): (*const u8, uint) = transmute("Hello!\0"); puts(ptr); } return 0; diff --git a/src/test/run-pass/stable-addr-of.rs b/src/test/run-pass/stable-addr-of.rs index 083d2e167a0..515198f7a71 100644 --- a/src/test/run-pass/stable-addr-of.rs +++ b/src/test/run-pass/stable-addr-of.rs @@ -12,5 +12,5 @@ pub fn main() { let foo = 1; - assert_eq!(&foo as *int, &foo as *int); + assert_eq!(&foo as *const int, &foo as *const int); } diff --git a/src/test/run-pass/static-assert.rs b/src/test/run-pass/static-assert.rs index f8fd81b9365..c695fa2b72e 100644 --- a/src/test/run-pass/static-assert.rs +++ b/src/test/run-pass/static-assert.rs @@ -12,13 +12,13 @@ static b: bool = true; #[static_assert] -static c: bool = 1 == 1; +static c: bool = 1i == 1; #[static_assert] -static d: bool = 1 != 2; +static d: bool = 1i != 2; #[static_assert] -static f: bool = (4/2) == 2; +static f: bool = (4i/2) == 2; pub fn main() { } diff --git a/src/test/run-pass/str-concat.rs b/src/test/run-pass/str-concat.rs index 7141d0b9df5..ad0d2f11abd 100644 --- a/src/test/run-pass/str-concat.rs +++ b/src/test/run-pass/str-concat.rs @@ -16,5 +16,5 @@ pub fn main() { let b: String = "world".to_string(); let s: String = format!("{}{}", a, b); println!("{}", s.clone()); - assert_eq!(s.as_slice()[9], 'd' as u8); + assert_eq!(s.as_bytes()[9], 'd' as u8); } diff --git a/src/test/run-pass/string-self-append.rs b/src/test/run-pass/string-self-append.rs index 612483f6909..dc1e23ca09c 100644 --- a/src/test/run-pass/string-self-append.rs +++ b/src/test/run-pass/string-self-append.rs @@ -11,7 +11,7 @@ pub fn main() { // Make sure we properly handle repeated self-appends. let mut a: String = "A".to_string(); - let mut i = 20; + let mut i = 20i; let mut expected_len = 1u; while i > 0 { println!("{}", a.len()); diff --git a/src/test/run-pass/supported-cast.rs b/src/test/run-pass/supported-cast.rs index b87535713a7..2757439828d 100644 --- a/src/test/run-pass/supported-cast.rs +++ b/src/test/run-pass/supported-cast.rs @@ -11,7 +11,7 @@ extern crate libc; pub fn main() { - let f = 1 as *libc::FILE; + let f = 1u as *const libc::FILE; println!("{}", f as int); println!("{}", f as uint); println!("{}", f as i8); @@ -25,7 +25,7 @@ pub fn main() { println!("{}", 1 as int); println!("{}", 1 as uint); - println!("{}", 1 as *libc::FILE); + println!("{}", 1 as *const libc::FILE); println!("{}", 1 as i8); println!("{}", 1 as i16); println!("{}", 1 as i32); @@ -34,12 +34,12 @@ pub fn main() { println!("{}", 1 as u16); println!("{}", 1 as u32); println!("{}", 1 as u64); - println!("{}", 1 as f32); - println!("{}", 1 as f64); + println!("{}", 1i as f32); + println!("{}", 1i as f64); println!("{}", 1u as int); println!("{}", 1u as uint); - println!("{}", 1u as *libc::FILE); + println!("{}", 1u as *const libc::FILE); println!("{}", 1u as i8); println!("{}", 1u as i16); println!("{}", 1u as i32); @@ -53,7 +53,7 @@ pub fn main() { println!("{}", 1i8 as int); println!("{}", 1i8 as uint); - println!("{}", 1i8 as *libc::FILE); + println!("{}", 1i8 as *const libc::FILE); println!("{}", 1i8 as i8); println!("{}", 1i8 as i16); println!("{}", 1i8 as i32); @@ -67,7 +67,7 @@ pub fn main() { println!("{}", 1u8 as int); println!("{}", 1u8 as uint); - println!("{}", 1u8 as *libc::FILE); + println!("{}", 1u8 as *const libc::FILE); println!("{}", 1u8 as i8); println!("{}", 1u8 as i16); println!("{}", 1u8 as i32); @@ -81,7 +81,7 @@ pub fn main() { println!("{}", 1i16 as int); println!("{}", 1i16 as uint); - println!("{}", 1i16 as *libc::FILE); + println!("{}", 1i16 as *const libc::FILE); println!("{}", 1i16 as i8); println!("{}", 1i16 as i16); println!("{}", 1i16 as i32); @@ -95,7 +95,7 @@ pub fn main() { println!("{}", 1u16 as int); println!("{}", 1u16 as uint); - println!("{}", 1u16 as *libc::FILE); + println!("{}", 1u16 as *const libc::FILE); println!("{}", 1u16 as i8); println!("{}", 1u16 as i16); println!("{}", 1u16 as i32); @@ -109,7 +109,7 @@ pub fn main() { println!("{}", 1i32 as int); println!("{}", 1i32 as uint); - println!("{}", 1i32 as *libc::FILE); + println!("{}", 1i32 as *const libc::FILE); println!("{}", 1i32 as i8); println!("{}", 1i32 as i16); println!("{}", 1i32 as i32); @@ -123,7 +123,7 @@ pub fn main() { println!("{}", 1u32 as int); println!("{}", 1u32 as uint); - println!("{}", 1u32 as *libc::FILE); + println!("{}", 1u32 as *const libc::FILE); println!("{}", 1u32 as i8); println!("{}", 1u32 as i16); println!("{}", 1u32 as i32); @@ -137,7 +137,7 @@ pub fn main() { println!("{}", 1i64 as int); println!("{}", 1i64 as uint); - println!("{}", 1i64 as *libc::FILE); + println!("{}", 1i64 as *const libc::FILE); println!("{}", 1i64 as i8); println!("{}", 1i64 as i16); println!("{}", 1i64 as i32); @@ -151,7 +151,7 @@ pub fn main() { println!("{}", 1u64 as int); println!("{}", 1u64 as uint); - println!("{}", 1u64 as *libc::FILE); + println!("{}", 1u64 as *const libc::FILE); println!("{}", 1u64 as i8); println!("{}", 1u64 as i16); println!("{}", 1u64 as i32); @@ -165,7 +165,7 @@ pub fn main() { println!("{}", 1u64 as int); println!("{}", 1u64 as uint); - println!("{}", 1u64 as *libc::FILE); + println!("{}", 1u64 as *const libc::FILE); println!("{}", 1u64 as i8); println!("{}", 1u64 as i16); println!("{}", 1u64 as i32); @@ -179,7 +179,7 @@ pub fn main() { println!("{}", true as int); println!("{}", true as uint); - println!("{}", true as *libc::FILE); + println!("{}", true as *const libc::FILE); println!("{}", true as i8); println!("{}", true as i16); println!("{}", true as i32); @@ -191,19 +191,6 @@ pub fn main() { println!("{}", true as f32); println!("{}", true as f64); - println!("{}", 1. as int); - println!("{}", 1. as uint); - println!("{}", 1. as i8); - println!("{}", 1. as i16); - println!("{}", 1. as i32); - println!("{}", 1. as i64); - println!("{}", 1. as u8); - println!("{}", 1. as u16); - println!("{}", 1. as u32); - println!("{}", 1. as u64); - println!("{}", 1. as f32); - println!("{}", 1. as f64); - println!("{}", 1f32 as int); println!("{}", 1f32 as uint); println!("{}", 1f32 as i8); diff --git a/src/test/run-pass/swap-1.rs b/src/test/run-pass/swap-1.rs index 82a76512e08..9a77356d7eb 100644 --- a/src/test/run-pass/swap-1.rs +++ b/src/test/run-pass/swap-1.rs @@ -11,7 +11,7 @@ use std::mem::swap; pub fn main() { - let mut x = 3; let mut y = 7; + let mut x = 3i; let mut y = 7i; swap(&mut x, &mut y); assert!((x == 7)); assert!((y == 3)); } diff --git a/src/test/run-pass/tag-variant-disr-type-mismatch.rs b/src/test/run-pass/tag-variant-disr-type-mismatch.rs index 3d63acd5b83..c04751d51b4 100644 --- a/src/test/run-pass/tag-variant-disr-type-mismatch.rs +++ b/src/test/run-pass/tag-variant-disr-type-mismatch.rs @@ -9,7 +9,7 @@ // except according to those terms. enum color { - red = 1u, + red = 1i, blue = 2, } diff --git a/src/test/run-pass/task-comm-12.rs b/src/test/run-pass/task-comm-12.rs index 851f87adfc2..f72c0ef8d7b 100644 --- a/src/test/run-pass/task-comm-12.rs +++ b/src/test/run-pass/task-comm-12.rs @@ -21,7 +21,7 @@ fn test00() { }); // Sleep long enough for the task to finish. - let mut i = 0; + let mut i = 0u; while i < 10000 { task::deschedule(); i += 1; diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index 9263cd1d485..d45e7a20c3b 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -39,10 +39,10 @@ fn test_str() { let s0 = "test".to_string(); tx.send(s0); let s1 = rx.recv(); - assert_eq!(s1.as_slice()[0], 't' as u8); - assert_eq!(s1.as_slice()[1], 'e' as u8); - assert_eq!(s1.as_slice()[2], 's' as u8); - assert_eq!(s1.as_slice()[3], 't' as u8); + assert_eq!(s1.as_bytes()[0], 't' as u8); + assert_eq!(s1.as_bytes()[1], 'e' as u8); + assert_eq!(s1.as_bytes()[2], 's' as u8); + assert_eq!(s1.as_bytes()[3], 't' as u8); } #[deriving(Show)] diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index 1c14153a110..afeb9125fe6 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 extern crate debug; diff --git a/src/test/run-pass/task-spawn-move-and-copy.rs b/src/test/run-pass/task-spawn-move-and-copy.rs index cf6c2754829..fafb9412c01 100644 --- a/src/test/run-pass/task-spawn-move-and-copy.rs +++ b/src/test/run-pass/task-spawn-move-and-copy.rs @@ -14,10 +14,10 @@ pub fn main() { let (tx, rx) = channel::<uint>(); let x = box 1; - let x_in_parent = &(*x) as *int as uint; + let x_in_parent = &(*x) as *const int as uint; task::spawn(proc() { - let x_in_child = &(*x) as *int as uint; + let x_in_child = &(*x) as *const int as uint; tx.send(x_in_child); }); diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index b066d8a8ae0..ebc720aa0c8 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -24,7 +24,7 @@ extern crate green; extern crate rustuv; #[cfg(test)] #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, __test::main) } diff --git a/src/test/run-pass/tcp-stress.rs b/src/test/run-pass/tcp-stress.rs index efad0cecbde..de3366708c5 100644 --- a/src/test/run-pass/tcp-stress.rs +++ b/src/test/run-pass/tcp-stress.rs @@ -25,7 +25,7 @@ use std::io::{Acceptor, Listener}; use std::task::TaskBuilder; #[start] -fn start(argc: int, argv: **u8) -> int { +fn start(argc: int, argv: *const *const u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } diff --git a/src/test/run-pass/terminate-in-initializer.rs b/src/test/run-pass/terminate-in-initializer.rs index 391f0e20fcc..eb0bfc969f3 100644 --- a/src/test/run-pass/terminate-in-initializer.rs +++ b/src/test/run-pass/terminate-in-initializer.rs @@ -18,7 +18,7 @@ use std::gc::{Gc}; fn test_break() { loop { let _x: Gc<int> = break; } } -fn test_cont() { let mut i = 0; while i < 1 { i += 1; let _x: Gc<int> = continue; } } +fn test_cont() { let mut i = 0i; while i < 1 { i += 1; let _x: Gc<int> = continue; } } fn test_ret() { let _x: Gc<int> = return; } diff --git a/src/test/run-pass/trailing-comma.rs b/src/test/run-pass/trailing-comma.rs index 13d79959f81..8d580729da9 100644 --- a/src/test/run-pass/trailing-comma.rs +++ b/src/test/run-pass/trailing-comma.rs @@ -11,6 +11,6 @@ fn f(_: int,) {} pub fn main() { - f(0,); - let (_, _,) = (1, 1,); + f(0i,); + let (_, _,) = (1i, 1i,); } diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index 18a0e5d471c..cfe9a772b2e 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -99,7 +99,7 @@ fn check_legs(arc: Arc<Vec<Box<Pet+Share+Send>>>) { fn check_names(arc: Arc<Vec<Box<Pet+Share+Send>>>) { for pet in arc.iter() { pet.name(|name| { - assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8); + assert!(name.as_bytes()[0] == 'a' as u8 && name.as_bytes()[1] == 'l' as u8); }) } } diff --git a/src/test/run-pass/trait-contravariant-self.rs b/src/test/run-pass/trait-contravariant-self.rs index d8df5d5600c..e06e01b9e05 100644 --- a/src/test/run-pass/trait-contravariant-self.rs +++ b/src/test/run-pass/trait-contravariant-self.rs @@ -1,3 +1,5 @@ +// ignore-test + // 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. diff --git a/src/test/run-pass/trait-default-method-xc-2.rs b/src/test/run-pass/trait-default-method-xc-2.rs index 9e4a7c4be97..447968eb8c4 100644 --- a/src/test/run-pass/trait-default-method-xc-2.rs +++ b/src/test/run-pass/trait-default-method-xc-2.rs @@ -20,8 +20,8 @@ use aux2::{a_struct, welp}; pub fn main () { - let a = a_struct { x: 0 }; - let b = a_struct { x: 1 }; + let a = a_struct { x: 0i }; + let b = a_struct { x: 1i }; assert_eq!(0i.g(), 10); assert_eq!(a.g(), 10); @@ -30,5 +30,5 @@ pub fn main () { assert_eq!(b.h(), 11); assert_eq!(A::lurr(&a, &b), 21); - welp(&0); + welp(&0i); } diff --git a/src/test/run-pass/type-param-constraints.rs b/src/test/run-pass/type-param-constraints.rs index b87517940c2..fd7e749935b 100644 --- a/src/test/run-pass/type-param-constraints.rs +++ b/src/test/run-pass/type-param-constraints.rs @@ -35,15 +35,15 @@ pub fn main() { p_foo(box(GC) r(10)); p_foo(box r(10)); - p_foo(box(GC) 10); - p_foo(box 10); - p_foo(10); + p_foo(box(GC) 10i); + p_foo(box 10i); + p_foo(10i); s_foo(box(GC) r(10)); - s_foo(box(GC) 10); - s_foo(box 10); - s_foo(10); + s_foo(box(GC) 10i); + s_foo(box 10i); + s_foo(10i); - u_foo(box 10); - u_foo(10); + u_foo(box 10i); + u_foo(10i); } diff --git a/src/test/run-pass/type-ptr.rs b/src/test/run-pass/type-ptr.rs index a00b6b8153e..410e3df9e2a 100644 --- a/src/test/run-pass/type-ptr.rs +++ b/src/test/run-pass/type-ptr.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(a: *int) -> *int { return a; } +fn f(a: *const int) -> *const int { return a; } -fn g(a: *int) -> *int { let b = f(a); return b; } +fn g(a: *const int) -> *const int { let b = f(a); return b; } pub fn main() { return; } diff --git a/src/test/run-pass/typeck-macro-interaction-issue-8852.rs b/src/test/run-pass/typeck-macro-interaction-issue-8852.rs index 50ef1922c8f..6be79cb62dd 100644 --- a/src/test/run-pass/typeck-macro-interaction-issue-8852.rs +++ b/src/test/run-pass/typeck-macro-interaction-issue-8852.rs @@ -15,19 +15,24 @@ enum T { B(f64) } +// after fixing #9384 and implementing hygiene for match bindings, +// this now fails because the insertion of the 'y' into the match +// doesn't cause capture. Making this macro hygienic (as I've done) +// could very well make this test case completely pointless.... + macro_rules! test( - ($e:expr) => ( + ($id1:ident, $id2:ident, $e:expr) => ( fn foo(a:T, b:T) -> T { match (a, b) { - (A(x), A(y)) => A($e), - (B(x), B(y)) => B($e), + (A($id1), A($id2)) => A($e), + (B($id1), B($id2)) => B($e), _ => fail!() } } ) ) -test!(x + y) +test!(x,y,x + y) pub fn main() { foo(A(1), A(2)); diff --git a/src/test/run-pass/typeck_type_placeholder_1.rs b/src/test/run-pass/typeck_type_placeholder_1.rs index 0316311993a..1a79edb30c9 100644 --- a/src/test/run-pass/typeck_type_placeholder_1.rs +++ b/src/test/run-pass/typeck_type_placeholder_1.rs @@ -11,7 +11,7 @@ // This test checks that the `_` type placeholder works // correctly for enabling type inference. -static CONSTEXPR: *int = &'static 413 as *_; +static CONSTEXPR: *const int = &'static 413 as *const _; pub fn main() { let x: Vec<_> = range(0u, 5).collect(); @@ -24,7 +24,7 @@ pub fn main() { assert_eq!(y.len(), 5); let ptr = &5u; - let ptr2 = ptr as *_; + let ptr2 = ptr as *const _; - assert_eq!(ptr as *uint as uint, ptr2 as uint); + assert_eq!(ptr as *const uint as uint, ptr2 as uint); } diff --git a/src/test/run-pass/typestate-cfg-nesting.rs b/src/test/run-pass/typestate-cfg-nesting.rs index 37d06bf4f83..f1e40cc3e58 100644 --- a/src/test/run-pass/typestate-cfg-nesting.rs +++ b/src/test/run-pass/typestate-cfg-nesting.rs @@ -12,12 +12,12 @@ #![allow(unused_variable)] fn f() { - let x = 10; let mut y = 11; + let x = 10i; let mut y = 11i; if true { match x { _ => { y = x; } } } else { } } pub fn main() { - let x = 10; - let mut y = 11; + let x = 10i; + let mut y = 11i; if true { while false { y = x; } } else { } } diff --git a/src/test/run-pass/typestate-multi-decl.rs b/src/test/run-pass/typestate-multi-decl.rs index 42910c47005..cbb0dcc8f2b 100644 --- a/src/test/run-pass/typestate-multi-decl.rs +++ b/src/test/run-pass/typestate-multi-decl.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let (x, y) = (10, 20); + let (x, y) = (10i, 20i); let z = x + y; assert!((z == 30)); } diff --git a/src/test/run-pass/unfold-cross-crate.rs b/src/test/run-pass/unfold-cross-crate.rs index d3e70706867..2af38047264 100644 --- a/src/test/run-pass/unfold-cross-crate.rs +++ b/src/test/run-pass/unfold-cross-crate.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 use std::iter::Unfold; diff --git a/src/test/run-pass/unify-return-ty.rs b/src/test/run-pass/unify-return-ty.rs index 7f46b0ff6e7..a189d4528ae 100644 --- a/src/test/run-pass/unify-return-ty.rs +++ b/src/test/run-pass/unify-return-ty.rs @@ -14,9 +14,9 @@ use std::mem; -fn null<T>() -> *T { +fn null<T>() -> *const T { unsafe { - mem::transmute(0) + mem::transmute(0u) } } diff --git a/src/test/run-pass/uniq-cc-generic.rs b/src/test/run-pass/uniq-cc-generic.rs index 77a8009c975..eb0a3c0eda8 100644 --- a/src/test/run-pass/uniq-cc-generic.rs +++ b/src/test/run-pass/uniq-cc-generic.rs @@ -26,7 +26,7 @@ struct Pointy { } fn make_uniq_closure<A:Send>(a: A) -> proc():Send -> uint { - proc() { &a as *A as uint } + proc() { &a as *const A as uint } } fn empty_pointy() -> Gc<RefCell<Pointy>> { diff --git a/src/test/run-pass/unique-create.rs b/src/test/run-pass/unique-create.rs index 834b549d4f4..acd405e2659 100644 --- a/src/test/run-pass/unique-create.rs +++ b/src/test/run-pass/unique-create.rs @@ -9,9 +9,9 @@ // except according to those terms. pub fn main() { - box 100; + box 100i; } fn vec() { - vec!(0); + vec!(0i); } diff --git a/src/test/run-pass/unique-drop-complex.rs b/src/test/run-pass/unique-drop-complex.rs index 01aac804bb6..a4b6ff5accf 100644 --- a/src/test/run-pass/unique-drop-complex.rs +++ b/src/test/run-pass/unique-drop-complex.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - let _x = box vec!(0,0,0,0,0); + let _x = box vec!(0i,0,0,0,0); } diff --git a/src/test/run-pass/unique-init.rs b/src/test/run-pass/unique-init.rs index d7105b472cc..6e58ec23a3b 100644 --- a/src/test/run-pass/unique-init.rs +++ b/src/test/run-pass/unique-init.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - let _i = box 100; + let _i = box 100i; } diff --git a/src/test/run-pass/unreachable-code.rs b/src/test/run-pass/unreachable-code.rs index 2d74b3163d2..6b6754f3432 100644 --- a/src/test/run-pass/unreachable-code.rs +++ b/src/test/run-pass/unreachable-code.rs @@ -23,10 +23,10 @@ fn call_id_2() { id(true) && id(return); } fn call_id_3() { id(return) && id(return); } -fn ret_ret() -> int { return (return 2) + 3; } +fn ret_ret() -> int { return (return 2i) + 3i; } fn ret_guard() { - match 2 { + match 2i { x if (return) => { x; } _ => {} } diff --git a/src/test/run-pass/unsafe-pointer-assignability.rs b/src/test/run-pass/unsafe-pointer-assignability.rs index 3385c6f6fef..7a624109a55 100644 --- a/src/test/run-pass/unsafe-pointer-assignability.rs +++ b/src/test/run-pass/unsafe-pointer-assignability.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(x: *int) { +fn f(x: *const int) { unsafe { assert_eq!(*x, 3); } diff --git a/src/test/run-pass/unused-move-capture.rs b/src/test/run-pass/unused-move-capture.rs index 83795e64467..ba48ae1c0ce 100644 --- a/src/test/run-pass/unused-move-capture.rs +++ b/src/test/run-pass/unused-move-capture.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let _x = box 1; + let _x = box 1i; let lam_move: || = || {}; lam_move(); } diff --git a/src/test/run-pass/unused-move.rs b/src/test/run-pass/unused-move.rs index bac9ce814bc..883ec44bf2e 100644 --- a/src/test/run-pass/unused-move.rs +++ b/src/test/run-pass/unused-move.rs @@ -16,6 +16,6 @@ pub fn main() { - let y = box 1; + let y = box 1i; y; } diff --git a/src/test/run-pass/unwind-box.rs b/src/test/run-pass/unwind-box.rs index f06791ff2c7..a81f88e2af3 100644 --- a/src/test/run-pass/unwind-box.rs +++ b/src/test/run-pass/unwind-box.rs @@ -14,7 +14,7 @@ use std::task; use std::gc::GC; fn f() { - let _a = box(GC) 0; + let _a = box(GC) 0i; fail!(); } diff --git a/src/test/run-pass/unwind-unique.rs b/src/test/run-pass/unwind-unique.rs index ce252439618..e5497427755 100644 --- a/src/test/run-pass/unwind-unique.rs +++ b/src/test/run-pass/unwind-unique.rs @@ -11,7 +11,7 @@ use std::task; fn f() { - let _a = box 0; + let _a = box 0i; fail!(); } diff --git a/src/test/run-pass/use.rs b/src/test/run-pass/use.rs index e5a79bfaa99..3f152cc1061 100644 --- a/src/test/run-pass/use.rs +++ b/src/test/run-pass/use.rs @@ -26,4 +26,4 @@ mod baz { } #[start] -pub fn start(_: int, _: **u8) -> int { 0 } +pub fn start(_: int, _: *const *const u8) -> int { 0 } diff --git a/src/test/run-pass/utf8.rs b/src/test/run-pass/utf8.rs index 6cf0d518628..557d2e5878e 100644 --- a/src/test/run-pass/utf8.rs +++ b/src/test/run-pass/utf8.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-pretty FIXME #15189 +// no-pretty-expanded FIXME #15189 pub fn main() { let yen: char = '¥'; // 0xa5 @@ -46,7 +46,7 @@ pub fn main() { for ab in a.as_slice().bytes() { println!("{}", i); println!("{}", ab); - let bb: u8 = b.as_slice()[i as uint]; + let bb: u8 = b.as_bytes()[i as uint]; println!("{}", bb); assert_eq!(ab, bb); i += 1; diff --git a/src/test/run-pass/variadic-ffi.rs b/src/test/run-pass/variadic-ffi.rs index c6a1654bfe4..570b881650a 100644 --- a/src/test/run-pass/variadic-ffi.rs +++ b/src/test/run-pass/variadic-ffi.rs @@ -15,7 +15,7 @@ use libc::{c_char, c_int}; // ignore-fast doesn't like extern crate extern { - fn sprintf(s: *mut c_char, format: *c_char, ...) -> c_int; + fn sprintf(s: *mut c_char, format: *const c_char, ...) -> c_int; } unsafe fn check<T>(expected: &str, f: |*mut c_char| -> T) { @@ -41,10 +41,10 @@ pub fn main() { }); // Make a function pointer - let x: unsafe extern "C" fn(*mut c_char, *c_char, ...) -> c_int = sprintf; + let x: unsafe extern "C" fn(*mut c_char, *const c_char, ...) -> c_int = sprintf; // A function that takes a function pointer - unsafe fn call(p: unsafe extern "C" fn(*mut c_char, *c_char, ...) -> c_int) { + unsafe fn call(p: unsafe extern "C" fn(*mut c_char, *const c_char, ...) -> c_int) { // Call with just the named parameter via fn pointer "Hello World\n".with_c_str(|c| { check("Hello World\n", |s| p(s, c)); diff --git a/src/test/run-pass/vec-macro-with-brackets.rs b/src/test/run-pass/vec-macro-with-brackets.rs index 87b18f841ed..d06e3dc0633 100644 --- a/src/test/run-pass/vec-macro-with-brackets.rs +++ b/src/test/run-pass/vec-macro-with-brackets.rs @@ -19,5 +19,5 @@ macro_rules! vec [ ] pub fn main() { - let my_vec = vec![1, 2, 3, 4, 5]; + let my_vec = vec![1i, 2, 3, 4, 5]; } diff --git a/src/test/run-pass/vec-matching.rs b/src/test/run-pass/vec-matching.rs index ac869a10d2e..8ba8ba4482e 100644 --- a/src/test/run-pass/vec-matching.rs +++ b/src/test/run-pass/vec-matching.rs @@ -69,7 +69,7 @@ fn d() { } fn e() { - match &[1, 2, 3] { + match &[1i, 2, 3] { [1, 2] => (), [..] => () } diff --git a/src/test/run-pass/vec-push.rs b/src/test/run-pass/vec-push.rs index 33f01c5bd41..fe0f92a0c11 100644 --- a/src/test/run-pass/vec-push.rs +++ b/src/test/run-pass/vec-push.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn main() { let mut v = vec!(1, 2, 3); v.push(1); } +pub fn main() { let mut v = vec!(1i, 2, 3); v.push(1); } diff --git a/src/test/run-pass/vec-repeat-with-cast.rs b/src/test/run-pass/vec-repeat-with-cast.rs index f5d09e308ba..18ccd8c96ab 100644 --- a/src/test/run-pass/vec-repeat-with-cast.rs +++ b/src/test/run-pass/vec-repeat-with-cast.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn main() { let _a = [0, ..1 as uint]; } +pub fn main() { let _a = [0i, ..1 as uint]; } diff --git a/src/test/run-pass/warn-ctypes-inhibit.rs b/src/test/run-pass/warn-ctypes-inhibit.rs index 9b0a2340156..93112e3e7ec 100644 --- a/src/test/run-pass/warn-ctypes-inhibit.rs +++ b/src/test/run-pass/warn-ctypes-inhibit.rs @@ -14,7 +14,7 @@ mod libc { extern { - pub fn malloc(size: int) -> *u8; + pub fn malloc(size: int) -> *const u8; } } diff --git a/src/test/run-pass/weird-exprs.rs b/src/test/run-pass/weird-exprs.rs index 61578578ab6..bae1a7c45e4 100644 --- a/src/test/run-pass/weird-exprs.rs +++ b/src/test/run-pass/weird-exprs.rs @@ -38,7 +38,7 @@ fn zombiejesus() { while (return) { if (return) { match (return) { - 1 => { + 1i => { if (return) { return } else { @@ -56,7 +56,7 @@ fn zombiejesus() { } fn notsure() { - let mut _x; + let mut _x: int; let mut _y = (_x = 0) == (_x = 0); let mut _z = (_x = 0) < (_x = 0); let _a = (_x += 0) == (_x = 0); @@ -72,8 +72,8 @@ fn canttouchthis() -> uint { fn angrydome() { loop { if break { } } - let mut i = 0; - loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => fail!("wat") } } + let mut i = 0i; + loop { i += 1; if i == 1 { match (continue) { 1i => { }, _ => fail!("wat") } } break; } } diff --git a/src/test/run-pass/while-flow-graph.rs b/src/test/run-pass/while-flow-graph.rs index 36d902dc2e0..01c5986b130 100644 --- a/src/test/run-pass/while-flow-graph.rs +++ b/src/test/run-pass/while-flow-graph.rs @@ -10,4 +10,4 @@ -pub fn main() { let x: int = 10; while x == 10 && x == 11 { let _y = 0xf00; } } +pub fn main() { let x: int = 10; while x == 10 && x == 11 { let _y = 0xf00u; } } |
