From c77ac6f3d0128b59810c0229524ed5b60ef9e4d9 Mon Sep 17 00:00:00 2001 From: Bheesham Persaud Date: Fri, 8 Aug 2014 20:45:34 -0400 Subject: [PATCH 01/25] Minor changes to `rust.md`, and `guide-ffi.md`. --- .gitignore | 1 + src/doc/guide-ffi.md | 6 +++--- src/doc/rust.md | 18 +++++++++--------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 5d5da135a8272..82b9c70ca2b98 100644 --- a/.gitignore +++ b/.gitignore @@ -92,3 +92,4 @@ tmp.*.rs version.md version.ml version.texi + diff --git a/src/doc/guide-ffi.md b/src/doc/guide-ffi.md index fb03d7bc11f5e..600a9019e6b94 100644 --- a/src/doc/guide-ffi.md +++ b/src/doc/guide-ffi.md @@ -350,9 +350,9 @@ linking to, and in the second case `bar` is the type of native library that the compiler is linking to. There are currently three known types of native libraries: -* Dynamic - `#[link(name = "readline")] -* Static - `#[link(name = "my_build_dependency", kind = "static")] -* Frameworks - `#[link(name = "CoreFoundation", kind = "framework")] +* Dynamic - `#[link(name = "readline")]` +* Static - `#[link(name = "my_build_dependency", kind = "static")]` +* Frameworks - `#[link(name = "CoreFoundation", kind = "framework")]` Note that frameworks are only available on OSX targets. diff --git a/src/doc/rust.md b/src/doc/rust.md index 9061a623c03f0..57819695b4516 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -135,9 +135,9 @@ The `ident` production is any nonempty Unicode string of the following form: that does _not_ occur in the set of [keywords](#keywords). -Note: `XID_start` and `XID_continue` as character properties cover the -character ranges used to form the more familiar C and Java language-family -identifiers. +> **Note:** `XID_start` and `XID_continue` as character properties cover the +> character ranges used to form the more familiar C and Java language-family +> identifiers. ### Delimiter-restricted productions @@ -490,7 +490,7 @@ The two values of the boolean type are written `true` and `false`. ### Symbols ~~~~ {.ebnf .gram} -symbol : "::" "->" +symbol : "::" | "->" | '#' | '[' | ']' | '(' | ')' | '{' | '}' | ',' | ';' ; ~~~~ @@ -933,9 +933,9 @@ Usually a `use` declaration is used to shorten the path required to refer to a module item. These declarations may appear at the top of [modules](#modules) and [blocks](#blocks). -*Note*: Unlike in many languages, -`use` declarations in Rust do *not* declare linkage dependency with external crates. -Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies. +> **Note**: Unlike in many languages, +> `use` declarations in Rust do *not* declare linkage dependency with external crates. +> Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies. Use declarations support a number of convenient shortcuts: @@ -2538,8 +2538,8 @@ within a statement block is simply a way of restricting its scope to a narrow region containing all of its uses; it is otherwise identical in meaning to declaring the item outside the statement block. -Note: there is no implicit capture of the function's dynamic environment when -declaring a function-local item. +> **Note:** there is no implicit capture of the function's dynamic environment when +> declaring a function-local item. #### Slot declarations From 7f352ea5766fdc7e866e7b02aca16a804600895b Mon Sep 17 00:00:00 2001 From: nham Date: Tue, 5 Aug 2014 16:12:15 -0400 Subject: [PATCH 02/25] Cleanup collections::slice documentation. This does a few things: - remove references to ~[] and the OwnedVector trait, which are both obsolete - correct the docs to say that this is the slice module, not the vec module - add a sentence pointing out that vectors are distinct from Vec - remove documentation on Vec. closes #15459 --- src/libcollections/slice.rs | 83 ++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 48 deletions(-) diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 5b1722b276916..e616824d94424 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -10,35 +10,46 @@ /*! -Utilities for vector manipulation +Utilities for slice manipulation -The `vec` module contains useful code to help work with vector values. -Vectors are Rust's list type. Vectors contain zero or more values of -homogeneous types: +The `slice` module contains useful code to help work with slice values. +Slices are a view into a block of memory represented as a pointer and a length. ```rust -let int_vector = [1i, 2i, 3i]; -let str_vector = ["one", "two", "three"]; +// slicing a Vec +let vec = vec!(1i, 2, 3); +let int_slice = vec.as_slice(); +// coercing an array to a slice +let str_slice: &[&str] = ["one", "two", "three"]; ``` -This is a big module, but for a high-level overview: +Slices are either mutable or shared. The shared slice type is `&[T]`, +while the mutable slice type is `&mut[T]`. For example, you can mutate the +block of memory that a mutable slice points to: + +```rust +let x: &mut[int] = [1i, 2, 3]; +x[1] = 7; +assert_eq!(x[0], 1); +assert_eq!(x[1], 7); +assert_eq!(x[2], 3); +``` + +Here are some of the things this module contains: ## Structs -Several structs that are useful for vectors, such as `Items`, which -represents iteration over a vector. +There are several structs that are useful for slices, such as `Items`, which +represents iteration over a slice. ## Traits -A number of traits add methods that allow you to accomplish tasks with vectors. - -Traits defined for the `&[T]` type (a vector slice), have methods that can be -called on either owned vectors, denoted `~[T]`, or on vector slices themselves. -These traits include `ImmutableVector`, and `MutableVector` for the `&mut [T]` -case. +A number of traits add methods that allow you to accomplish tasks with slices. +These traits include `ImmutableVector`, which is defined for `&[T]` types, +and `MutableVector`, defined for `&mut [T]` types. 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)`: +a `Vec` or another slice from the index interval `[a, b)`: ```rust let numbers = [0i, 1i, 2i]; @@ -46,33 +57,20 @@ let last_numbers = numbers.slice(1, 3); // last_numbers is now &[1i, 2i] ``` -Traits defined for the `~[T]` type, like `OwnedVector`, can only be called -on such vectors. These methods deal with adding elements or otherwise changing -the allocation of the vector. - -An example is the method `.push(element)` that will add an element at the end -of the vector: - -```rust -let mut numbers = vec![0i, 1i, 2i]; -numbers.push(7); -// numbers is now vec![0i, 1i, 2i, 7i]; -``` - ## Implementations of other traits -Vectors are a very useful type, and so there's several implementations of -traits from other modules. Some notable examples: +There are several implementations of common traits for slices. Some examples +include: * `Clone` -* `Eq`, `Ord`, `Eq`, `Ord` -- vectors can be compared, - if the element type defines the corresponding trait. +* `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`. +* `Hash` - for slices whose element type is `Hash` ## Iteration -The method `iter()` returns an iteration value for a vector or a vector slice. -The iterator yields references to the vector's elements, so if the element -type of the vector is `int`, the element type of the iterator is `&int`. +The method `iter()` returns an iteration value for a slice. The iterator +yields references to the slice's elements, so if the element +type of the slice is `int`, the element type of the iterator is `&int`. ```rust let numbers = [0i, 1i, 2i]; @@ -82,18 +80,7 @@ for &x in numbers.iter() { ``` * `.mut_iter()` returns an iterator that allows modifying each value. -* `.move_iter()` converts an owned vector into an iterator that - moves out a value from the vector each iteration. -* Further iterators exist that split, chunk or permute the vector. - -## Function definitions - -There are a number of free functions that create or take vectors, for example: - -* Creating a vector, like `from_elem` and `from_fn` -* Creating a vector with a given size: `with_capacity` -* Modifying a vector and returning it, like `append` -* Operations on paired elements, like `unzip`. +* Further iterators exist that split, chunk or permute the slice. */ From 4a8edeeff45265612178bd54eb58f939078c5d9f Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 6 Aug 2014 15:38:15 -0400 Subject: [PATCH 03/25] Guide: tasks --- src/doc/guide.md | 146 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/src/doc/guide.md b/src/doc/guide.md index a2b3f22c1554b..b821f0de47b9c 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -4318,6 +4318,152 @@ the same function, so our binary is a little bit larger. # Tasks +Concurrency and parallelism are topics that are of increasing interest to a +broad subsection of software developers. Modern computers are often multi-core, +to the point that even embedded devices like cell phones have more than one +processor. Rust's semantics lend themselves very nicely to solving a number of +issues that programmers have with concurrency. Many concurrency errors that are +runtime errors in other languages are compile-time errors in Rust. + +Rust's concurrency primitive is called a **task**. Tasks are lightweight, and +do not share memory in an unsafe manner, preferring message passing to +communicate. It's worth noting that tasks are implemented as a library, and +not part of the language. This means that in the future, other concurrency +libraries can be written for Rust to help in specific scenarios. Here's an +example of creating a task: + +```{rust} +spawn(proc() { + println!("Hello from a task!"); +}); +``` + +The `spawn` function takes a proc as an argument, and runs that proc in a new +task. A proc takes ownership of its entire environment, and so any variables +that you use inside the proc will not be usable afterward: + +```{rust,ignore} +let mut x = vec![1i, 2i, 3i]; + +spawn(proc() { + println!("The value of x[0] is: {}", x[0]); +}); + +println!("The value of x[0] is: {}", x[0]); // error: use of moved value: `x` +``` + +`x` is now owned by the proc, and so we can't use it anymore. Many other +languages would let us do this, but it's not safe to do so. Rust's type system +catches the error. + +If tasks were only able to capture these values, they wouldn't be very useful. +Luckily, tasks can communicate with each other through **channel**s. Channels +work like this: + +```{rust} +let (tx, rx) = channel(); + +spawn(proc() { + tx.send("Hello from a task!".to_string()); +}); + +let message = rx.recv(); +println!("{}", message); +``` + +The `channel()` function returns two endpoints: a `Receiver` and a +`Sender`. You can use the `.send()` method on the `Sender` end, and +receive the message on the `Receiver` side with the `recv()` method. This +method blocks until it gets a message. There's a similar method, `.try_recv()`, +which returns an `Option` and does not block. + +If you want to send messages to the task as well, create two channels! + +```{rust} +let (tx1, rx1) = channel(); +let (tx2, rx2) = channel(); + +spawn(proc() { + tx1.send("Hello from a task!".to_string()); + let message = rx2.recv(); + println!("{}", message); +}); + +let message = rx1.recv(); +println!("{}", message); + +tx2.send("Goodbye from main!".to_string()); +``` + +The proc has one sending end and one receiving end, and the main task has one +of each as well. Now they can talk back and forth in whatever way they wish. + +Notice as well that because `Sender` and `Receiver` are generic, while you can +pass any kind of information through the channel, the ends are strongly typed. +If you try to pass a string, and then an integer, Rust will complain. + +## Futures + +With these basic primitives, many different concurrency patterns can be +developed. Rust includes some of these types in its standard library. For +example, if you wish to compute some value in the background, `Future` is +a useful thing to use: + +```{rust} +use std::sync::Future; + +let mut delayed_value = Future::spawn(proc() { + // just return anything for examples' sake + + 12345i +}); +println!("value = {}", delayed_value.get()); +``` + +Calling `Future::spawn` works just like `spawn()`: it takes a proc. In this +case, though, you don't need to mess with the channel: just have the proc +return the value. + +`Future::spawn` will return a value which we can bind with `let`. It needs +to be mutable, because once the value is computed, it saves a copy of the +value, and if it were immutable, it couldn't update itself. + +The proc will go on processing in the background, and when we need the final +value, we can call `get()` on it. This will block until the result is done, +but if it's finished computing in the background, we'll just get the value +immediately. + +## Success and failure + +Tasks don't always succeed, they can also fail. A task that wishes to fail +can call the `fail!` macro, passing a message: + +```{rust} +spawn(proc() { + fail!("Nope."); +}); +``` + +If a task fails, it is not possible for it to recover. However, it can +notify other tasks that it has failed. We can do this with `task::try`: + +```{rust} +use std::task; +use std::rand; + +let result = task::try(proc() { + if rand::random() { + println!("OK"); + } else { + fail!("oops!"); + } +}); +``` + +This task will randomly fail or succeed. `task::try` returns a `Result` +type, so we can handle the response like any other computation that may +fail. + # Macros # Unsafe From 55d8ec1c729255facbd024a1f7bf9666882b2ce9 Mon Sep 17 00:00:00 2001 From: Gioele Barabucci Date: Thu, 7 Aug 2014 14:00:35 +0200 Subject: [PATCH 04/25] Use system rustc if configured with --enable-local-rust This commit makes the configuration system autodetect a rustc that is already installed and use that instead of downloading a snapshot. --- configure | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/configure b/configure index e08e28e0aece0..636d50276ff54 100755 --- a/configure +++ b/configure @@ -557,13 +557,21 @@ fi if [ ! -z "$CFG_ENABLE_LOCAL_RUST" ] then - if [ ! -f ${CFG_LOCAL_RUST_ROOT}/bin/rustc${BIN_SUF} ] + system_rustc=$(which rustc) + if [ -f ${CFG_LOCAL_RUST_ROOT}/bin/rustc${BIN_SUF} ] then - err "no local rust to use" + : # everything already configured + elif [ -n "$system_rustc" ] + then + # we assume that rustc is in a /bin directory + CFG_LOCAL_RUST_ROOT=${system_rustc%/bin/rustc} else - LRV=`${CFG_LOCAL_RUST_ROOT}/bin/rustc${BIN_SUF} --version` - step_msg "using rustc at: ${CFG_LOCAL_RUST_ROOT} with version: $LRV" + err "no local rust to use" fi + + LRV=`${CFG_LOCAL_RUST_ROOT}/bin/rustc${BIN_SUF} --version` + step_msg "using rustc at: ${CFG_LOCAL_RUST_ROOT} with version: $LRV" + putvar CFG_LOCAL_RUST_ROOT fi # Force freebsd to build with clang; gcc doesn't like us there From e7eb877c913aa4342479890ffc717dcefe3ab074 Mon Sep 17 00:00:00 2001 From: Nathan Froyd Date: Thu, 7 Aug 2014 11:27:06 -0400 Subject: [PATCH 05/25] fix grammar in Vec.retain's doc comment --- src/libcollections/vec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 6618906cf69de..39fe57038b0b2 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1318,7 +1318,7 @@ impl Vec { /// Retains only the elements specified by the predicate. /// /// In other words, remove all elements `e` such that `f(&e)` returns false. - /// This method operates in place and preserves the order the retained elements. + /// This method operates in place and preserves the order of the retained elements. /// /// # Example /// From 3f958de5a4c002b958af663c3eb8451169ea6bb8 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 8 Aug 2014 06:20:01 -0400 Subject: [PATCH 06/25] Register new snapshot 12e0f72 --- src/libcore/char.rs | 3 --- src/libcore/failure.rs | 24 ------------------------ src/libcore/fmt/float.rs | 5 ----- src/libcore/fmt/num.rs | 5 ----- src/libcore/ops.rs | 1 - src/libcore/ptr.rs | 3 --- src/libcore/str.rs | 3 --- src/librustrt/unwind.rs | 16 ---------------- src/libstd/io/tempfile.rs | 3 --- src/libstd/macros.rs | 34 ---------------------------------- src/libunicode/normalize.rs | 3 --- src/snapshots.txt | 8 ++++++++ 12 files changed, 8 insertions(+), 100 deletions(-) diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 71144095f478b..63ffc4a046f68 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -19,9 +19,6 @@ use mem::transmute; use option::{None, Option, Some}; use iter::range_step; -#[cfg(stage0)] -use iter::Iterator; // NOTE(stage0): Remove after snapshot. - // UTF-8 ranges and tags for encoding characters static TAG_CONT: u8 = 0b1000_0000u8; static TAG_TWO_B: u8 = 0b1100_0000u8; diff --git a/src/libcore/failure.rs b/src/libcore/failure.rs index f5cfa2611d5e6..e764ae17500b6 100644 --- a/src/libcore/failure.rs +++ b/src/libcore/failure.rs @@ -33,29 +33,6 @@ use fmt; use intrinsics; -#[cfg(stage0)] -#[cold] #[inline(never)] // this is the slow path, always -#[lang="fail_"] -fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! { - format_args!(|args| -> () { - begin_unwind(args, &(file, line)); - }, "{}", expr); - - unsafe { intrinsics::abort() } -} - -#[cfg(stage0)] -#[cold] -#[lang="fail_bounds_check"] -fn fail_bounds_check(file: &'static str, line: uint, - index: uint, len: uint) -> ! { - format_args!(|args| -> () { - begin_unwind(args, &(file, line)); - }, "index out of bounds: the len is {} but the index is {}", len, index); - unsafe { intrinsics::abort() } -} - -#[cfg(not(stage0))] #[cold] #[inline(never)] // this is the slow path, always #[lang="fail_"] fn fail_(expr_file_line: &(&'static str, &'static str, uint)) -> ! { @@ -68,7 +45,6 @@ fn fail_(expr_file_line: &(&'static str, &'static str, uint)) -> ! { unsafe { intrinsics::abort() } } -#[cfg(not(stage0))] #[cold] #[inline(never)] #[lang="fail_bounds_check"] fn fail_bounds_check(file_line: &(&'static str, uint), diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index 88702e59e30d1..1bfa5168cf796 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -21,11 +21,6 @@ use slice::{ImmutableVector, MutableVector}; use slice; use str::StrSlice; -#[cfg(stage0)] -use iter::Iterator; // NOTE(stage0): Remove after snapshot. -#[cfg(stage0)] -use option::{Some, None}; // NOTE(stage0): Remove after snapshot. - /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 99920dc788190..bba3e4cb9afcc 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -20,11 +20,6 @@ use iter::DoubleEndedIterator; use num::{Int, cast, zero}; use slice::{ImmutableVector, MutableVector}; -#[cfg(stage0)] -use iter::Iterator; // NOTE(stage0): Remove after snapshot. -#[cfg(stage0)] -use option::{Some, None}; // NOTE(stage0): Remove after snapshot. - /// A type that represents a specific radix #[doc(hidden)] trait GenericRadix { diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 839243970ac67..23577dd29e0af 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -771,7 +771,6 @@ pub trait FnOnce { macro_rules! def_fn_mut( ($($args:ident)*) => ( - #[cfg(not(stage0))] impl FnMut<($($args,)*),Result> for extern "Rust" fn($($args: $args,)*) -> Result { diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 4921802ba732e..eb9bede85d8b2 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -95,9 +95,6 @@ use option::{Some, None, Option}; use cmp::{PartialEq, Eq, PartialOrd, Equiv, Ordering, Less, Equal, Greater}; -#[cfg(stage0)] -use iter::Iterator; // NOTE(stage0): Remove after snapshot. - pub use intrinsics::copy_memory; pub use intrinsics::copy_nonoverlapping_memory; pub use intrinsics::set_memory; diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 5eb463687904c..c1166a7621e19 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -1030,9 +1030,6 @@ pub mod traits { use option::{Option, Some}; use str::{Str, StrSlice, eq_slice}; - #[cfg(stage0)] - use option::None; // NOTE(stage0): Remove after snapshot. - impl<'a> Ord for &'a str { #[inline] fn cmp(&self, other: & &'a str) -> Ordering { diff --git a/src/librustrt/unwind.rs b/src/librustrt/unwind.rs index 117f680011e5b..79f83df5be809 100644 --- a/src/librustrt/unwind.rs +++ b/src/librustrt/unwind.rs @@ -523,22 +523,6 @@ pub fn begin_unwind_fmt(msg: &fmt::Arguments, file_line: &(&'static str, uint)) } /// This is the entry point of unwinding for fail!() and assert!(). -#[cfg(stage0)] -#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible -pub fn begin_unwind(msg: M, file: &'static str, line: uint) -> ! { - // Note that this should be the only allocation performed in this code path. - // Currently this means that fail!() on OOM will invoke this code path, - // but then again we're not really ready for failing on OOM anyway. If - // we do start doing this, then we should propagate this allocation to - // be performed in the parent of this task instead of the task that's - // failing. - - // see below for why we do the `Any` coercion here. - begin_unwind_inner(box msg, &(file, line)) -} - -/// This is the entry point of unwinding for fail!() and assert!(). -#[cfg(not(stage0))] #[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible pub fn begin_unwind(msg: M, file_line: &(&'static str, uint)) -> ! { // Note that this should be the only allocation performed in this code path. diff --git a/src/libstd/io/tempfile.rs b/src/libstd/io/tempfile.rs index 1d53ed814377e..2faa23a6aa0a5 100644 --- a/src/libstd/io/tempfile.rs +++ b/src/libstd/io/tempfile.rs @@ -21,9 +21,6 @@ use path::{Path, GenericPath}; use result::{Ok, Err}; use sync::atomic; -#[cfg(stage0)] -use iter::Iterator; // NOTE(stage0): Remove after snapshot. - /// A wrapper for a path to temporary directory implementing automatic /// scope-based deletion. pub struct TempDir { diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 3184c151bd2c7..f2d7fb0cea68a 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -37,7 +37,6 @@ /// fail!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] -#[cfg(not(stage0))] macro_rules! fail( () => ({ fail!("explicit failure") @@ -68,39 +67,6 @@ macro_rules! fail( }); ) -#[macro_export] -#[cfg(stage0)] -macro_rules! fail( - () => ({ - fail!("explicit failure") - }); - ($msg:expr) => ({ - // static requires less code at runtime, more constant data - static FILE_LINE: (&'static str, uint) = (file!(), line!()); - let (file, line) = FILE_LINE; - ::std::rt::begin_unwind($msg, file, line) - }); - ($fmt:expr, $($arg:tt)*) => ({ - // a closure can't have return type !, so we need a full - // function to pass to format_args!, *and* we need the - // file and line numbers right here; so an inner bare fn - // is our only choice. - // - // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt - // is #[cold] and #[inline(never)] and because this is flagged as cold - // as returning !. We really do want this to be inlined, however, - // because it's just a tiny wrapper. Small wins (156K to 149K in size) - // were seen when forcing this to be inlined, and that number just goes - // up with the number of calls to fail!() - #[inline(always)] - fn run_fmt(fmt: &::std::fmt::Arguments) -> ! { - static FILE_LINE: (&'static str, uint) = (file!(), line!()); - ::std::rt::begin_unwind_fmt(fmt, &FILE_LINE) - } - format_args!(run_fmt, $fmt, $($arg)*) - }); -) - /// Ensure that a boolean expression is `true` at runtime. /// /// This will invoke the `fail!` macro if the provided expression cannot be diff --git a/src/libunicode/normalize.rs b/src/libunicode/normalize.rs index df0be09aea1f7..ec31181e8a748 100644 --- a/src/libunicode/normalize.rs +++ b/src/libunicode/normalize.rs @@ -39,9 +39,6 @@ pub fn decompose_canonical(c: char, i: |char|) { d(c, i, false); } pub fn decompose_compatible(c: char, i: |char|) { d(c, i, true); } fn d(c: char, i: |char|, k: bool) { - #[cfg(stage0)] - use core::iter::Iterator; - // 7-bit ASCII never decomposes if c <= '\x7f' { i(c); return; } diff --git a/src/snapshots.txt b/src/snapshots.txt index 623f8f8bcc00d..a07be82d58ef9 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,11 @@ +S 2014-08-07 12e0f72 + freebsd-x86_64 e55055a876ebbde0d3ed3bcb97579afab9264def + linux-i386 2665e45879f2ef77ce0c9015f971642fe424ac33 + linux-x86_64 51ed1f4cf0707585a136bb149a443394067c074c + macos-i386 78f1996954a6e0718d684a3756b4870a6f8771ee + macos-x86_64 216f46f65866207a9f41c3ed654f5c1e085cb7f3 + winnt-i386 95a9b8a8bf587761ae954392aee2ccee3758a533 + S 2014-07-17 9fc8394 freebsd-x86_64 5a4b645e2b42ae06224cc679d4a43b3d89be1482 linux-i386 a5e1bb723020ac35173d49600e76b0935e257a6a From 774d46cd0cc29c57c69ab05c6ff13cab03df22d9 Mon Sep 17 00:00:00 2001 From: mdinger Date: Thu, 7 Aug 2014 15:14:16 -0400 Subject: [PATCH 07/25] Fix typo --- src/libstd/sync/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 1d189f8d4bcbd..c9526a64f46d0 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -10,7 +10,7 @@ //! Useful synchronization primitives //! -//! This modules contains useful safe and unsafe synchronization primitives. +//! This module contains useful safe and unsafe synchronization primitives. //! Most of the primitives in this module do not provide any sort of locking //! and/or blocking at all, but rather provide the necessary tools to build //! other types of concurrent primitives. From de547eac6426ab21186549ed162f51aa4dc81da7 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 4 Aug 2014 17:43:48 -0400 Subject: [PATCH 08/25] Guide: method syntax --- src/doc/guide.md | 88 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/src/doc/guide.md b/src/doc/guide.md index b821f0de47b9c..c3dfa93cda36a 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -3614,6 +3614,94 @@ guide](http://doc.rust-lang.org/guide-pointers.html#rc-and-arc). # Patterns +# Method Syntax + +Functions are great, but if you want to call a bunch of them on some data, it +can be awkward. Consider this code: + +```{rust,ignore} +baz(bar(foo(x))); +``` + +We would read this left-to right, and so we see 'baz bar foo.' But this isn't the +order that the functions would get called in, that's inside-out: 'foo bar baz.' +Wouldn't it be nice if we could do this instead? + +```{rust,ignore} +x.foo().bar().baz(); +``` + +Luckily, as you may have guessed with the leading question, you can! Rust provides +the ability to use this **method call syntax** via the `impl` keyword. + +Here's how it works: + +``` +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } +} + +fn main() { + let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; + println!("{}", c.area()); +} +``` + +This will print `12.566371`. + +We've made a struct that represents a circle. We then write an `impl` block, +and inside it, define a method, `area`. Methods take a special first +parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`. +You can think of this first parameter as being the `x` in `x.foo()`. The three +variants correspond to the three kinds of thing `x` could be: `self` if it's +just a value on the stack, `&self` if it's a reference, and `&mut self` if it's +a mutable reference. We should default to using `&self`, as it's the most +common. + +Finally, as you may remember, the value of the area of a circle is `π*r²`. +Because we took the `&self` parameter to `area`, we can use it just like any +other parameter. Because we know it's a `Circle`, we can access the `radius` +just like we would with any other struct. An import of π and some +multiplications later, and we have our area. + +You can also define methods that do not take a `self` parameter. Here's a +pattern that's very common in Rust code: + +``` +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl Circle { + fn new(x: f64, y: f64, radius: f64) -> Circle { + Circle { + x: x, + y: y, + radius: radius, + } + } +} + +fn main() { + let c = Circle::new(0.0, 0.0, 2.0); +} +``` + +This **static method** builds a new `Circle` for us. Note that static methods +are called with the `Struct::method()` syntax, rather than the `ref.method()` +syntax. + + # Closures So far, we've made lots of functions in Rust. But we've given them all names. From 9a2b41967573e9cd4c011599c4c1056f6db343d5 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Thu, 7 Aug 2014 16:37:39 -0400 Subject: [PATCH 09/25] Guide: strings --- src/doc/guide.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/src/doc/guide.md b/src/doc/guide.md index c3dfa93cda36a..a5091f41974b4 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -1432,6 +1432,86 @@ building our guessing game, but we need to know how to do one last thing first: get input from the keyboard. You can't have a guessing game without the ability to guess! +# Strings + +Strings are an important concept for any programmer to master. Rust's string +handling system is a bit different than in other languages, due to its systems +focus. Any time you have a data structure of variable size, things can get +tricky, and strings are a re-sizable data structure. That said, Rust's strings +also work differently than in some other systems languages, such as C. + +Let's dig into the details. A **string** is a sequence of unicode scalar values +encoded as a stream of UTF-8 bytes. All strings are guaranteed to be +validly-encoded UTF-8 sequences. Additionally, strings are not null-terminated +and can contain null bytes. + +Rust has two main types of strings: `&str` and `String`. + +The first kind is a `&str`. This is pronounced a 'string slice.' String literals +are of the type `&str`: + +```{rust} +let string = "Hello there."; +``` + +This string is statically allocated, meaning that it's saved inside our +compiled program, and exists for the entire duration it runs. The `string` +binding is a reference to this statically allocated string. String slices +have a fixed size, and cannot be mutated. + +A `String`, on the other hand, is an in-memory string. This string is +growable, and is also guaranteed to be UTF-8. + +```{rust} +let mut s = "Hello".to_string(); +println!("{}", s); + +s.push_str(", world."); +println!("{}", s); +``` + +You can coerce a `String` into a `&str` with the `as_slice()` method: + +```{rust} +fn takes_slice(slice: &str) { + println!("Got: {}", slice); +} + +fn main() { + let s = "Hello".to_string(); + takes_slice(s.as_slice()); +} +``` + +To compare a String to a constant string, prefer `as_slice()`... + +```{rust} +fn compare(string: String) { + if string.as_slice() == "Hello" { + println!("yes"); + } +} +``` + +... over `to_string()`: + +```{rust} +fn compare(string: String) { + if string == "Hello".to_string() { + println!("yes"); + } +} +``` + +Converting a `String` to a `&str` is cheap, but converting the `&str` to a +`String` involves allocating memory. No reason to do that unless you have to! + +That's the basics of strings in Rust! They're probably a bit more complicated +than you are used to, if you come from a scripting language, but when the +low-level details matter, they really matter. Just remember that `String`s +allocate memory and control their data, while `&str`s are a reference to +another string, and you'll be all set. + # Standard Input Getting input from the keyboard is pretty easy, but uses some things From 16734b54f6722129922af8b13146cc75c9905afd Mon Sep 17 00:00:00 2001 From: Peter Atashian Date: Thu, 7 Aug 2014 04:05:00 -0400 Subject: [PATCH 10/25] windows: Fix several tests on 64-bit. Signed-off-by: Peter Atashian --- src/liblibc/lib.rs | 21 +++++++++------------ src/libnative/io/c_win32.rs | 12 ++++++++++++ src/libnative/io/util.rs | 8 ++++++++ src/libstd/io/fs.rs | 9 +++++---- 4 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index 1bc64ffcc92ae..fa29ab508ff24 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -1142,18 +1142,17 @@ pub mod types { pub mod os { pub mod common { pub mod posix01 { - use types::os::arch::c95::{c_short, time_t, suseconds_t, + use types::os::arch::c95::{c_short, time_t, c_long}; use types::os::arch::extra::{int64, time64_t}; use types::os::arch::posix88::{dev_t, ino_t}; - use types::os::arch::posix88::mode_t; // pub Note: this is the struct called stat64 in win32. Not stat, // nor stati64. pub struct stat { pub st_dev: dev_t, pub st_ino: ino_t, - pub st_mode: mode_t, + pub st_mode: u16, pub st_nlink: c_short, pub st_uid: c_short, pub st_gid: c_short, @@ -1171,8 +1170,8 @@ pub mod types { } pub struct timeval { - pub tv_sec: time_t, - pub tv_usec: suseconds_t, + pub tv_sec: c_long, + pub tv_usec: c_long, } pub struct timespec { @@ -1186,7 +1185,7 @@ pub mod types { pub mod bsd44 { use types::os::arch::c95::{c_char, c_int, c_uint, size_t}; - pub type SOCKET = c_uint; + pub type SOCKET = uint; pub type socklen_t = c_int; pub type sa_family_t = u16; pub type in_port_t = u16; @@ -1197,6 +1196,7 @@ pub mod types { } pub struct sockaddr_storage { pub ss_family: sa_family_t, + pub __ss_pad1: [u8, ..6], pub __ss_align: i64, pub __ss_pad2: [u8, ..112], } @@ -1293,12 +1293,9 @@ pub mod types { pub mod posix88 { pub type off_t = i32; pub type dev_t = u32; - pub type ino_t = i16; + pub type ino_t = u16; - #[cfg(target_arch = "x86")] - pub type pid_t = i32; - #[cfg(target_arch = "x86_64")] - pub type pid_t = i64; + pub type pid_t = u32; pub type useconds_t = u32; pub type mode_t = u16; @@ -1415,7 +1412,7 @@ pub mod types { pub dwPageSize: DWORD, pub lpMinimumApplicationAddress: LPVOID, pub lpMaximumApplicationAddress: LPVOID, - pub dwActiveProcessorMask: DWORD, + pub dwActiveProcessorMask: uint, pub dwNumberOfProcessors: DWORD, pub dwProcessorType: DWORD, pub dwAllocationGranularity: DWORD, diff --git a/src/libnative/io/c_win32.rs b/src/libnative/io/c_win32.rs index 482155c339c9b..80c9e91b48f7a 100644 --- a/src/libnative/io/c_win32.rs +++ b/src/libnative/io/c_win32.rs @@ -28,6 +28,7 @@ pub static ENABLE_PROCESSED_INPUT: libc::DWORD = 0x1; pub static ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; #[repr(C)] +#[cfg(target_arch = "x86")] pub struct WSADATA { pub wVersion: libc::WORD, pub wHighVersion: libc::WORD, @@ -37,6 +38,17 @@ pub struct WSADATA { pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, } +#[repr(C)] +#[cfg(target_arch = "x86_64")] +pub struct WSADATA { + pub wVersion: libc::WORD, + pub wHighVersion: libc::WORD, + pub iMaxSockets: u16, + pub iMaxUdpDg: u16, + pub lpVendorInfo: *mut u8, + pub szDescription: [u8, ..WSADESCRIPTION_LEN + 1], + pub szSystemStatus: [u8, ..WSASYS_STATUS_LEN + 1], +} pub type LPWSADATA = *mut WSADATA; diff --git a/src/libnative/io/util.rs b/src/libnative/io/util.rs index 06046cc74cfd8..97518bbf19995 100644 --- a/src/libnative/io/util.rs +++ b/src/libnative/io/util.rs @@ -52,6 +52,14 @@ pub fn eof() -> IoError { } } +#[cfg(windows)] +pub fn ms_to_timeval(ms: u64) -> libc::timeval { + libc::timeval { + tv_sec: (ms / 1000) as libc::c_long, + tv_usec: ((ms % 1000) * 1000) as libc::c_long, + } +} +#[cfg(not(windows))] pub fn ms_to_timeval(ms: u64) -> libc::timeval { libc::timeval { tv_sec: (ms / 1000) as libc::time_t, diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 6a4172d5c3526..7335511ed857e 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -1592,10 +1592,11 @@ mod test { let tmpdir = tmpdir(); let path = tmpdir.join("a"); check!(File::create(&path)); - - check!(change_file_times(&path, 1000, 2000)); - assert_eq!(check!(path.stat()).accessed, 1000); - assert_eq!(check!(path.stat()).modified, 2000); + // These numbers have to be bigger than the time in the day to account for timezones + // Windows in particular will fail in certain timezones with small enough values + check!(change_file_times(&path, 100000, 200000)); + assert_eq!(check!(path.stat()).accessed, 100000); + assert_eq!(check!(path.stat()).modified, 200000); }) iotest!(fn utime_noexist() { From 2166aab35987960b5a7c1dc88e3431a9d525c2ba Mon Sep 17 00:00:00 2001 From: Peter Atashian Date: Thu, 7 Aug 2014 16:40:12 -0400 Subject: [PATCH 11/25] windows: Fix INVALID_HANDLE_VALUE Made INVALID_HANDLE_VALUE actually a HANDLE. Removed all useless casts during INVALID_HANDLE_VALUE comparisons. Signed-off-by: Peter Atashian --- src/liblibc/lib.rs | 7 +++---- src/libnative/io/file_win32.rs | 6 +++--- src/libnative/io/pipe_win32.rs | 10 +++++----- src/libnative/io/process.rs | 10 +++++----- src/librustdoc/flock.rs | 2 +- 5 files changed, 17 insertions(+), 18 deletions(-) diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index fa29ab508ff24..e368a5644159c 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -1142,8 +1142,7 @@ pub mod types { pub mod os { pub mod common { pub mod posix01 { - use types::os::arch::c95::{c_short, time_t, - c_long}; + use types::os::arch::c95::{c_short, time_t, c_long}; use types::os::arch::extra::{int64, time64_t}; use types::os::arch::posix88::{dev_t, ino_t}; @@ -1947,7 +1946,7 @@ pub mod consts { } pub mod extra { use types::os::arch::c95::c_int; - use types::os::arch::extra::{WORD, DWORD, BOOL}; + use types::os::arch::extra::{WORD, DWORD, BOOL, HANDLE}; pub static TRUE : BOOL = 1; pub static FALSE : BOOL = 0; @@ -1976,7 +1975,7 @@ pub mod consts { pub static ERROR_IO_PENDING: c_int = 997; pub static ERROR_FILE_INVALID : c_int = 1006; pub static ERROR_NOT_FOUND: c_int = 1168; - pub static INVALID_HANDLE_VALUE : c_int = -1; + pub static INVALID_HANDLE_VALUE: HANDLE = -1 as HANDLE; pub static DELETE : DWORD = 0x00010000; pub static READ_CONTROL : DWORD = 0x00020000; diff --git a/src/libnative/io/file_win32.rs b/src/libnative/io/file_win32.rs index a024d498ef341..fe29c0245297c 100644 --- a/src/libnative/io/file_win32.rs +++ b/src/libnative/io/file_win32.rs @@ -320,7 +320,7 @@ pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess) dwFlagsAndAttributes, ptr::mut_null()) }; - if handle == libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if handle == libc::INVALID_HANDLE_VALUE { Err(super::last_error()) } else { let fd = unsafe { @@ -368,7 +368,7 @@ pub fn readdir(p: &CString) -> IoResult> { 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); - if find_handle as libc::c_int != libc::INVALID_HANDLE_VALUE { + if find_handle != libc::INVALID_HANDLE_VALUE { let mut paths = vec!(); let mut more_files = 1 as libc::c_int; while more_files != 0 { @@ -440,7 +440,7 @@ pub fn readlink(p: &CString) -> IoResult { libc::FILE_ATTRIBUTE_NORMAL, ptr::mut_null()) }; - if handle as int == libc::INVALID_HANDLE_VALUE as int { + if handle == libc::INVALID_HANDLE_VALUE { return Err(super::last_error()) } // Specify (sz - 1) because the documentation states that it's the size diff --git a/src/libnative/io/pipe_win32.rs b/src/libnative/io/pipe_win32.rs index 87129bba845bf..717915e5d23bd 100644 --- a/src/libnative/io/pipe_win32.rs +++ b/src/libnative/io/pipe_win32.rs @@ -223,7 +223,7 @@ impl UnixStream { libc::FILE_FLAG_OVERLAPPED, ptr::mut_null()) }; - if result != libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if result != libc::INVALID_HANDLE_VALUE { return Some(result) } @@ -238,7 +238,7 @@ impl UnixStream { libc::FILE_FLAG_OVERLAPPED, ptr::mut_null()) }; - if result != libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if result != libc::INVALID_HANDLE_VALUE { return Some(result) } } @@ -253,7 +253,7 @@ impl UnixStream { libc::FILE_FLAG_OVERLAPPED, ptr::mut_null()) }; - if result != libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if result != libc::INVALID_HANDLE_VALUE { return Some(result) } } @@ -565,7 +565,7 @@ impl UnixListener { // and such. let addr_v = try!(to_utf16(addr)); let ret = unsafe { pipe(addr_v.as_ptr(), true) }; - if ret == libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if ret == libc::INVALID_HANDLE_VALUE { Err(super::last_error()) } else { Ok(UnixListener { handle: ret, name: addr.clone() }) @@ -680,7 +680,7 @@ impl UnixAcceptor { // create a second server pipe. If this fails, we disconnect the // connected client and return an error (see comments above). let new_handle = unsafe { pipe(name.as_ptr(), false) }; - if new_handle == libc::INVALID_HANDLE_VALUE as libc::HANDLE { + if new_handle == libc::INVALID_HANDLE_VALUE { let ret = Err(super::last_error()); // If our disconnection fails, then there's not really a whole lot // that we can do, so fail the task. diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index c89a40d651351..d83e36a5e2a9c 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -359,13 +359,13 @@ fn spawn_process_os(cfg: ProcessConfig, libc::OPEN_EXISTING, 0, ptr::mut_null()); - if *slot == INVALID_HANDLE_VALUE as libc::HANDLE { + if *slot == INVALID_HANDLE_VALUE { return Err(super::last_error()) } } Some(ref fd) => { let orig = get_osfhandle(fd.fd()) as HANDLE; - if orig == INVALID_HANDLE_VALUE as HANDLE { + if orig == INVALID_HANDLE_VALUE { return Err(super::last_error()) } if DuplicateHandle(cur_proc, orig, cur_proc, slot, @@ -450,9 +450,9 @@ fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO { wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::mut_null(), - hStdInput: libc::INVALID_HANDLE_VALUE as libc::HANDLE, - hStdOutput: libc::INVALID_HANDLE_VALUE as libc::HANDLE, - hStdError: libc::INVALID_HANDLE_VALUE as libc::HANDLE, + hStdInput: libc::INVALID_HANDLE_VALUE, + hStdOutput: libc::INVALID_HANDLE_VALUE, + hStdError: libc::INVALID_HANDLE_VALUE, } } diff --git a/src/librustdoc/flock.rs b/src/librustdoc/flock.rs index f22950e7a299e..cb8be9c899757 100644 --- a/src/librustdoc/flock.rs +++ b/src/librustdoc/flock.rs @@ -197,7 +197,7 @@ mod imp { libc::FILE_ATTRIBUTE_NORMAL, ptr::mut_null()) }; - if handle as uint == libc::INVALID_HANDLE_VALUE as uint { + if handle == libc::INVALID_HANDLE_VALUE { fail!("create file error: {}", os::last_os_error()); } let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() }; From 46f68816a3ca941d097924d6fae5d991428872da Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Sat, 2 Aug 2014 20:58:41 -0400 Subject: [PATCH 12/25] make rustdoc more responsive * move some sidebar contents to a title bar when small * inline description toggle when small * make out-of-band and in-band content share space, rather than float and clash * compress wording of out-of-band content to avoid line-wrap as much as possible --- src/librustdoc/html/render.rs | 14 ++--- src/librustdoc/html/static/main.css | 93 ++++++++++++++++++++++------- 2 files changed, 79 insertions(+), 28 deletions(-) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 76e18d5258c49..eea594550398b 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1294,7 +1294,7 @@ impl<'a> Item<'a> { impl<'a> fmt::Show for Item<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Write the breadcrumb trail header for the top - try!(write!(fmt, "\n

")); + try!(write!(fmt, "\n

")); match self.item.inner { clean::ModuleItem(ref m) => if m.is_crate { try!(write!(fmt, "Crate ")); @@ -1316,7 +1316,7 @@ impl<'a> fmt::Show for Item<'a> { let cur = self.cx.current.as_slice(); let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() }; for (i, component) in cur.iter().enumerate().take(amt) { - try!(write!(fmt, "{}::", + try!(write!(fmt, "{}​::", "../".repeat(cur.len() - i - 1), component.as_slice())); } @@ -1325,10 +1325,10 @@ impl<'a> fmt::Show for Item<'a> { shortty(self.item), self.item.name.get_ref().as_slice())); // Write stability level - try!(write!(fmt, "{}", Stability(&self.item.stability))); + try!(write!(fmt, "​{}", Stability(&self.item.stability))); // Links to out-of-band information, i.e. src and stability dashboard - try!(write!(fmt, "")); + try!(write!(fmt, "
")); // Write stability dashboard link match self.item.inner { @@ -1340,8 +1340,8 @@ impl<'a> fmt::Show for Item<'a> { try!(write!(fmt, r##" - [collapse all] - [expand all] + [-] +  [+] "##)); // Write `src` tag @@ -1360,7 +1360,7 @@ impl<'a> fmt::Show for Item<'a> { } } - try!(write!(fmt, "")); + try!(write!(fmt, "
")); try!(write!(fmt, "

\n")); diff --git a/src/librustdoc/html/static/main.css b/src/librustdoc/html/static/main.css index f579123fc462b..e41566e07fd81 100644 --- a/src/librustdoc/html/static/main.css +++ b/src/librustdoc/html/static/main.css @@ -252,8 +252,19 @@ nav.sub { .docblock h3, .docblock h4, .docblock h5 { font-size: 1em; } .content .out-of-band { - float: right; font-size: 23px; + width: 40%; + margin: 0px; + padding: 0px; + text-align: right; + display: inline-block; +} + +.content .in-band { + width: 60%; + margin: 0px; + padding: 0px; + display: inline-block; } .content table { @@ -282,8 +293,8 @@ nav.sub { } .content .multi-column li { width: 100%; display: inline-block; } -.content .method { - font-size: 1em; +.content .method { + font-size: 1em; position: relative; } .content .methods .docblock { margin-left: 40px; } @@ -455,8 +466,8 @@ pre.rust { position: relative; } top: 0; right: 10px; font-size: 150%; - -webkit-transform: scaleX(-1); - transform: scaleX(-1); + -webkit-transform: scaleX(-1); + transform: scaleX(-1); } .methods .section-header { @@ -470,22 +481,6 @@ pre.rust { position: relative; } content: '\2002\00a7\2002'; } -/* Media Queries */ - -@media (max-width: 700px) { - .sidebar { - display: none; - } - - .content { - margin-left: 0px; - } - - nav.sub { - margin: 0 auto; - } -} - .collapse-toggle { font-weight: 100; position: absolute; @@ -518,3 +513,59 @@ pre.rust { position: relative; } color: #999; font-style: italic; } + + + +/* Media Queries */ + +@media (max-width: 700px) { + body { + padding-top: 0px; + } + + .sidebar { + height: 40px; + min-height: 40px; + width: 100%; + margin: 0px; + padding: 0px; + position: static; + } + + .sidebar .location { + float: left; + margin: 0px; + padding: 5px; + width: 60%; + background: inherit; + text-align: left; + font-size: 24px; + } + + .sidebar img { + width: 35px; + margin-top: 5px; + margin-bottom: 0px; + float: left; + } + + nav.sub { + margin: 0 auto; + } + + .sidebar .block { + display: none; + } + + .content { + margin-left: 0px; + } + + .toggle-wrapper > .collapse-toggle { + left: 0px; + } + + .toggle-wrapper { + height: 1.5em; + } +} From 0a6c8e8dbcec7544595ed8b29c896d6b7fa6e0d2 Mon Sep 17 00:00:00 2001 From: Kevin Butler Date: Thu, 7 Aug 2014 02:11:13 +0100 Subject: [PATCH 13/25] libcollections: Fix RingBuf growth for non-power-of-two capacities --- src/libcollections/ringbuf.rs | 47 ++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs index 0cde7a90e9c89..84b5c5bb9985b 100644 --- a/src/libcollections/ringbuf.rs +++ b/src/libcollections/ringbuf.rs @@ -403,11 +403,11 @@ impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {} fn grow(nelts: uint, loptr: &mut uint, elts: &mut Vec>) { assert_eq!(nelts, elts.len()); let lo = *loptr; - let newlen = nelts * 2; - elts.reserve(newlen); + elts.reserve(nelts * 2); + let newlen = elts.capacity(); /* fill with None */ - for _ in range(elts.len(), elts.capacity()) { + for _ in range(elts.len(), newlen) { elts.push(None); } @@ -750,6 +750,47 @@ mod tests { assert_eq!(d.len(), 1); } + #[test] + fn test_with_capacity_non_power_two() { + let mut d3 = RingBuf::with_capacity(3); + d3.push(1i); + + // X = None, | = lo + // [|1, X, X] + assert_eq!(d3.pop_front(), Some(1)); + // [X, |X, X] + assert_eq!(d3.front(), None); + + // [X, |3, X] + d3.push(3); + // [X, |3, 6] + d3.push(6); + // [X, X, |6] + assert_eq!(d3.pop_front(), Some(3)); + + // Pushing the lo past half way point to trigger + // the 'B' scenario for growth + // [9, X, |6] + d3.push(9); + // [9, 12, |6] + d3.push(12); + + d3.push(15); + // There used to be a bug here about how the + // RingBuf made growth assumptions about the + // underlying Vec which didn't hold and lead + // to corruption. + // (Vec grows to next power of two) + //good- [9, 12, 15, X, X, X, X, |6] + //bug- [15, 12, X, X, X, |6, X, X] + assert_eq!(d3.pop_front(), Some(6)); + + // Which leads us to the following state which + // would be a failure case. + //bug- [15, 12, X, X, X, X, |X, X] + assert_eq!(d3.front(), Some(&9)); + } + #[test] fn test_reserve_exact() { let mut d = RingBuf::new(); From be8285395aa6822650a5655e6292812f8954472a Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 25 Jul 2014 10:01:42 +1000 Subject: [PATCH 14/25] rustc: gensym the module names for --test to avoid introducing user-accessible names. This requires avoiding `quote_...!` for constructing the parts of the __test module, since that stringifies and reinterns the idents, losing the special gensym'd nature of them. (#15962.) --- src/librustc/front/test.rs | 115 ++++++++++-------- .../compile-fail/inaccessible-test-modules.rs | 19 +++ 2 files changed, 84 insertions(+), 50 deletions(-) create mode 100644 src/test/compile-fail/inaccessible-test-modules.rs diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index 0fce75c8369bc..c2581fb888fdf 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -206,7 +206,7 @@ fn generate_test_harness(sess: &Session, krate: ast::Crate) -> ast::Crate { }), path: Vec::new(), testfns: Vec::new(), - reexport_mod_ident: token::str_to_ident("__test_reexports"), + reexport_mod_ident: token::gensym_ident("__test_reexports"), is_test_crate: is_test_crate(&krate), config: krate.config.clone(), }; @@ -384,7 +384,7 @@ fn mk_test_module(cx: &TestCtxt) -> Gc { let item_ = ast::ItemMod(testmod); let item = ast::Item { - ident: token::str_to_ident("__test"), + ident: token::gensym_ident("__test"), attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: item_, @@ -417,11 +417,27 @@ fn mk_tests(cx: &TestCtxt) -> Gc { // The vector of test_descs for this crate let test_descs = mk_test_descs(cx); - (quote_item!(&cx.ext_cx, - pub static TESTS : &'static [self::test::TestDescAndFn] = - $test_descs - ; - )).unwrap() + // FIXME #15962: should be using quote_item, but that stringifies + // __test_reexports, causing it to be reinterned, losing the + // gensym information. + let sp = DUMMY_SP; + let ecx = &cx.ext_cx; + let struct_type = ecx.ty_path(ecx.path(sp, vec![ecx.ident_of("self"), + ecx.ident_of("test"), + ecx.ident_of("TestDescAndFn")]), + None); + let static_lt = ecx.lifetime(sp, token::special_idents::static_lifetime.name); + // &'static [self::test::TestDescAndFn] + let static_type = ecx.ty_rptr(sp, + ecx.ty(sp, ast::TyVec(struct_type)), + Some(static_lt), + ast::MutImmutable); + // static TESTS: $static_type = &[...]; + ecx.item_static(sp, + ecx.ident_of("TESTS"), + static_type, + ast::MutImmutable, + test_descs) } fn is_test_crate(krate: &ast::Crate) -> bool { @@ -448,59 +464,58 @@ fn mk_test_descs(cx: &TestCtxt) -> Gc { } fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> Gc { + // FIXME #15962: should be using quote_expr, but that stringifies + // __test_reexports, causing it to be reinterned, losing the + // gensym information. + let span = test.span; let path = test.path.clone(); + let ecx = &cx.ext_cx; + let self_id = ecx.ident_of("self"); + let test_id = ecx.ident_of("test"); + + // creates self::test::$name + let test_path = |name| { + ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)]) + }; + // creates $name: $expr + let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr); debug!("encoding {}", ast_util::path_name_i(path.as_slice())); - let name_lit: ast::Lit = - nospan(ast::LitStr(token::intern_and_get_ident( - ast_util::path_name_i(path.as_slice()).as_slice()), - ast::CookedStr)); + // path to the #[test] function: "foo::bar::baz" + let path_string = ast_util::path_name_i(path.as_slice()); + let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string.as_slice())); - let name_expr = box(GC) ast::Expr { - id: ast::DUMMY_NODE_ID, - node: ast::ExprLit(box(GC) name_lit), - span: span - }; + // self::test::StaticTestName($name_expr) + let name_expr = ecx.expr_call(span, + ecx.expr_path(test_path("StaticTestName")), + vec![name_expr]); - let mut visible_path = vec![cx.reexport_mod_ident.clone()]; - visible_path.extend(path.move_iter()); - let fn_path = cx.ext_cx.path_global(DUMMY_SP, visible_path); + let ignore_expr = ecx.expr_bool(span, test.ignore); + let fail_expr = ecx.expr_bool(span, test.should_fail); - let fn_expr = box(GC) ast::Expr { - id: ast::DUMMY_NODE_ID, - node: ast::ExprPath(fn_path), - span: span, - }; + // self::test::TestDesc { ... } + let desc_expr = ecx.expr_struct( + span, + test_path("TestDesc"), + vec![field("name", name_expr), + field("ignore", ignore_expr), + field("should_fail", fail_expr)]); - let t_expr = if test.bench { - quote_expr!(&cx.ext_cx, self::test::StaticBenchFn($fn_expr) ) - } else { - quote_expr!(&cx.ext_cx, self::test::StaticTestFn($fn_expr) ) - }; - let ignore_expr = if test.ignore { - quote_expr!(&cx.ext_cx, true ) - } else { - quote_expr!(&cx.ext_cx, false ) - }; + let mut visible_path = vec![cx.reexport_mod_ident.clone()]; + visible_path.extend(path.move_iter()); - let fail_expr = if test.should_fail { - quote_expr!(&cx.ext_cx, true ) - } else { - quote_expr!(&cx.ext_cx, false ) - }; + let fn_expr = ecx.expr_path(ecx.path_global(span, visible_path)); - let e = quote_expr!(&cx.ext_cx, - self::test::TestDescAndFn { - desc: self::test::TestDesc { - name: self::test::StaticTestName($name_expr), - ignore: $ignore_expr, - should_fail: $fail_expr - }, - testfn: $t_expr, - } - ); - e + let variant_name = if test.bench { "StaticBenchFn" } else { "StaticTestFn" }; + // self::test::$variant_name($fn_expr) + let testfn_expr = ecx.expr_call(span, ecx.expr_path(test_path(variant_name)), vec![fn_expr]); + + // self::test::TestDescAndFn { ... } + ecx.expr_struct(span, + test_path("TestDescAndFn"), + vec![field("desc", desc_expr), + field("testfn", testfn_expr)]) } diff --git a/src/test/compile-fail/inaccessible-test-modules.rs b/src/test/compile-fail/inaccessible-test-modules.rs new file mode 100644 index 0000000000000..b646f8083b8d5 --- /dev/null +++ b/src/test/compile-fail/inaccessible-test-modules.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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// compile-flags:--test + +// the `--test` harness creates modules with these textual names, but +// they should be inaccessible from normal code. +use x = __test; //~ ERROR unresolved import `__test` +use y = __test_reexports; //~ ERROR unresolved import `__test_reexports` + +#[test] +fn baz() {} From 2e87190a967ccbf7ba32afafd48d7586cc7114b3 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 7 Aug 2014 22:06:29 +1000 Subject: [PATCH 15/25] move a test into a run make, to check external affect rather than implementation details. (Mainly to avoid accessing the secret internal test module symbol name.) --- src/test/run-make/test-harness/Makefile | 7 ++++ .../run-make/test-harness/test-ignore-cfg.rs | 19 ++++++++++ src/test/run-pass/test-ignore-cfg.rs | 36 ------------------- 3 files changed, 26 insertions(+), 36 deletions(-) create mode 100644 src/test/run-make/test-harness/Makefile create mode 100644 src/test/run-make/test-harness/test-ignore-cfg.rs delete mode 100644 src/test/run-pass/test-ignore-cfg.rs diff --git a/src/test/run-make/test-harness/Makefile b/src/test/run-make/test-harness/Makefile new file mode 100644 index 0000000000000..4517af8e24be5 --- /dev/null +++ b/src/test/run-make/test-harness/Makefile @@ -0,0 +1,7 @@ +-include ../tools.mk + +all: + # check that #[ignore(cfg(...))] does the right thing. + $(RUSTC) --test test-ignore-cfg.rs --cfg ignorecfg + $(call RUN,test-ignore-cfg) | grep 'shouldnotignore ... ok' + $(call RUN,test-ignore-cfg) | grep 'shouldignore ... ignored' diff --git a/src/test/run-make/test-harness/test-ignore-cfg.rs b/src/test/run-make/test-harness/test-ignore-cfg.rs new file mode 100644 index 0000000000000..a8f88cc8544a9 --- /dev/null +++ b/src/test/run-make/test-harness/test-ignore-cfg.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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[test] +#[ignore(cfg(ignorecfg))] +fn shouldignore() { +} + +#[test] +#[ignore(cfg(noignorecfg))] +fn shouldnotignore() { +} diff --git a/src/test/run-pass/test-ignore-cfg.rs b/src/test/run-pass/test-ignore-cfg.rs deleted file mode 100644 index b36fbca2da048..0000000000000 --- a/src/test/run-pass/test-ignore-cfg.rs +++ /dev/null @@ -1,36 +0,0 @@ -// 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. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// compile-flags: --test --cfg ignorecfg -// ignore-pretty: does not work well with `--test` - -#[test] -#[ignore(cfg(ignorecfg))] -fn shouldignore() { -} - -#[test] -#[ignore(cfg(noignorecfg))] -fn shouldnotignore() { -} - -#[test] -fn checktests() { - // Pull the tests out of the secreturn test module - let tests = __test::TESTS; - - assert!( - tests.iter().any(|t| t.desc.name.to_string().as_slice() == "shouldignore" && - t.desc.ignore)); - - assert!( - tests.iter().any(|t| t.desc.name.to_string().as_slice() == "shouldnotignore" && - !t.desc.ignore)); -} From 881ab0e508a1cafce342b9287116873d67f5c92e Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 9 Aug 2014 00:01:05 +1000 Subject: [PATCH 16/25] testsuite: implement #[reexport_test_harness_name] to get access to the default entrypoint of the --test binary. This allows one to, e.g., run tests under libgreen by starting it manually, passing in the test entrypoint. --- src/librustc/front/test.rs | 61 +++++++++++++------ src/librustuv/lib.rs | 8 +-- src/libstd/lib.rs | 8 +-- src/test/run-pass/core-run-destroy.rs | 4 +- .../run-pass/reexport-test-harness-main.rs | 21 +++++++ src/test/run-pass/tcp-connect-timeouts.rs | 3 +- 6 files changed, 75 insertions(+), 30 deletions(-) create mode 100644 src/test/run-pass/reexport-test-harness-main.rs diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index c2581fb888fdf..14cda7d62c35d 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -51,6 +51,7 @@ struct TestCtxt<'a> { ext_cx: ExtCtxt<'a>, testfns: Vec, reexport_mod_ident: ast::Ident, + reexport_test_harness_main: Option, is_test_crate: bool, config: ast::CrateConfig, } @@ -64,8 +65,16 @@ pub fn modify_for_testing(sess: &Session, // command line options. let should_test = attr::contains_name(krate.config.as_slice(), "test"); + // Check for #[reexport_test_harness_main = "some_name"] which + // creates a `use some_name = __test::main;`. This needs to be + // unconditional, so that the attribute is still marked as used in + // non-test builds. + let reexport_test_harness_main = + attr::first_attr_value_str_by_name(krate.attrs.as_slice(), + "reexport_test_harness_main"); + if should_test { - generate_test_harness(sess, krate) + generate_test_harness(sess, reexport_test_harness_main, krate) } else { strip_test_functions(krate) } @@ -79,14 +88,17 @@ struct TestHarnessGenerator<'a> { impl<'a> fold::Folder for TestHarnessGenerator<'a> { fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { - let folded = fold::noop_fold_crate(c, self); + let mut folded = fold::noop_fold_crate(c, self); // Add a special __test module to the crate that will contain code // generated for the test harness - ast::Crate { - module: add_test_module(&self.cx, &folded.module), - .. folded + let (mod_, reexport) = mk_test_module(&self.cx, &self.cx.reexport_test_harness_main); + folded.module.items.push(mod_); + match reexport { + Some(re) => folded.module.view_items.push(re), + None => {} } + folded } fn fold_item(&mut self, i: Gc) -> SmallVector> { @@ -196,7 +208,9 @@ fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec, } } -fn generate_test_harness(sess: &Session, krate: ast::Crate) -> ast::Crate { +fn generate_test_harness(sess: &Session, + reexport_test_harness_main: Option, + krate: ast::Crate) -> ast::Crate { let mut cx: TestCtxt = TestCtxt { sess: sess, ext_cx: ExtCtxt::new(&sess.parse_sess, sess.opts.cfg.clone(), @@ -207,6 +221,7 @@ fn generate_test_harness(sess: &Session, krate: ast::Crate) -> ast::Crate { path: Vec::new(), testfns: Vec::new(), reexport_mod_ident: token::gensym_ident("__test_reexports"), + reexport_test_harness_main: reexport_test_harness_main, is_test_crate: is_test_crate(&krate), config: krate.config.clone(), }; @@ -314,14 +329,6 @@ fn should_fail(i: Gc) -> bool { attr::contains_name(i.attrs.as_slice(), "should_fail") } -fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod { - let testmod = mk_test_module(cx); - ast::Mod { - items: m.items.clone().append_one(testmod), - ..(*m).clone() - } -} - /* We're going to be building a module that looks more or less like: @@ -359,7 +366,8 @@ fn mk_std(cx: &TestCtxt) -> ast::ViewItem { } } -fn mk_test_module(cx: &TestCtxt) -> Gc { +fn mk_test_module(cx: &TestCtxt, reexport_test_harness_main: &Option) + -> (Gc, Option) { // Link to test crate let view_items = vec!(mk_std(cx)); @@ -383,18 +391,35 @@ fn mk_test_module(cx: &TestCtxt) -> Gc { }; let item_ = ast::ItemMod(testmod); + let mod_ident = token::gensym_ident("__test"); let item = ast::Item { - ident: token::gensym_ident("__test"), + ident: mod_ident, attrs: Vec::new(), id: ast::DUMMY_NODE_ID, node: item_, vis: ast::Public, span: DUMMY_SP, - }; + }; + let reexport = reexport_test_harness_main.as_ref().map(|s| { + // building `use = __test::main` + let reexport_ident = token::str_to_ident(s.get()); + + let use_path = + nospan(ast::ViewPathSimple(reexport_ident, + path_node(vec![mod_ident, token::str_to_ident("main")]), + ast::DUMMY_NODE_ID)); + + ast::ViewItem { + node: ast::ViewItemUse(box(GC) use_path), + attrs: vec![], + vis: ast::Inherited, + span: DUMMY_SP + } + }); debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); - box(GC) item + (box(GC) item, reexport) } fn nospan(t: T) -> codemap::Spanned { diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index 24b8c29785804..dd80ab3ee78a1 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -48,6 +48,8 @@ via `close` and `delete` methods. #![deny(unused_result, unused_must_use)] #![allow(visible_private_types)] +#![reexport_test_harness_main = "test_main"] + #[cfg(test)] extern crate green; #[cfg(test)] extern crate debug; #[cfg(test)] extern crate realrustuv = "rustuv"; @@ -76,13 +78,9 @@ pub use self::timer::TimerWatcher; pub use self::tty::TtyWatcher; // Run tests with libgreen instead of libnative. -// -// FIXME: This egregiously hacks around starting the test runner in a different -// threading mode than the default by reaching into the auto-generated -// '__test' module. #[cfg(test)] #[start] fn start(argc: int, argv: *const *const u8) -> int { - green::start(argc, argv, event_loop, __test::main) + green::start(argc, argv, event_loop, test_main) } mod macros; diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 125c3fdf5d90c..20fc7efeb574f 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -114,6 +114,8 @@ #![allow(deprecated)] #![deny(missing_doc)] +#![reexport_test_harness_main = "test_main"] + // When testing libstd, bring in libuv as the I/O backend so tests can print // things and all of the std::io tests have an I/O interface to run on top // of @@ -186,13 +188,9 @@ pub use unicode::char; pub use core_sync::comm; // Run tests with libgreen instead of libnative. -// -// FIXME: This egregiously hacks around starting the test runner in a different -// threading mode than the default by reaching into the auto-generated -// '__test' module. #[cfg(test)] #[start] fn start(argc: int, argv: *const *const u8) -> int { - green::start(argc, argv, rustuv::event_loop, __test::main) + green::start(argc, argv, rustuv::event_loop, test_main) } /* Exported macros */ diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index 8e84278c10e02..d187a6a8afebb 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -16,6 +16,8 @@ // instead of in std. #![feature(macro_rules)] +#![reexport_test_harness_main = "test_main"] + extern crate libc; extern crate native; @@ -55,7 +57,7 @@ macro_rules! iotest ( #[cfg(test)] #[start] fn start(argc: int, argv: *const *const u8) -> int { - green::start(argc, argv, rustuv::event_loop, __test::main) + green::start(argc, argv, rustuv::event_loop, test_main) } iotest!(fn test_destroy_once() { diff --git a/src/test/run-pass/reexport-test-harness-main.rs b/src/test/run-pass/reexport-test-harness-main.rs new file mode 100644 index 0000000000000..309ae1bcc56ec --- /dev/null +++ b/src/test/run-pass/reexport-test-harness-main.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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// ignore-pretty +// compile-flags:--test + +#![reexport_test_harness_main = "test_main"] + +#[cfg(test)] +fn _unused() { + // should resolve to the entry point function the --test harness + // creates. + test_main(); +} diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index d2408509fc582..6f6fff15814d5 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -18,6 +18,7 @@ #![feature(macro_rules, globs)] #![allow(experimental)] +#![reexport_test_harness_main = "test_main"] extern crate native; extern crate green; @@ -25,7 +26,7 @@ extern crate rustuv; #[cfg(test)] #[start] fn start(argc: int, argv: *const *const u8) -> int { - green::start(argc, argv, rustuv::event_loop, __test::main) + green::start(argc, argv, rustuv::event_loop, test_main) } macro_rules! iotest ( From adaf7a1d44574f412451a31214a8b1ff13bcaadd Mon Sep 17 00:00:00 2001 From: Chris Nixon Date: Fri, 8 Aug 2014 10:37:17 +0100 Subject: [PATCH 17/25] Move system header includes above valgrind.h include This allows rustc to be build under msys2's mingw64 gcc --- src/rt/rust_builtin.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/rt/rust_builtin.c b/src/rt/rust_builtin.c index 89cb27c1f1ae1..ba20f2c6f27f9 100644 --- a/src/rt/rust_builtin.c +++ b/src/rt/rust_builtin.c @@ -8,10 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/* Foreign builtins. */ - -#include "valgrind/valgrind.h" - #include #include #include @@ -41,6 +37,10 @@ #endif #endif +/* Foreign builtins. */ +//include valgrind.h after stdint.h so that uintptr_t is defined for msys2 w64 +#include "valgrind/valgrind.h" + #ifdef __ANDROID__ time_t timegm(struct tm *tm) From 1e229ee7c3e356064822883063c0e7c7660bba0a Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Thu, 7 Aug 2014 11:22:42 +0200 Subject: [PATCH 18/25] ast_map: Added iterator over all node id's that match a path suffix. This is useful e.g. for tools need a node-id, such as the flowgraph pretty printer, since it can avoids the need to first pretty-print the whole expanded,identified input in order to find out what the node-id actually is. It currently only supports path suffixes thst are made up of module names (e.g. you cannot use the type instantiation form `a::::b` or `option::Option::unwrap_or` as a path suffix for this tool, though the tool will produce paths that have non-modulues in the portion of the path that is not included in the suffix). (addressed review feedback too) --- src/libsyntax/ast_map/mod.rs | 133 ++++++++++++++++++++++++++++++++++- 1 file changed, 132 insertions(+), 1 deletion(-) diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 67de8e7aba102..94ffad40c6f5c 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -11,7 +11,7 @@ use abi; use ast::*; use ast_util; -use codemap::Span; +use codemap::{Span, Spanned}; use fold::Folder; use fold; use parse::token; @@ -203,6 +203,10 @@ pub struct Map { } impl Map { + fn entry_count(&self) -> uint { + self.map.borrow().len() + } + fn find_entry(&self, id: NodeId) -> Option { let map = self.map.borrow(); if map.len() > id as uint { @@ -405,6 +409,20 @@ impl Map { f(attrs) } + /// Returns an iterator that yields the node id's with paths that + /// match `parts`. (Requires `parts` is non-empty.) + /// + /// For example, if given `parts` equal to `["bar", "quux"]`, then + /// the iterator will produce node id's for items with paths + /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and + /// any other such items it can find in the map. + pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S]) -> NodesMatchingSuffix<'a,S> { + NodesMatchingSuffix { map: self, + item_name: parts.last().unwrap(), + where: parts.slice_to(parts.len() - 1), + idx: 0 } + } + pub fn opt_span(&self, id: NodeId) -> Option { let sp = match self.find(id) { Some(NodeItem(item)) => item.span, @@ -438,6 +456,119 @@ impl Map { } } +pub struct NodesMatchingSuffix<'a, S> { + map: &'a Map, + item_name: &'a S, + where: &'a [S], + idx: NodeId, +} + +impl<'a,S:Str> NodesMatchingSuffix<'a,S> { + /// Returns true only if some suffix of the module path for parent + /// matches `self.where`. + /// + /// In other words: let `[x_0,x_1,...,x_k]` be `self.where`; + /// returns true if parent's path ends with the suffix + /// `x_0::x_1::...::x_k`. + fn suffix_matches(&self, parent: NodeId) -> bool { + let mut cursor = parent; + for part in self.where.iter().rev() { + let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) { + None => return false, + Some((node_id, name)) => (node_id, name), + }; + if part.as_slice() != mod_name.as_str() { + return false; + } + cursor = self.map.get_parent(mod_id); + } + return true; + + // Finds the first mod in parent chain for `id`, along with + // that mod's name. + // + // If `id` itself is a mod named `m` with parent `p`, then + // returns `Some(id, m, p)`. If `id` has no mod in its parent + // chain, then returns `None`. + fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> { + loop { + match map.find(id) { + None => return None, + Some(NodeItem(item)) if item_is_mod(&*item) => + return Some((id, item.ident.name)), + _ => {} + } + let parent = map.get_parent(id); + if parent == id { return None } + id = parent; + } + + fn item_is_mod(item: &Item) -> bool { + match item.node { + ItemMod(_) => true, + _ => false, + } + } + } + } + + // We are looking at some node `n` with a given name and parent + // id; do their names match what I am seeking? + fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool { + name.as_str() == self.item_name.as_slice() && + self.suffix_matches(parent_of_n) + } +} + +impl<'a,S:Str> Iterator for NodesMatchingSuffix<'a,S> { + fn next(&mut self) -> Option { + loop { + let idx = self.idx; + if idx as uint >= self.map.entry_count() { + return None; + } + self.idx += 1; + let (p, name) = match self.map.find_entry(idx) { + Some(EntryItem(p, n)) => (p, n.name()), + Some(EntryForeignItem(p, n)) => (p, n.name()), + Some(EntryTraitMethod(p, n)) => (p, n.name()), + Some(EntryMethod(p, n)) => (p, n.name()), + Some(EntryVariant(p, n)) => (p, n.name()), + _ => continue, + }; + if self.matches_names(p, name) { + return Some(idx) + } + } + } +} + +trait Named { + fn name(&self) -> Name; +} + +impl Named for Spanned { fn name(&self) -> Name { self.node.name() } } + +impl Named for Item { fn name(&self) -> Name { self.ident.name } } +impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } } +impl Named for Variant_ { fn name(&self) -> Name { self.name.name } } +impl Named for TraitMethod { + fn name(&self) -> Name { + match *self { + Required(ref tm) => tm.ident.name, + Provided(m) => m.name(), + } + } +} +impl Named for Method { + fn name(&self) -> Name { + match self.node { + MethDecl(i, _, _, _, _, _, _, _) => i.name, + MethMac(_) => fail!("encountered unexpanded method macro."), + } + } +} + pub trait FoldOps { fn new_id(&self, id: NodeId) -> NodeId { id From db139e56525b786c23b04de5d62f0b2f862e5ee0 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Thu, 7 Aug 2014 11:25:31 +0200 Subject: [PATCH 19/25] refactored pprust::State constructor methods out from `pprust::print_crate`. (Groundwork for pretty-printing only selected items in an input crate.) --- src/libsyntax/print/pprust.rs | 75 ++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 24 deletions(-) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index d60e4cb3b542b..9d4b7343c8a15 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -97,35 +97,62 @@ pub fn print_crate<'a>(cm: &'a CodeMap, out: Box, ann: &'a PpAnn, is_expanded: bool) -> IoResult<()> { - let (cmnts, lits) = comments::gather_comments_and_literals( - span_diagnostic, - filename, - input - ); - let mut s = State { - s: pp::mk_printer(out, default_columns), - cm: Some(cm), - comments: Some(cmnts), - // If the code is post expansion, don't use the table of - // literals, since it doesn't correspond with the literals - // in the AST anymore. - literals: if is_expanded { - None - } else { - Some(lits) - }, - cur_cmnt_and_lit: CurrentCommentAndLiteral { - cur_cmnt: 0, - cur_lit: 0 - }, - boxes: Vec::new(), - ann: ann - }; + let mut s = State::new_from_input(cm, + span_diagnostic, + filename, + input, + out, + ann, + is_expanded); try!(s.print_mod(&krate.module, krate.attrs.as_slice())); try!(s.print_remaining_comments()); eof(&mut s.s) } +impl<'a> State<'a> { + pub fn new_from_input(cm: &'a CodeMap, + span_diagnostic: &diagnostic::SpanHandler, + filename: String, + input: &mut io::Reader, + out: Box, + ann: &'a PpAnn, + is_expanded: bool) -> State<'a> { + let (cmnts, lits) = comments::gather_comments_and_literals( + span_diagnostic, + filename, + input); + + State::new( + cm, + out, + ann, + Some(cmnts), + // If the code is post expansion, don't use the table of + // literals, since it doesn't correspond with the literals + // in the AST anymore. + if is_expanded { None } else { Some(lits) }) + } + + pub fn new(cm: &'a CodeMap, + out: Box, + ann: &'a PpAnn, + comments: Option>, + literals: Option>) -> State<'a> { + State { + s: pp::mk_printer(out, default_columns), + cm: Some(cm), + comments: comments, + literals: literals, + cur_cmnt_and_lit: CurrentCommentAndLiteral { + cur_cmnt: 0, + cur_lit: 0 + }, + boxes: Vec::new(), + ann: ann + } + } +} + pub fn to_string(f: |&mut State| -> IoResult<()>) -> String { let mut s = rust_printer(box MemWriter::new()); f(&mut s).unwrap(); From ccabd333398393108b45ba05cb3fbf2370bfd775 Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Thu, 7 Aug 2014 14:21:15 +0200 Subject: [PATCH 20/25] Helper method for `pprust::State` for printing instances of `ast_map::Node`. --- src/libsyntax/ast_map/mod.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 94ffad40c6f5c..881ee4fd8d13e 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -21,6 +21,7 @@ use util::small_vector::SmallVector; use std::cell::RefCell; use std::fmt; use std::gc::{Gc, GC}; +use std::io::IoResult; use std::iter; use std::slice; @@ -819,6 +820,34 @@ pub fn map_decoded_item(map: &Map, ii } +pub trait NodePrinter { + fn print_node(&mut self, node: &Node) -> IoResult<()>; +} + +impl<'a> NodePrinter for pprust::State<'a> { + fn print_node(&mut self, node: &Node) -> IoResult<()> { + match *node { + NodeItem(a) => self.print_item(&*a), + NodeForeignItem(a) => self.print_foreign_item(&*a), + NodeTraitMethod(a) => self.print_trait_method(&*a), + NodeMethod(a) => self.print_method(&*a), + NodeVariant(a) => self.print_variant(&*a), + NodeExpr(a) => self.print_expr(&*a), + NodeStmt(a) => self.print_stmt(&*a), + NodePat(a) => self.print_pat(&*a), + NodeBlock(a) => self.print_block(&*a), + NodeLifetime(a) => self.print_lifetime(&*a), + + // these cases do not carry enough information in the + // ast_map to reconstruct their full structure for pretty + // printing. + NodeLocal(_) => fail!("cannot print isolated Local"), + NodeArg(_) => fail!("cannot print isolated Arg"), + NodeStructCtor(_) => fail!("cannot print isolated StructCtor"), + } + } +} + fn node_id_to_string(map: &Map, id: NodeId) -> String { match map.find(id) { Some(NodeItem(item)) => { From 63dac176da1316d747a7f54b344eb3e08b9e6dab Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Thu, 7 Aug 2014 18:22:24 +0200 Subject: [PATCH 21/25] pretty-printer: let users choose particular items to pretty print. With this change: * `--pretty variant=` will print the item associated with `` (where `` is an integer for some node-id in the AST, and `variant` means one of {`normal`,`expanded`,...}). * `--pretty variant=` will print all of the items that match the `` (where `` is a suffix of a path, and `variant` again means one of {`normal`,`expanded`,...}). Example 1: the suffix `typeck::check::check_struct` matches the item with the path `rustc::middle::typeck::check::check_struct` when compiling the `rustc` crate. Example 2: the suffix `and` matches `core::option::Option::and` and `core::result::Result::and` when compiling the `core` crate. Both of the `--pretty variant=...` modes will include the full path to the item in a comment that follows the item. Note that when multiple paths match, then either: 1. all matching items are printed, in series; this is what happens in the usual pretty-print variants, or 2. the compiler signals an error; this is what happens in flowgraph printing. ---- Some drive-by improvements: Heavily refactored the pretty-printing glue in driver.rs, introducing a couple local traits to avoid cut-and-pasting very code segments that differed only in how they accessed the `Session` or the `ast_map::Map`. (Note the previous code had three similar calls to `print_crate` which have all been unified in this revision; the addition of printing individual node-ids exacerbated the situation beyond tolerance.) We may want to consider promoting some of these traits, e.g. `SessionCarrier`, for use more generally elsewhere in the compiler; right now I have to double check how to access the `Session` depending on what context I am hacking in. Refactored `PpMode` to make the data directly reflect the fundamental difference in the categories (in terms of printing source-code with various annotations, versus printing a control-flow graph). (also, addressed review feedback.) --- src/librustc/driver/driver.rs | 349 +++++++++++++++++++++++++++++----- src/librustc/driver/mod.rs | 45 +++-- 2 files changed, 319 insertions(+), 75 deletions(-) diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 9796aab51fb6b..477fc5e1c0f30 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -11,9 +11,9 @@ use back::link; use driver::session::Session; -use driver::{config, PpMode}; +use driver::{config, PpMode, PpSourceMode}; use driver::{PpmFlowGraph, PpmExpanded, PpmExpandedIdentified, PpmTyped}; -use driver::{PpmIdentified}; +use driver::{PpmIdentified, PpmNormal, PpmSource}; use front; use lint; use llvm::{ContextRef, ModuleRef}; @@ -39,11 +39,15 @@ use dot = graphviz; use serialize::{json, Encodable}; +use std::from_str::FromStr; use std::io; use std::io::fs; use std::io::MemReader; +use std::option; use syntax::ast; +use syntax::ast_map; use syntax::ast_map::blocks; +use syntax::ast_map::NodePrinter; use syntax::attr; use syntax::attr::{AttrMetaMethods}; use syntax::diagnostics; @@ -602,7 +606,90 @@ fn write_out_deps(sess: &Session, } } -struct IdentifiedAnnotation; +// This slightly awkward construction is to allow for each PpMode to +// choose whether it needs to do analyses (which can consume the +// Session) and then pass through the session (now attached to the +// analysis results) on to the chosen pretty-printer, along with the +// `&PpAnn` object. +// +// Note that since the `&PrinterSupport` is freshly constructed on each +// call, it would not make sense to try to attach the lifetime of `self` +// to the lifetime of the `&PrinterObject`. +// +// (The `use_once_payload` is working around the current lack of once +// functions in the compiler.) +trait CratePrinter { + /// Constructs a `PrinterSupport` object and passes it to `f`. + fn call_with_pp_support(&self, + sess: Session, + krate: &ast::Crate, + ast_map: Option, + id: String, + use_once_payload: B, + f: |&PrinterSupport, B| -> A) -> A; +} + +trait SessionCarrier { + /// Provides a uniform interface for re-extracting a reference to a + /// `Session` from a value that now owns it. + fn sess<'a>(&'a self) -> &'a Session; +} + +trait AstMapCarrier { + /// Provides a uniform interface for re-extracting a reference to an + /// `ast_map::Map` from a value that now owns it. + fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map>; +} + +trait PrinterSupport : SessionCarrier + AstMapCarrier { + /// Produces the pretty-print annotation object. + /// + /// Usually implemented via `self as &pprust::PpAnn`. + /// + /// (Rust does not yet support upcasting from a trait object to + /// an object for one of its super-traits.) + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn; +} + +struct NoAnn { + sess: Session, + ast_map: Option, +} + +impl PrinterSupport for NoAnn { + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn } +} + +impl SessionCarrier for NoAnn { + fn sess<'a>(&'a self) -> &'a Session { &self.sess } +} + +impl AstMapCarrier for NoAnn { + fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> { + self.ast_map.as_ref() + } +} + +impl pprust::PpAnn for NoAnn {} + +struct IdentifiedAnnotation { + sess: Session, + ast_map: Option, +} + +impl PrinterSupport for IdentifiedAnnotation { + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn } +} + +impl SessionCarrier for IdentifiedAnnotation { + fn sess<'a>(&'a self) -> &'a Session { &self.sess } +} + +impl AstMapCarrier for IdentifiedAnnotation { + fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> { + self.ast_map.as_ref() + } +} impl pprust::PpAnn for IdentifiedAnnotation { fn pre(&self, @@ -642,6 +729,20 @@ struct TypedAnnotation { analysis: CrateAnalysis, } +impl PrinterSupport for TypedAnnotation { + fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn } +} + +impl SessionCarrier for TypedAnnotation { + fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess } +} + +impl AstMapCarrier for TypedAnnotation { + fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> { + Some(&self.analysis.ty_cx.map) + } +} + impl pprust::PpAnn for TypedAnnotation { fn pre(&self, s: &mut pprust::State, @@ -690,25 +791,155 @@ fn gather_flowgraph_variants(sess: &Session) -> Vec { variants } +#[deriving(Clone, Show)] +pub enum UserIdentifiedItem { + ItemViaNode(ast::NodeId), + ItemViaPath(Vec), +} + +impl FromStr for UserIdentifiedItem { + fn from_str(s: &str) -> Option { + let extract_path_parts = || { + let v : Vec<_> = s.split_str("::") + .map(|x|x.to_string()) + .collect(); + Some(ItemViaPath(v)) + }; + + from_str(s).map(ItemViaNode).or_else(extract_path_parts) + } +} + +enum NodesMatchingUII<'a> { + NodesMatchingDirect(option::Item), + NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, String>), +} + +impl<'a> Iterator for NodesMatchingUII<'a> { + fn next(&mut self) -> Option { + match self { + &NodesMatchingDirect(ref mut iter) => iter.next(), + &NodesMatchingSuffix(ref mut iter) => iter.next(), + } + } +} + +impl UserIdentifiedItem { + fn reconstructed_input(&self) -> String { + match *self { + ItemViaNode(node_id) => node_id.to_string(), + ItemViaPath(ref parts) => parts.connect("::"), + } + } + + fn all_matching_node_ids<'a>(&'a self, map: &'a ast_map::Map) -> NodesMatchingUII<'a> { + match *self { + ItemViaNode(node_id) => + NodesMatchingDirect(Some(node_id).move_iter()), + ItemViaPath(ref parts) => + NodesMatchingSuffix(map.nodes_matching_suffix(parts.as_slice())), + } + } + + fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId { + let fail_because = |is_wrong_because| -> ast::NodeId { + let message = + format!("{:s} needs NodeId (int) or unique \ + path suffix (b::c::d); got {:s}, which {:s}", + user_option, + self.reconstructed_input(), + is_wrong_because); + sess.fatal(message.as_slice()) + }; + + let mut saw_node = ast::DUMMY_NODE_ID; + let mut seen = 0u; + for node in self.all_matching_node_ids(map) { + saw_node = node; + seen += 1; + if seen > 1 { + fail_because("does not resolve uniquely"); + } + } + if seen == 0 { + fail_because("does not resolve to any item"); + } + + assert!(seen == 1); + return saw_node; + } +} + +impl CratePrinter for PpSourceMode { + fn call_with_pp_support(&self, + sess: Session, + krate: &ast::Crate, + ast_map: Option, + id: String, + payload: B, + f: |&PrinterSupport, B| -> A) -> A { + match *self { + PpmNormal | PpmExpanded => { + let annotation = NoAnn { sess: sess, ast_map: ast_map }; + f(&annotation, payload) + } + + PpmIdentified | PpmExpandedIdentified => { + let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map }; + f(&annotation, payload) + } + PpmTyped => { + let ast_map = ast_map.expect("--pretty=typed missing ast_map"); + let analysis = phase_3_run_analysis_passes(sess, krate, ast_map, id); + let annotation = TypedAnnotation { analysis: analysis }; + f(&annotation, payload) + } + } + } +} + +fn needs_ast_map(ppm: &PpMode, opt_uii: &Option) -> bool { + match *ppm { + PpmSource(PpmNormal) | + PpmSource(PpmIdentified) => opt_uii.is_some(), + + PpmSource(PpmExpanded) | + PpmSource(PpmExpandedIdentified) | + PpmSource(PpmTyped) | + PpmFlowGraph => true + } +} + +fn needs_expansion(ppm: &PpMode) -> bool { + match *ppm { + PpmSource(PpmNormal) | + PpmSource(PpmIdentified) => false, + + PpmSource(PpmExpanded) | + PpmSource(PpmExpandedIdentified) | + PpmSource(PpmTyped) | + PpmFlowGraph => true + } +} pub fn pretty_print_input(sess: Session, cfg: ast::CrateConfig, input: &Input, ppm: PpMode, + opt_uii: Option, ofile: Option) { let krate = phase_1_parse_input(&sess, cfg, input); let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input); - let (krate, ast_map, is_expanded) = match ppm { - PpmExpanded | PpmExpandedIdentified | PpmTyped | PpmFlowGraph(_) => { - let (krate, ast_map) - = match phase_2_configure_and_expand(&sess, krate, - id.as_slice(), None) { - None => return, - Some(p) => p, - }; - (krate, Some(ast_map), true) - } - _ => (krate, None, false) + let is_expanded = needs_expansion(&ppm); + let (krate, ast_map) = if needs_ast_map(&ppm, &opt_uii) { + let k = phase_2_configure_and_expand(&sess, krate, id.as_slice(), None); + let (krate, ast_map) = match k { + None => return, + Some(p) => p, + }; + (krate, Some(ast_map)) + } else { + (krate, None) }; let src_name = source_name(input); @@ -729,38 +960,63 @@ pub fn pretty_print_input(sess: Session, } } }; - match ppm { - PpmIdentified | PpmExpandedIdentified => { - pprust::print_crate(sess.codemap(), - sess.diagnostic(), - &krate, - src_name.to_string(), - &mut rdr, - out, - &IdentifiedAnnotation, - is_expanded) - } - PpmTyped => { - let ast_map = ast_map.expect("--pretty=typed missing ast_map"); - let analysis = phase_3_run_analysis_passes(sess, &krate, ast_map, id); - let annotation = TypedAnnotation { - analysis: analysis - }; - pprust::print_crate(annotation.analysis.ty_cx.sess.codemap(), - annotation.analysis.ty_cx.sess.diagnostic(), - &krate, - src_name.to_string(), - &mut rdr, - out, - &annotation, - is_expanded) - } - PpmFlowGraph(nodeid) => { + + match (ppm, opt_uii) { + (PpmSource(s), None) => + s.call_with_pp_support( + sess, &krate, ast_map, id, out, |annotation, out| { + debug!("pretty printing source code {}", s); + let sess = annotation.sess(); + pprust::print_crate(sess.codemap(), + sess.diagnostic(), + &krate, + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + is_expanded) + }), + + (PpmSource(s), Some(uii)) => + s.call_with_pp_support( + sess, &krate, ast_map, id, (out,uii), |annotation, (out,uii)| { + debug!("pretty printing source code {}", s); + let sess = annotation.sess(); + let ast_map = annotation.ast_map() + .expect("--pretty missing ast_map"); + let mut pp_state = + pprust::State::new_from_input(sess.codemap(), + sess.diagnostic(), + src_name.to_string(), + &mut rdr, + out, + annotation.pp_ann(), + is_expanded); + for node_id in uii.all_matching_node_ids(ast_map) { + let node = ast_map.get(node_id); + try!(pp_state.print_node(&node)); + try!(pp::space(&mut pp_state.s)); + try!(pp_state.synth_comment(ast_map.path_to_string(node_id))); + try!(pp::hardbreak(&mut pp_state.s)); + } + pp::eof(&mut pp_state.s) + }), + + (PpmFlowGraph, opt_uii) => { + debug!("pretty printing flow graph for {}", opt_uii); + let uii = opt_uii.unwrap_or_else(|| { + sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or + unique path suffix (b::c::d)").as_slice()) + + }); let ast_map = ast_map.expect("--pretty flowgraph missing ast_map"); + let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map); + let node = ast_map.find(nodeid).unwrap_or_else(|| { sess.fatal(format!("--pretty flowgraph couldn't find id: {}", nodeid).as_slice()) }); + let code = blocks::Code::from_node(node); match code { Some(code) => { @@ -783,18 +1039,7 @@ pub fn pretty_print_input(sess: Session, } } } - _ => { - pprust::print_crate(sess.codemap(), - sess.diagnostic(), - &krate, - src_name.to_string(), - &mut rdr, - out, - &pprust::NoAnn, - is_expanded) - } }.unwrap() - } fn print_flowgraph(variants: Vec, diff --git a/src/librustc/driver/mod.rs b/src/librustc/driver/mod.rs index a5df63a9e23fa..05762aa3db276 100644 --- a/src/librustc/driver/mod.rs +++ b/src/librustc/driver/mod.rs @@ -99,11 +99,11 @@ fn run_compiler(args: &[String]) { parse_pretty(&sess, a.as_slice()) }); match pretty { - Some::(ppm) => { - driver::pretty_print_input(sess, cfg, &input, ppm, ofile); + Some((ppm, opt_uii)) => { + driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile); return; } - None:: => {/* continue */ } + None => {/* continue */ } } let r = matches.opt_strs("Z"); @@ -340,42 +340,41 @@ fn print_crate_info(sess: &Session, } } -pub enum PpMode { +#[deriving(PartialEq, Show)] +pub enum PpSourceMode { PpmNormal, PpmExpanded, PpmTyped, PpmIdentified, PpmExpandedIdentified, - PpmFlowGraph(ast::NodeId), } -pub fn parse_pretty(sess: &Session, name: &str) -> PpMode { +#[deriving(PartialEq, Show)] +pub enum PpMode { + PpmSource(PpSourceMode), + PpmFlowGraph, +} + +fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option) { let mut split = name.splitn('=', 1); let first = split.next().unwrap(); let opt_second = split.next(); - match (opt_second, first) { - (None, "normal") => PpmNormal, - (None, "expanded") => PpmExpanded, - (None, "typed") => PpmTyped, - (None, "expanded,identified") => PpmExpandedIdentified, - (None, "identified") => PpmIdentified, - (arg, "flowgraph") => { - match arg.and_then(from_str) { - Some(id) => PpmFlowGraph(id), - None => { - sess.fatal(format!("`pretty flowgraph=` needs \ - an integer ; got {}", - arg.unwrap_or("nothing")).as_slice()) - } - } - } + let first = match first { + "normal" => PpmSource(PpmNormal), + "expanded" => PpmSource(PpmExpanded), + "typed" => PpmSource(PpmTyped), + "expanded,identified" => PpmSource(PpmExpandedIdentified), + "identified" => PpmSource(PpmIdentified), + "flowgraph" => PpmFlowGraph, _ => { sess.fatal(format!( "argument to `pretty` must be one of `normal`, \ `expanded`, `flowgraph=`, `typed`, `identified`, \ or `expanded,identified`; got {}", name).as_slice()); } - } + }; + let opt_second = opt_second.and_then::(from_str); + (first, opt_second) } fn parse_crate_attrs(sess: &Session, input: &Input) -> From 683c454f14bf505ea5bf2677ab399dc98880067b Mon Sep 17 00:00:00 2001 From: "Felix S. Klock II" Date: Sat, 9 Aug 2014 09:59:47 +0200 Subject: [PATCH 22/25] pretty printer: Added some `run-make` tests of path-suffix lookup functionality. --- .../pretty-print-path-suffix/Makefile | 9 ++++++ .../run-make/pretty-print-path-suffix/foo.pp | 15 ++++++++++ .../pretty-print-path-suffix/foo_method.pp | 16 +++++++++++ .../pretty-print-path-suffix/input.rs | 28 +++++++++++++++++++ .../pretty-print-path-suffix/nest_foo.pp | 14 ++++++++++ 5 files changed, 82 insertions(+) create mode 100644 src/test/run-make/pretty-print-path-suffix/Makefile create mode 100644 src/test/run-make/pretty-print-path-suffix/foo.pp create mode 100644 src/test/run-make/pretty-print-path-suffix/foo_method.pp create mode 100644 src/test/run-make/pretty-print-path-suffix/input.rs create mode 100644 src/test/run-make/pretty-print-path-suffix/nest_foo.pp diff --git a/src/test/run-make/pretty-print-path-suffix/Makefile b/src/test/run-make/pretty-print-path-suffix/Makefile new file mode 100644 index 0000000000000..f58a6527ac688 --- /dev/null +++ b/src/test/run-make/pretty-print-path-suffix/Makefile @@ -0,0 +1,9 @@ +-include ../tools.mk + +all: + $(RUSTC) -o $(TMPDIR)/foo.out --pretty normal=foo input.rs + $(RUSTC) -o $(TMPDIR)/nest_foo.out --pretty normal=nest::foo input.rs + $(RUSTC) -o $(TMPDIR)/foo_method.out --pretty normal=foo_method input.rs + diff -u $(TMPDIR)/foo.out foo.pp + diff -u $(TMPDIR)/nest_foo.out nest_foo.pp + diff -u $(TMPDIR)/foo_method.out foo_method.pp diff --git a/src/test/run-make/pretty-print-path-suffix/foo.pp b/src/test/run-make/pretty-print-path-suffix/foo.pp new file mode 100644 index 0000000000000..f3130a8044a20 --- /dev/null +++ b/src/test/run-make/pretty-print-path-suffix/foo.pp @@ -0,0 +1,15 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +pub fn foo() -> i32 { 45 } /* foo */ + + +pub fn foo() -> &'static str { "i am a foo." } /* nest::foo */ diff --git a/src/test/run-make/pretty-print-path-suffix/foo_method.pp b/src/test/run-make/pretty-print-path-suffix/foo_method.pp new file mode 100644 index 0000000000000..acf3f90cb0e1f --- /dev/null +++ b/src/test/run-make/pretty-print-path-suffix/foo_method.pp @@ -0,0 +1,16 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + + + + +fn foo_method(&self) -> &'static str { return "i am very similiar to foo."; } +/* nest::S::foo_method */ diff --git a/src/test/run-make/pretty-print-path-suffix/input.rs b/src/test/run-make/pretty-print-path-suffix/input.rs new file mode 100644 index 0000000000000..4942540126b11 --- /dev/null +++ b/src/test/run-make/pretty-print-path-suffix/input.rs @@ -0,0 +1,28 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_type="lib"] + +pub fn +foo() -> i32 +{ 45 } + +pub fn bar() -> &'static str { "i am not a foo." } + +pub mod nest { + pub fn foo() -> &'static str { "i am a foo." } + + struct S; + impl S { + fn foo_method(&self) -> &'static str { + return "i am very similiar to foo."; + } + } +} diff --git a/src/test/run-make/pretty-print-path-suffix/nest_foo.pp b/src/test/run-make/pretty-print-path-suffix/nest_foo.pp new file mode 100644 index 0000000000000..88eaa062b0320 --- /dev/null +++ b/src/test/run-make/pretty-print-path-suffix/nest_foo.pp @@ -0,0 +1,14 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + + + +pub fn foo() -> &'static str { "i am a foo." } /* nest::foo */ From 7faf33c42e8ba29e1f4321fc225f4e03ac3f0347 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Mon, 4 Aug 2014 13:10:08 -0700 Subject: [PATCH 23/25] librustc: Allow mutation of moved upvars. --- src/librustc/middle/mem_categorization.rs | 57 ++++++++++++++--------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 52a32241faf7c..39a7b4aa3d68e 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -306,6 +306,29 @@ impl MutabilityCategory { } } + fn from_def(def: &def::Def) -> MutabilityCategory { + match *def { + def::DefFn(..) | def::DefStaticMethod(..) | def::DefSelfTy(..) | + def::DefMod(..) | def::DefForeignMod(..) | def::DefVariant(..) | + def::DefTy(..) | def::DefTrait(..) | def::DefPrimTy(..) | + def::DefTyParam(..) | def::DefUse(..) | def::DefStruct(..) | + def::DefTyParamBinder(..) | def::DefRegion(..) | def::DefLabel(..) | + def::DefMethod(..) => fail!("no MutabilityCategory for def: {}", *def), + + def::DefStatic(_, false) => McImmutable, + def::DefStatic(_, true) => McDeclared, + + def::DefArg(_, binding_mode) | + def::DefBinding(_, binding_mode) | + def::DefLocal(_, binding_mode) => match binding_mode { + ast::BindByValue(ast::MutMutable) => McDeclared, + _ => McImmutable + }, + + def::DefUpvar(_, def, _, _) => MutabilityCategory::from_def(&*def) + } + } + pub fn inherit(&self) -> MutabilityCategory { match *self { McImmutable => McImmutable, @@ -503,8 +526,8 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { def::DefStaticMethod(..) => { Ok(self.cat_rvalue_node(id, span, expr_ty)) } - def::DefMod(_) | def::DefForeignMod(_) | def::DefStatic(_, false) | - def::DefUse(_) | def::DefTrait(_) | def::DefTy(_) | def::DefPrimTy(_) | + def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) | + def::DefTrait(_) | def::DefTy(_) | def::DefPrimTy(_) | def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) | def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) => { Ok(Rc::new(cmt_ { @@ -516,30 +539,25 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { })) } - def::DefStatic(_, true) => { + def::DefStatic(_, _) => { Ok(Rc::new(cmt_ { id:id, span:span, cat:cat_static_item, - mutbl: McDeclared, + mutbl: MutabilityCategory::from_def(&def), ty:expr_ty })) } - def::DefArg(vid, binding_mode) => { + def::DefArg(vid, _) => { // Idea: make this could be rewritten to model by-ref // stuff as `&const` and `&mut`? - // m: mutability of the argument - let m = match binding_mode { - ast::BindByValue(ast::MutMutable) => McDeclared, - _ => McImmutable - }; Ok(Rc::new(cmt_ { id: id, span: span, cat: cat_arg(vid), - mutbl: m, + mutbl: MutabilityCategory::from_def(&def), ty:expr_ty })) } @@ -564,7 +582,6 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { if var_is_refd { self.cat_upvar(id, span, var_id, fn_node_id) } else { - // FIXME #2152 allow mutation of moved upvars Ok(Rc::new(cmt_ { id:id, span:span, @@ -573,13 +590,12 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { onceness: closure_ty.onceness, capturing_proc: fn_node_id, }), - mutbl:McImmutable, + mutbl: MutabilityCategory::from_def(&def), ty:expr_ty })) } } ty::ty_unboxed_closure(_) => { - // FIXME #2152 allow mutation of moved upvars Ok(Rc::new(cmt_ { id: id, span: span, @@ -588,7 +604,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { onceness: ast::Many, capturing_proc: fn_node_id, }), - mutbl: McImmutable, + mutbl: MutabilityCategory::from_def(&def), ty: expr_ty })) } @@ -602,19 +618,14 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> { } } - def::DefLocal(vid, binding_mode) | - def::DefBinding(vid, binding_mode) => { + def::DefLocal(vid, _) | + def::DefBinding(vid, _) => { // by-value/by-ref bindings are local variables - let m = match binding_mode { - ast::BindByValue(ast::MutMutable) => McDeclared, - _ => McImmutable - }; - Ok(Rc::new(cmt_ { id: id, span: span, cat: cat_local(vid), - mutbl: m, + mutbl: MutabilityCategory::from_def(&def), ty: expr_ty })) } From 12f176a47e09c2c57086c235aba728d77d35568f Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Mon, 4 Aug 2014 13:26:25 -0700 Subject: [PATCH 24/25] librustc: Update unused mut lint to properly track moved upvars. --- src/librustc/middle/borrowck/check_loans.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 7dec42538cffb..65c7e1a6031ee 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -764,18 +764,17 @@ impl<'a> CheckLoanCtxt<'a> { return; fn mark_variable_as_used_mut(this: &CheckLoanCtxt, - cmt: mc::cmt) { + mut cmt: mc::cmt) { //! If the mutability of the `cmt` being written is inherited //! from a local variable, liveness will //! not have been able to detect that this variable's mutability //! is important, so we must add the variable to the //! `used_mut_nodes` table here. - let mut cmt = cmt; loop { - debug!("mark_writes_through_upvars_as_used_mut(cmt={})", - cmt.repr(this.tcx())); + debug!("mark_variable_as_used_mut(cmt={})", cmt.repr(this.tcx())); match cmt.cat.clone() { + mc::cat_copied_upvar(mc::CopiedUpvar { upvar_id: id, .. }) | mc::cat_local(id) | mc::cat_arg(id) => { this.tcx().used_mut_nodes.borrow_mut().insert(id); return; @@ -792,7 +791,6 @@ impl<'a> CheckLoanCtxt<'a> { mc::cat_rvalue(..) | mc::cat_static_item | - mc::cat_copied_upvar(..) | mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) => { From c018a682d52a02ee5f4370a6b92c8d1849e979d4 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Mon, 4 Aug 2014 13:30:38 -0700 Subject: [PATCH 25/25] Add tests. --- .../cannot-mutate-captured-non-mut-var.rs | 15 +++++++++++++ .../unused-mut-warning-captured-var.rs | 17 ++++++++++++++ src/test/run-pass/issue-11958.rs | 22 +++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs create mode 100644 src/test/compile-fail/unused-mut-warning-captured-var.rs create mode 100644 src/test/run-pass/issue-11958.rs diff --git a/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs new file mode 100644 index 0000000000000..6bc436d3c18ce --- /dev/null +++ b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs @@ -0,0 +1,15 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + let x = 1i; + proc() { x = 2; }; + //~^ ERROR: cannot assign to immutable captured outer variable in a proc `x` +} diff --git a/src/test/compile-fail/unused-mut-warning-captured-var.rs b/src/test/compile-fail/unused-mut-warning-captured-var.rs new file mode 100644 index 0000000000000..a3db84b0ac65f --- /dev/null +++ b/src/test/compile-fail/unused-mut-warning-captured-var.rs @@ -0,0 +1,17 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![forbid(unused_mut)] + +fn main() { + let mut x = 1i; + //~^ ERROR: variable does not need to be mutable + proc() { println!("{}", x); }; +} diff --git a/src/test/run-pass/issue-11958.rs b/src/test/run-pass/issue-11958.rs new file mode 100644 index 0000000000000..f4ed7c5d9c871 --- /dev/null +++ b/src/test/run-pass/issue-11958.rs @@ -0,0 +1,22 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![forbid(warnings)] + +// Pretty printing tests complain about `use std::predule::*` +#![allow(unused_imports)] + +// We shouldn't need to rebind a moved upvar as mut if it's already +// marked as mut + +pub fn main() { + let mut x = 1i; + proc() { x = 2; }; +}