make_dir $h/test/debuginfo-lldb
make_dir $h/test/codegen
make_dir $h/test/doc-tutorial
+ make_dir $h/test/doc-guide
make_dir $h/test/doc-guide-ffi
make_dir $h/test/doc-guide-runtime
make_dir $h/test/doc-guide-macros
make_dir $h/test/doc-guide-pointers
make_dir $h/test/doc-guide-container
make_dir $h/test/doc-guide-tasks
- make_dir $h/test/doc-complement-cheatsheet
make_dir $h/test/doc-rust
done
# L10N_LANGS are the languages for which the docs have been
# translated.
######################################################################
-DOCS := index intro tutorial guide-ffi guide-macros guide-lifetimes \
+DOCS := index intro tutorial guide guide-ffi guide-macros guide-lifetimes \
guide-tasks guide-container guide-pointers guide-testing \
- guide-runtime complement-bugreport complement-cheatsheet \
+ guide-runtime complement-bugreport \
complement-lang-faq complement-design-faq complement-project-faq rust \
rustdoc guide-unsafe
SPACE +=
ifneq ($(wildcard $(subst $(SPACE),\$(SPACE),$(CFG_GIT))),)
ifneq ($(wildcard $(subst $(SPACE),\$(SPACE),$(CFG_GIT_DIR))),)
- CFG_VERSION += $(shell git --git-dir='$(CFG_GIT_DIR)' log -1 \
- --pretty=format:'(%h %ci)')
+ CFG_VER_DATE = $(shell git --git-dir='$(CFG_GIT_DIR)' log -1 --pretty=format:'%ci')
CFG_VER_HASH = $(shell git --git-dir='$(CFG_GIT_DIR)' rev-parse HEAD)
+ CFG_VERSION += ($(CFG_VER_HASH) $(CFG_VER_DATE))
endif
endif
export CFG_SRC_DIR
export CFG_BUILD_DIR
+ifdef CFG_VER_DATE
+export CFG_VER_DATE
+endif
+ifdef CFG_VER_HASH
+export CFG_VER_HASH
+endif
export CFG_VERSION
export CFG_VERSION_WIN
export CFG_RELEASE
+++ /dev/null
-% Rust Cheatsheet
-
-# How do I convert *X* to *Y*?
-
-**Int to string**
-
-Use [`ToStr`](std/to_str/trait.ToStr.html).
-
-~~~
-let x: int = 42;
-let y: String = x.to_str();
-~~~
-
-**String to int**
-
-Use [`FromStr`](std/from_str/trait.FromStr.html), and its helper function,
-[`from_str`](std/from_str/fn.from_str.html).
-
-~~~
-let x: Option<int> = from_str("42");
-let y: int = x.unwrap();
-~~~
-
-**Int to string, in non-base-10**
-
-Use the `format!` syntax extension.
-
-~~~
-let x: int = 42;
-let y: String = format!("{:t}", x); // binary
-let y: String = format!("{:o}", x); // octal
-let y: String = format!("{:x}", x); // lowercase hexadecimal
-let y: String = format!("{:X}", x); // uppercase hexadecimal
-~~~
-
-**String to int, in non-base-10**
-
-Use [`FromStrRadix`](std/num/trait.FromStrRadix.html), and its helper
-function, [`from_str_radix`](std/num/fn.from_str_radix.html).
-
-~~~
-use std::num;
-
-let x: Option<i64> = num::from_str_radix("deadbeef", 16);
-let y: i64 = x.unwrap();
-~~~
-
-**Vector of Bytes to String**
-
-To return a Borrowed String Slice (&str) use the str helper function
-[`from_utf8`](std/str/fn.from_utf8.html).
-
-~~~
-use std::str;
-
-let bytes = &[104u8,105u8];
-let x: &str = str::from_utf8(bytes).unwrap();
-~~~
-
-To return an Owned String use the str helper function
-[`from_utf8_owned`](std/str/fn.from_utf8_owned.html).
-
-~~~
-use std::str;
-
-let x: Option<String> =
- str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_string());
-let y: String = x.unwrap();
-~~~
-
-To return a [`MaybeOwned`](std/str/type.MaybeOwned.html) use the str helper
-function [`from_utf8_lossy`](std/str/fn.from_utf8_owned.html).
-This function also replaces non-valid utf-8 sequences with U+FFFD replacement
-character.
-
-~~~
-use std::str;
-
-let x = b"Hello \xF0\x90\x80World!";
-let y = str::from_utf8_lossy(x);
-~~~
-
-**`Vec<T>`/`String` to `&[T]`/`&str`**
-
-The `.as_slice` method on each type provides a borrowed slice pointing
-to the contents of a `Vec` or `String`. The slice points directly to
-the data already stored in the vector or string, and so is a very
-cheap operation (no allocations or complicated computations required).
-
-~~~
-let vec: Vec<u32> = vec![1, 2, 3];
-let slice: &[u32] = vec.as_slice();
-
-let string: String = "foo bar".to_string();
-let str_slice: &str = string.as_slice();
-~~~
-
-`Vec` also provides the `.as_mut_slice` method for viewing the
-contained data as a `&mut [T]`.
-
-# File operations
-
-## How do I read from a file?
-
-Use
-[`File::open`](std/io/fs/struct.File.html#method.open)
-to create a
-[`File`](std/io/fs/struct.File.html)
-struct, which implements the
-[`Reader`](std/io/trait.Reader.html)
-trait.
-
-~~~ {.ignore}
-use std::path::Path;
-use std::io::fs::File;
-
-let path : Path = Path::new("Doc-FAQ-Cheatsheet.md");
-let on_error = || fail!("open of {:?} failed", path);
-let reader : File = File::open(&path).unwrap_or_else(on_error);
-~~~
-
-## How do I iterate over the lines in a file?
-
-Use the [`lines`](std/io/trait.Buffer.html#method.lines) method on a
-[`BufferedReader`](std/io/struct.BufferedReader.html).
-
-~~~
-use std::io::BufferedReader;
-# use std::io::MemReader;
-
-# let reader = MemReader::new(vec!());
-
-let mut reader = BufferedReader::new(reader);
-for line in reader.lines() {
- print!("line: {}", line);
-}
-~~~
-
-# String operations
-
-## How do I search for a substring?
-
-Use the [`find_str`](std/str/trait.StrSlice.html#tymethod.find_str) method.
-
-~~~
-let str = "Hello, this is some random string";
-let index: Option<uint> = str.find_str("rand");
-~~~
-
-# Containers
-
-## How do I get the length of a vector?
-
-The [`Container`](std/container/trait.Container.html) trait provides the `len` method.
-
-~~~
-let u: Vec<u32> = vec![0, 1, 2];
-let v: &[u32] = &[0, 1, 2, 3];
-let w: [u32, .. 5] = [0, 1, 2, 3, 4];
-
-println!("u: {}, v: {}, w: {}", u.len(), v.len(), w.len()); // 3, 4, 5
-~~~
-
-## How do I iterate over a vector?
-
-Use the [`iter`](std/slice/trait.ImmutableVector.html#tymethod.iter) method.
-
-~~~
-let values: Vec<int> = vec![1, 2, 3, 4, 5];
-for value in values.iter() { // value: &int
- println!("{}", *value);
-}
-~~~
-
-(See also [`mut_iter`](std/slice/trait.MutableVector.html#tymethod.mut_iter)
-which yields `&mut int` and
-[`move_iter`](std/slice/trait.OwnedVector.html#tymethod.move_iter) which yields
-`int` while consuming the `values` vector.)
-
-# Type system
-
-## How do I store a function in a struct?
-
-~~~
-struct Foo {
- myfunc: fn(int, uint) -> i32
-}
-
-struct FooClosure<'a> {
- myfunc: |int, uint|: 'a -> i32
-}
-
-fn a(a: int, b: uint) -> i32 {
- (a as uint + b) as i32
-}
-
-fn main() {
- let f = Foo { myfunc: a };
- let g = FooClosure { myfunc: |a, b| { (a - b as int) as i32 } };
- println!("{}", (f.myfunc)(1, 2));
- println!("{}", (g.myfunc)(3, 4));
-}
-~~~
-
-Note that the parenthesis surrounding `f.myfunc` are necessary: they are how Rust disambiguates field lookup and method call. The `'a` on `FooClosure` is the lifetime of the closure's environment pointer.
-
-## How do I express phantom types?
-
-[Phantom types](http://www.haskell.org/haskellwiki/Phantom_type) are those that cannot be constructed at compile time. To express these in Rust, zero-variant `enum`s can be used:
-
-~~~
-enum Open {}
-enum Closed {}
-~~~
-
-Phantom types are useful for enforcing state at compile time. For example:
-
-~~~
-struct Door<State>(String);
-
-struct Open;
-struct Closed;
-
-fn close(Door(name): Door<Open>) -> Door<Closed> {
- Door::<Closed>(name)
-}
-
-fn open(Door(name): Door<Closed>) -> Door<Open> {
- Door::<Open>(name)
-}
-
-let _ = close(Door::<Open>("front".to_string()));
-~~~
-
-Attempting to close a closed door is prevented statically:
-
-~~~ {.ignore}
-let _ = close(Door::<Closed>("front".to_string())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
-~~~
-
-# FFI (Foreign Function Interface)
-
-## C function signature conversions
-
-| Description | C signature | Equivalent Rust signature |
-|---------------------|-----------------------------------------------|------------------------------------------------|
-| no parameters | `void foo(void);` | `fn foo();` |
-| return value | `int foo(void);` | `fn foo() -> c_int;` |
-| function parameters | `void foo(int x, int y);` | `fn foo(x: c_int, y: c_int);` |
-| in-out pointers | `void foo(const int* in_ptr, int* out_ptr);` | `fn foo(in_ptr: *c_int, out_ptr: *mut c_int);` |
-
-Note: The Rust signatures should be wrapped in an `extern "ABI" { ... }` block.
-
-### Representing opaque handles
-
-You might see things like this in C APIs:
-
-~~~c
-typedef struct Window Window;
-Window* createWindow(int width, int height);
-~~~
-
-You can use a zero-element `enum` ([phantom type](#how-do-i-express-phantom-types)) to represent the opaque object handle. The FFI would look like this:
-
-~~~ {.ignore}
-enum Window {}
-extern "C" {
- fn createWindow(width: c_int, height: c_int) -> *Window;
-}
-~~~
-
-Using a phantom type ensures that the handles cannot be (safely) constructed in client code.
-
-# Contributing to this page
-
-For small examples, have full type annotations, as much as is reasonable, to keep it clear what, exactly, everything is doing. Try to link to the API docs, as well.
-
-Similar documents for other programming languages:
-
- * [http://pleac.sourceforge.net/](http://pleac.sourceforge.net)
modification of the container through another handle.
~~~
-let mut xs = [1, 2, 3];
+let mut xs = [1i, 2, 3];
{
let _it = xs.iter();
into a single value:
~~~
-let xs = [1, 9, 2, 3, 14, 12];
+let xs = [1i, 9, 2, 3, 14, 12];
let result = xs.iter().fold(0, |accumulator, item| accumulator - *item);
assert_eq!(result, -41);
~~~
Most adaptors return an adaptor object implementing the `Iterator` trait itself:
~~~
-let xs = [1, 9, 2, 3, 14, 12];
-let ys = [5, 2, 1, 8];
+let xs = [1i, 9, 2, 3, 14, 12];
+let ys = [5i, 2, 1, 8];
let sum = xs.iter().chain(ys.iter()).fold(0, |a, b| a + *b);
assert_eq!(sum, 57);
~~~
never call its underlying iterator again once `None` has been returned:
~~~
-let xs = [1,2,3,4,5];
-let mut calls = 0;
+let xs = [1i,2,3,4,5];
+let mut calls = 0i;
{
let it = xs.iter().scan((), |_, x| {
The function `range` (or `range_inclusive`) allows to simply iterate through a given range:
~~~
-for i in range(0, 5) {
+for i in range(0i, 5) {
print!("{} ", i) // prints "0 1 2 3 4"
}
-for i in std::iter::range_inclusive(0, 5) { // needs explicit import
+for i in std::iter::range_inclusive(0i, 5) { // needs explicit import
print!("{} ", i) // prints "0 1 2 3 4 5"
}
~~~
also advance the state of an iterator in a mutable location:
~~~
-let xs = [1, 2, 3, 4, 5];
+let xs = [1i, 2, 3, 4, 5];
let ys = ["foo", "bar", "baz", "foobar"];
// create an iterator yielding tuples of elements from both vectors
Iterators offer generic conversion to containers with the `collect` adaptor:
~~~
-let xs = [0, 1, 1, 2, 3, 5, 8];
+let xs = [0i, 1, 1, 2, 3, 5, 8];
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<Vec<int>>();
assert_eq!(ys, vec![10, 6, 4, 2, 2, 0]);
~~~
returning another `DoubleEndedIterator` with `next` and `next_back` exchanged.
~~~
-let xs = [1, 2, 3, 4, 5, 6];
+let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter();
println!("{}", it.next()); // prints `Some(1)`
println!("{}", it.next()); // prints `Some(2)`
`DoubleEndedIterator` implementations if the underlying iterators are.
~~~
-let xs = [1, 2, 3, 4];
-let ys = [5, 6, 7, 8];
+let xs = [1i, 2, 3, 4];
+let ys = [5i, 6, 7, 8];
let mut it = xs.iter().chain(ys.iter()).map(|&x| x * 2);
println!("{}", it.next()); // prints `Some(2)`
the trailing underscore is a workaround for issue #5898 and will be removed.
~~~
-let mut ys = [1, 2, 3, 4, 5];
+let mut ys = [1i, 2, 3, 4, 5];
ys.mut_iter().reverse_();
-assert!(ys == [5, 4, 3, 2, 1]);
+assert!(ys == [5i, 4, 3, 2, 1]);
~~~
## Random-access iterators
underlying iterators are.
~~~
-let xs = [1, 2, 3, 4, 5];
-let ys = [7, 9, 11];
+let xs = [1i, 2, 3, 4, 5];
+let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter());
println!("{}", it.idx(0)); // prints `Some(1)`
println!("{}", it.idx(5)); // prints `Some(7)`
Named lifetime notation can also be used to control the flow of execution:
~~~
-'h: for i in range(0,10) {
+'h: for i in range(0u, 10) {
'g: loop {
if i % 2 == 0 { continue 'h; }
if i == 9 { break 'h; }
~~~rust
fn main() {
- let mut x = box 5;
+ let mut x = box 5i;
if *x < 10 {
let y = &x;
println!("Oh no: {}", y);
~~~rust{.ignore}
fn main() {
- let mut x = box 5;
+ let mut x = box 5i;
if *x < 10 {
let y = &x;
*x -= 1;
#[bench]
fn bench_xor_1000_ints(b: &mut Bencher) {
b.iter(|| {
- range(0, 1000).fold(0, |old, new| old ^ new);
+ range(0u, 1000).fold(0, |old, new| old ^ new);
});
}
~~~
# struct X; impl X { fn iter<T>(&self, _: || -> T) {} } let b = X;
b.iter(|| {
// note lack of `;` (could also use an explicit `return`).
- range(0, 1000).fold(0, |old, new| old ^ new)
+ range(0u, 1000).fold(0, |old, new| old ^ new)
});
~~~
# fn main() {
# struct X; impl X { fn iter<T>(&self, _: || -> T) {} } let b = X;
b.iter(|| {
- test::black_box(range(0, 1000).fold(0, |old, new| old ^ new));
+ test::black_box(range(0u, 1000).fold(0, |old, new| old ^ new));
});
# }
~~~
--- /dev/null
+% The Rust Guide
+
+<div style="border: 2px solid red; padding:5px;">
+This guide is a work in progress. Until it is ready, we highly recommend that
+you read the <a href="tutorial.html">Tutorial</a> instead. This work-in-progress Guide is being
+displayed here in line with Rust's open development policy. Please open any
+issues you find as usual.
+</div>
+
+Coming soon. :)
* [Language Design FAQ](complement-design-faq.html)
* [Language FAQ](complement-lang-faq.html)
* [Project FAQ](complement-project-faq.html)
-* [Code cheatsheet](complement-cheatsheet.html) - "How do I do X?"
* [How to submit a bug report](complement-bugreport.html)
# Libraries
```
fn main() {
- let numbers = vec![1,2,3];
+ let numbers = vec![1i, 2i, 3i];
let (tx, rx) = channel();
tx.send(numbers);
```ignore
fn main() {
- let numbers = vec![1,2,3];
+ let numbers = vec![1i, 2i, 3i];
let (tx, rx) = channel();
tx.send(numbers);
```
fn main() {
- let numbers = vec![1,2,3];
+ let numbers = vec![1i, 2i, 3i];
- for num in range(0, 3) {
+ for num in range(0u, 3) {
let (tx, rx) = channel();
// Use `clone` to send a *copy* of the array
tx.send(numbers.clone());
use std::sync::Arc;
fn main() {
- let numbers = vec![1,2,3];
+ let numbers = vec![1i, 2i, 3i];
let numbers = Arc::new(numbers);
- for num in range(0, 3) {
+ for num in range(0u, 3) {
let (tx, rx) = channel();
tx.send(numbers.clone());
use std::sync::{Arc, Mutex};
fn main() {
- let numbers = vec![1,2,3];
+ let numbers = vec![1i, 2i, 3i];
let numbers_lock = Arc::new(Mutex::new(numbers));
- for num in range(0, 3) {
+ for num in range(0u, 3) {
let (tx, rx) = channel();
tx.send(numbers_lock.clone());
# fn foo<T>(_: T){}
fn main() {
- // Equivalent to 'std::iter::range_step(0, 10, 2);'
- range_step(0, 10, 2);
+ // Equivalent to 'std::iter::range_step(0u, 10u, 2u);'
+ range_step(0u, 10u, 2u);
- // Equivalent to 'foo(vec![std::option::Some(1.0), std::option::None]);'
- foo(vec![Some(1.0), None]);
+ // Equivalent to 'foo(vec![std::option::Some(1.0f64),
+ // std::option::None]);'
+ foo(vec![Some(1.0f64), None]);
}
~~~~
~~~~
# trait Shape { }
# impl Shape for int { }
-# let mycircle = 0;
+# let mycircle = 0i;
let myshape: Box<Shape> = box mycircle as Box<Shape>;
~~~~
An example of creating and calling a closure:
```rust
-let captured_var = 10;
+let captured_var = 10i;
let closure_no_args = || println!("captured_var={}", captured_var);
}
fn main() {
- print(box 10 as Box<Printable>);
+ print(box 10i as Box<Printable>);
}
~~~~
% The Rust Language Tutorial
+<div style="border: 2px solid red; padding:5px;">
+The tutorial is undergoing a complete re-write as <a href="guide.html">the Guide</a>.
+Until it's ready, this tutorial is the right place to come to start learning
+Rust. Please submit improvements as pull requests, but understand that
+eventually it will be going away.
+</div>
+
# Introduction
Rust is a programming language with a focus on type safety, memory
~~~~
let hi = "hi";
-let mut count = 0;
+let mut count = 0i;
while count < 10 {
println!("count is {}", count);
~~~
// `{}` will print the "default format" of a type
-println!("{} is {}", "the answer", 43);
+println!("{} is {}", "the answer", 43i);
~~~
~~~~
example:
~~~~
-# let age = 23;
+# let age = 23i;
match age {
a @ 0..20 => println!("{} years old", a),
_ => println!("older than 21")
There is also a for-loop that can be used to iterate over a range of numbers:
~~~~
-for n in range(0, 5) {
+for n in range(0u, 5) {
println!("{}", n);
}
~~~~
Avoiding a move can be done with the library-defined `clone` method:
~~~~
-let x = box 5;
+let x = box 5i;
let y = x.clone(); // `y` is a newly allocated box
let z = x; // no new memory allocated, `x` can no longer be used
~~~~
}
}
-let xs = Cons(5, box Cons(10, box Nil));
-let ys = Cons(5, box Cons(10, box Nil));
+let xs = Cons(5i, box Cons(10i, box Nil));
+let ys = Cons(5i, box Cons(10i, box Nil));
// The methods below are part of the PartialEq trait,
// which we implemented on our linked list.
assert!(xs.eq(&ys));
## Freezing
-Lending an &-pointer to an object freezes it and prevents mutation—even if the object was declared as `mut`.
-`Freeze` objects have freezing enforced statically at compile-time. An example
-of a non-`Freeze` type is [`RefCell<T>`][refcell].
+Lending an &-pointer to an object freezes the pointed-to object and prevents
+mutation—even if the object was declared as `mut`. `Freeze` objects have
+freezing enforced statically at compile-time. An example of a non-`Freeze` type
+is [`RefCell<T>`][refcell].
~~~~
let mut x = 5;
~~~
// A fixed-size vector
-let numbers = [1, 2, 3];
+let numbers = [1i, 2, 3];
let more_numbers = numbers;
// The type of a fixed-size vector is written as `[Type, ..length]`
use std::string::String;
// A dynamically sized vector (unique vector)
-let mut numbers = vec![1, 2, 3];
+let mut numbers = vec![1i, 2, 3];
numbers.push(4);
numbers.push(5);
use std::rc::Rc;
// A fixed-size array allocated in a reference-counted box
-let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+let x = Rc::new([1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let y = x.clone(); // a new owner
let z = x; // this moves `x` into `z`, rather than creating a new owner
-assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// the variable is mutable, but not the contents of the box
let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
use std::gc::GC;
// A fixed-size array allocated in a garbage-collected box
-let x = box(GC) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let y = x; // does not perform a move, unlike with `Rc`
let z = x;
-assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
~~~
With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
fn main() {
// The rational number '1/2':
- let one_half = ::num::rational::Ratio::new(1, 2);
+ let one_half = ::num::rational::Ratio::new(1i, 2);
}
~~~
fn main() {
farm::dog();
- let a_third = Ratio::new(1, 3);
+ let a_third = Ratio::new(1i, 3);
}
~~~
fn main() {
// `range` is imported by default
- for _ in range(0, 10) {}
+ for _ in range(0u, 10) {}
// Doesn't hinder you from importing it under a different name yourself
- for _ in iter_range(0, 10) {}
+ for _ in iter_range(0u, 10) {}
// Or from not using the automatic import.
- for _ in ::std::iter::range(0, 10) {}
+ for _ in ::std::iter::range(0u, 10) {}
}
~~~
* [Testing Rust code][testing]
* [The Rust Runtime][runtime]
-There is further documentation on the [wiki], however those tend to be even more out of date as this document.
+There is further documentation on the [wiki], however those tend to be even more out of date than this document.
[pointers]: guide-pointers.html
[lifetimes]: guide-lifetimes.html
/// let numbers = Vec::from_fn(100, |i| i as f32);
/// let shared_numbers = Arc::new(numbers);
///
-/// for _ in range(0, 10) {
+/// for _ in range(0u, 10) {
/// let child_numbers = shared_numbers.clone();
///
/// spawn(proc() {
}
}
+#[unstable]
impl<T: Share + Send> Clone for Arc<T> {
/// Duplicate an atomically reference counted wrapper.
///
}
}
+#[unstable]
impl<T: Share + Send> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
fn default() -> Box<T> { box Default::default() }
}
+#[unstable]
impl<T: Clone> Clone for Box<T> {
/// Return a copy of the owned box.
#[inline]
}
}
+#[unstable]
impl<T> Clone for Rc<T> {
#[inline]
fn clone(&self) -> Rc<T> {
}
}
+#[unstable]
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
#[test]
fn test_clone() {
- let x = Rc::new(RefCell::new(5));
+ let x = Rc::new(RefCell::new(5i));
let y = x.clone();
*x.borrow_mut() = 20;
assert_eq!(*y.borrow(), 20);
#[test]
fn test_simple() {
- let x = Rc::new(5);
+ let x = Rc::new(5i);
assert_eq!(*x, 5);
}
#[test]
fn test_simple_clone() {
- let x = Rc::new(5);
+ let x = Rc::new(5i);
let y = x.clone();
assert_eq!(*x, 5);
assert_eq!(*y, 5);
#[test]
fn test_destructor() {
- let x = Rc::new(box 5);
+ let x = Rc::new(box 5i);
assert_eq!(**x, 5);
}
#[test]
fn test_live() {
- let x = Rc::new(5);
+ let x = Rc::new(5i);
let y = x.downgrade();
assert!(y.upgrade().is_some());
}
#[test]
fn test_dead() {
- let x = Rc::new(5);
+ let x = Rc::new(5i);
let y = x.downgrade();
drop(x);
assert!(y.upgrade().is_none());
fn gc_inside() {
// see issue #11532
use std::gc::GC;
- let a = Rc::new(RefCell::new(box(GC) 1));
+ let a = Rc::new(RefCell::new(box(GC) 1i));
assert!(a.try_borrow_mut().is_some());
}
#[test]
pub fn test_copy() {
let arena = TypedArena::new();
- for _ in range(0, 100000) {
+ for _ in range(0u, 100000) {
arena.alloc(Point {
x: 1,
y: 2,
#[test]
pub fn test_noncopy() {
let arena = TypedArena::new();
- for _ in range(0, 100000) {
+ for _ in range(0u, 100000) {
arena.alloc(Noncopy {
string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
impl fmt::Show for Bitv {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self.iter() {
- try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
+ try!(write!(fmt, "{}", if bit { 1u } else { 0u }));
}
Ok(())
}
//Tests the functionality of the insert methods (which are unfinished).
#[test]
fn insert_test_one() {
- let b = BTree::new(1, "abc".to_string(), 2);
- let is_insert = b.insert(2, "xyz".to_string());
+ let b = BTree::new(1i, "abc".to_string(), 2);
+ let is_insert = b.insert(2i, "xyz".to_string());
//println!("{}", is_insert.clone().to_str());
assert!(is_insert.root.is_leaf());
}
#[test]
fn insert_test_two() {
- let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
- let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
- let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
+ let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3));
let b = BTree::new_with_node_len(n, 3, 2);
//println!("{}", b.clone().insert(4, "ddd".to_string()).to_str());
#[test]
fn insert_test_three() {
- let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
- let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
- let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
- let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
+ let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(4i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
//println!("{}", b.clone().insert(5, "eee".to_string()).to_str());
#[test]
fn insert_test_four() {
- let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
- let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
- let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
- let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
+ let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(4i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let mut b = BTree::new_with_node_len(n, 3, 2);
b = b.clone().insert(5, "eee".to_string());
#[test]
fn bsearch_test_one() {
- let b = BTree::new(1, "abc".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2u);
assert_eq!(Some(1), b.root.bsearch_node(2));
}
#[test]
fn bsearch_test_two() {
- let b = BTree::new(1, "abc".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2u);
assert_eq!(Some(0), b.root.bsearch_node(0));
}
#[test]
fn bsearch_test_three() {
- let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
- let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
- let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
- let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
+ let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(4i, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(5i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(2), b.root.bsearch_node(3));
#[test]
fn bsearch_test_four() {
- let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
- let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
- let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
- let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
+ let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
+ let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
+ let leaf_elt_3 = LeafElt::new(4i, "ccc".to_string());
+ let leaf_elt_4 = LeafElt::new(5i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(4), b.root.bsearch_node(800));
//Tests the functionality of the get method.
#[test]
fn get_test() {
- let b = BTree::new(1, "abc".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
let val = b.get(1);
assert_eq!(val, Some("abc".to_string()));
}
//Tests the BTree's clone() method.
#[test]
fn btree_clone_test() {
- let b = BTree::new(1, "abc".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
let b2 = b.clone();
assert!(b.root == b2.root)
}
//Tests the BTree's cmp() method when one node is "less than" another.
#[test]
fn btree_cmp_test_less() {
- let b = BTree::new(1, "abc".to_string(), 2);
- let b2 = BTree::new(2, "bcd".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
+ let b2 = BTree::new(2i, "bcd".to_string(), 2);
assert!(&b.cmp(&b2) == &Less)
}
//Tests the BTree's cmp() method when two nodes are equal.
#[test]
fn btree_cmp_test_eq() {
- let b = BTree::new(1, "abc".to_string(), 2);
- let b2 = BTree::new(1, "bcd".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
+ let b2 = BTree::new(1i, "bcd".to_string(), 2);
assert!(&b.cmp(&b2) == &Equal)
}
//Tests the BTree's cmp() method when one node is "greater than" another.
#[test]
fn btree_cmp_test_greater() {
- let b = BTree::new(1, "abc".to_string(), 2);
- let b2 = BTree::new(2, "bcd".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
+ let b2 = BTree::new(2i, "bcd".to_string(), 2);
assert!(&b2.cmp(&b) == &Greater)
}
//Tests the BTree's to_str() method.
#[test]
fn btree_tostr_test() {
- let b = BTree::new(1, "abc".to_string(), 2);
+ let b = BTree::new(1i, "abc".to_string(), 2);
assert_eq!(b.to_str(), "Key: 1, value: abc;".to_string())
}
assert_eq!(m.pop_front(), Some(box 1));
let mut n = DList::new();
- n.push_front(2);
+ n.push_front(2i);
n.push_front(3);
{
assert_eq!(n.front().unwrap(), &3);
#[cfg(test)]
fn generate_test() -> DList<int> {
- list_from(&[0,1,2,3,4,5,6])
+ list_from(&[0i,1,2,3,4,5,6])
}
#[cfg(test)]
{
let mut m = DList::new();
let mut n = DList::new();
- n.push_back(2);
+ n.push_back(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
{
let mut m = DList::new();
let n = DList::new();
- m.push_back(2);
+ m.push_back(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
check_links(&m);
}
- let v = vec![1,2,3,4,5];
- let u = vec![9,8,1,2,3,4,5];
+ let v = vec![1i,2,3,4,5];
+ let u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.append(list_from(u.as_slice()));
check_links(&m);
{
let mut m = DList::new();
let mut n = DList::new();
- n.push_back(2);
+ n.push_back(2i);
m.prepend(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
check_links(&m);
}
- let v = vec![1,2,3,4,5];
- let u = vec![9,8,1,2,3,4,5];
+ let v = vec![1i,2,3,4,5];
+ let u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.prepend(list_from(u.as_slice()));
check_links(&m);
n.rotate_forward(); check_links(&n);
assert_eq!(n.len(), 0);
- let v = vec![1,2,3,4,5];
+ let v = vec![1i,2,3,4,5];
let mut m = list_from(v.as_slice());
m.rotate_backward(); check_links(&m);
m.rotate_forward(); check_links(&m);
m.rotate_backward(); check_links(&m);
m.push_front(9); check_links(&m);
m.rotate_forward(); check_links(&m);
- assert_eq!(vec![3,9,5,1,2], m.move_iter().collect());
+ assert_eq!(vec![3i,9,5,1,2], m.move_iter().collect());
}
#[test]
}
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
- n.push_front(4);
+ n.push_front(4i);
let mut it = n.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
#[test]
fn test_iterator_clone() {
let mut n = DList::new();
- n.push_back(2);
+ n.push_back(2i);
n.push_back(3);
n.push_back(4);
let mut it = n.iter();
fn test_iterator_double_end() {
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
- n.push_front(4);
+ n.push_front(4i);
n.push_front(5);
n.push_front(6);
let mut it = n.iter();
}
let mut n = DList::new();
assert_eq!(n.iter().rev().next(), None);
- n.push_front(4);
+ n.push_front(4i);
let mut it = n.iter().rev();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
assert_eq!(len, 0);
let mut n = DList::new();
assert!(n.mut_iter().next().is_none());
- n.push_front(4);
+ n.push_front(4i);
n.push_back(5);
let mut it = n.mut_iter();
assert_eq!(it.size_hint(), (2, Some(2)));
fn test_iterator_mut_double_end() {
let mut n = DList::new();
assert!(n.mut_iter().next_back().is_none());
- n.push_front(4);
+ n.push_front(4i);
n.push_front(5);
n.push_front(6);
let mut it = n.mut_iter();
#[test]
fn test_insert_prev() {
- let mut m = list_from(&[0,2,4,6,8]);
+ let mut m = list_from(&[0i,2,4,6,8]);
let len = m.len();
{
let mut it = m.mut_iter();
#[test]
fn test_merge() {
- let mut m = list_from([0, 1, 3, 5, 6, 7, 2]);
- let n = list_from([-1, 0, 0, 7, 7, 9]);
+ let mut m = list_from([0i, 1, 3, 5, 6, 7, 2]);
+ let n = list_from([-1i, 0, 0, 7, 7, 9]);
let len = m.len() + n.len();
m.merge(n, |a, b| a <= b);
assert_eq!(m.len(), len);
#[test]
fn test_insert_ordered() {
let mut n = DList::new();
- n.insert_ordered(1);
+ n.insert_ordered(1i);
assert_eq!(n.len(), 1);
assert_eq!(n.pop_front(), Some(1));
let mut m = DList::new();
- m.push_back(2);
+ m.push_back(2i);
m.push_back(4);
m.insert_ordered(3);
check_links(&m);
}
let mut n = DList::new();
assert!(n.mut_iter().rev().next().is_none());
- n.push_front(4);
+ n.push_front(4i);
let mut it = n.mut_iter().rev();
assert!(it.next().is_some());
assert!(it.next().is_none());
#[test]
fn test_send() {
- let n = list_from([1,2,3]);
+ let n = list_from([1i,2,3]);
spawn(proc() {
check_links(&n);
assert_eq!(&[&1,&2,&3], n.iter().collect::<Vec<&int>>().as_slice());
m.push_back(1);
assert!(n == m);
- let n = list_from([2,3,4]);
- let m = list_from([1,2,3]);
+ let n = list_from([2i,3,4]);
+ let m = list_from([1i,2,3]);
assert!(n != m);
}
#[test]
fn test_ord() {
let n: DList<int> = list_from([]);
- let m = list_from([1,2,3]);
+ let m = list_from([1i,2,3]);
assert!(n < m);
assert!(m > n);
assert!(n <= n);
#[test]
fn test_ord_nan() {
- let nan = 0.0/0.0;
+ let nan = 0.0f64/0.0;
let n = list_from([nan]);
let m = list_from([nan]);
assert!(!(n < m));
assert!(!(n >= m));
let n = list_from([nan]);
- let one = list_from([1.0]);
+ let one = list_from([1.0f64]);
assert!(!(n < one));
assert!(!(n > one));
assert!(!(n <= one));
assert!(!(n >= one));
- let u = list_from([1.0,2.0,nan]);
- let v = list_from([1.0,2.0,3.0]);
+ let u = list_from([1.0f64,2.0,nan]);
+ let v = list_from([1.0f64,2.0,3.0]);
assert!(!(u < v));
assert!(!(u > v));
assert!(!(u <= v));
assert!(!(u >= v));
- let s = list_from([1.0,2.0,4.0,2.0]);
- let t = list_from([1.0,2.0,3.0,2.0]);
+ let s = list_from([1.0f64,2.0,4.0,2.0]);
+ let t = list_from([1.0f64,2.0,3.0,2.0]);
assert!(!(s < t));
assert!(s > one);
assert!(!(s <= one));
#[test]
fn test_fuzz() {
- for _ in range(0, 25) {
+ for _ in range(0u, 25) {
fuzz_test(3);
fuzz_test(16);
fuzz_test(189);
#[test]
fn test_show() {
- let list: DList<int> = range(0, 10).collect();
+ let list: DList<int> = range(0i, 10).collect();
assert!(list.to_str().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
#[bench]
fn bench_collect_into(b: &mut test::Bencher) {
- let v = &[0, ..64];
+ let v = &[0i, ..64];
b.iter(|| {
let _: DList<int> = v.iter().map(|x| *x).collect();
})
#[bench]
fn bench_rotate_forward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
- m.push_front(0);
+ m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_forward();
#[bench]
fn bench_rotate_backward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
- m.push_front(0);
+ m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_backward();
#[bench]
fn bench_iter(b: &mut test::Bencher) {
- let v = &[0, ..128];
+ let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().count() == 128);
}
#[bench]
fn bench_iter_mut(b: &mut test::Bencher) {
- let v = &[0, ..128];
+ let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.mut_iter().count() == 128);
}
#[bench]
fn bench_iter_rev(b: &mut test::Bencher) {
- let v = &[0, ..128];
+ let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().rev().count() == 128);
}
#[bench]
fn bench_iter_mut_rev(b: &mut test::Bencher) {
- let v = &[0, ..128];
+ let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.mut_iter().rev().count() == 128);
#[test]
fn test_iterator() {
- let data = vec!(5, 9, 3);
- let iterout = [9, 5, 3];
+ let data = vec!(5i, 9, 3);
+ let iterout = [9i, 5, 3];
let pq = PriorityQueue::from_vec(data);
let mut i = 0;
for el in pq.iter() {
#[test]
fn test_push() {
- let mut heap = PriorityQueue::from_vec(vec!(2, 4, 9));
+ let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
assert_eq!(heap.len(), 3);
assert!(*heap.top().unwrap() == 9);
heap.push(11);
#[test]
fn test_push_unique() {
- let mut heap = PriorityQueue::from_vec(vec!(box 2, box 4, box 9));
+ let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
assert_eq!(heap.len(), 3);
assert!(*heap.top().unwrap() == box 9);
heap.push(box 11);
#[test]
fn test_push_pop() {
- let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
+ let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.push_pop(6), 6);
assert_eq!(heap.len(), 5);
#[test]
fn test_replace() {
- let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
+ let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.replace(6).unwrap(), 5);
assert_eq!(heap.len(), 5);
#[test]
fn test_to_vec() {
check_to_vec(vec!());
- check_to_vec(vec!(5));
- check_to_vec(vec!(3, 2));
- check_to_vec(vec!(2, 3));
- check_to_vec(vec!(5, 1, 2));
- check_to_vec(vec!(1, 100, 2, 3));
- check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
- check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
- check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
- check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
- check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
- check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
- check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
+ check_to_vec(vec!(5i));
+ check_to_vec(vec!(3i, 2));
+ check_to_vec(vec!(2i, 3));
+ check_to_vec(vec!(5i, 1, 2));
+ check_to_vec(vec!(1i, 100, 2, 3));
+ check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
+ check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
+ check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
+ check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
+ check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
+ check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
+ check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
}
#[test]
fn test_simple() {
let mut d = RingBuf::new();
assert_eq!(d.len(), 0u);
- d.push_front(17);
- d.push_front(42);
+ d.push_front(17i);
+ d.push_front(42i);
d.push_back(137);
assert_eq!(d.len(), 3u);
d.push_back(137);
fn bench_grow(b: &mut test::Bencher) {
let mut deq = RingBuf::new();
b.iter(|| {
- for _ in range(0, 65) {
+ for _ in range(0i, 65) {
deq.push_front(1);
}
})
#[test]
fn test_swap() {
- let mut d: RingBuf<int> = range(0, 5).collect();
+ let mut d: RingBuf<int> = range(0i, 5).collect();
d.pop_front();
d.swap(0, 3);
assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
assert_eq!(d.iter().next(), None);
assert_eq!(d.iter().size_hint(), (0, Some(0)));
- for i in range(0, 5) {
+ for i in range(0i, 5) {
d.push_back(i);
}
assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&0,&1,&2,&3,&4]);
- for i in range(6, 9) {
+ for i in range(6i, 9) {
d.push_front(i);
}
assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&8,&7,&6,&0,&1,&2,&3,&4]);
let mut d = RingBuf::new();
assert_eq!(d.iter().rev().next(), None);
- for i in range(0, 5) {
+ for i in range(0i, 5) {
d.push_back(i);
}
assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0]);
- for i in range(6, 9) {
+ for i in range(6i, 9) {
d.push_front(i);
}
assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0,&6,&7,&8]);
let mut d = RingBuf::with_capacity(3);
assert!(d.mut_iter().rev().next().is_none());
- d.push_back(1);
+ d.push_back(1i);
d.push_back(2);
d.push_back(3);
assert_eq!(d.pop_front(), Some(1));
#[test]
fn test_from_iter() {
use std::iter;
- let v = vec!(1,2,3,4,5,6,7);
+ let v = vec!(1i,2,3,4,5,6,7);
let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
let u: Vec<int> = deq.iter().map(|&x| x).collect();
assert_eq!(u, v);
#[test]
fn test_clone() {
let mut d = RingBuf::new();
- d.push_front(17);
+ d.push_front(17i);
d.push_front(42);
d.push_back(137);
d.push_back(137);
fn test_eq() {
let mut d = RingBuf::new();
assert!(d == RingBuf::with_capacity(0));
- d.push_front(137);
+ d.push_front(137i);
d.push_front(17);
d.push_front(42);
d.push_back(137);
#[test]
fn test_show() {
- let ringbuf: RingBuf<int> = range(0, 10).collect();
+ let ringbuf: RingBuf<int> = range(0i, 10).collect();
assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
type of the vector is `int`, the element type of the iterator is `&int`.
```rust
-let numbers = [0, 1, 2];
+let numbers = [0i, 1i, 2i];
for &x in numbers.iter() {
println!("{} is a number!", x);
}
/// # Example
///
/// ```rust
- /// let mut v = [-5, 4, 1, -3, 2];
+ /// let mut v = [-5i, 4, 1, -3, 2];
///
/// v.sort();
- /// assert!(v == [-5, -3, 1, 2, 4]);
+ /// assert!(v == [-5i, -3, 1, 2, 4]);
/// ```
fn sort(self);
/// # Example
///
/// ```rust
- /// let v = &mut [0, 1, 2];
+ /// let v = &mut [0i, 1, 2];
/// v.next_permutation();
- /// assert_eq!(v, &mut [0, 2, 1]);
+ /// assert_eq!(v, &mut [0i, 2, 1]);
/// v.next_permutation();
- /// assert_eq!(v, &mut [1, 0, 2]);
+ /// assert_eq!(v, &mut [1i, 0, 2]);
/// ```
fn next_permutation(self) -> bool;
/// # Example
///
/// ```rust
- /// let v = &mut [1, 0, 2];
+ /// let v = &mut [1i, 0, 2];
/// v.prev_permutation();
- /// assert_eq!(v, &mut [0, 2, 1]);
+ /// assert_eq!(v, &mut [0i, 2, 1]);
/// v.prev_permutation();
- /// assert_eq!(v, &mut [0, 1, 2]);
+ /// assert_eq!(v, &mut [0i, 1, 2]);
/// ```
fn prev_permutation(self) -> bool;
}
#[test]
fn test_get() {
- let mut a = vec![11];
+ let mut a = vec![11i];
assert_eq!(a.as_slice().get(1), None);
- a = vec![11, 12];
+ a = vec![11i, 12];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
- a = vec![11, 12, 13];
+ a = vec![11i, 12, 13];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
}
fn test_head() {
let mut a = vec![];
assert_eq!(a.as_slice().head(), None);
- a = vec![11];
+ a = vec![11i];
assert_eq!(a.as_slice().head().unwrap(), &11);
- a = vec![11, 12];
+ a = vec![11i, 12];
assert_eq!(a.as_slice().head().unwrap(), &11);
}
#[test]
fn test_tail() {
- let mut a = vec![11];
+ let mut a = vec![11i];
assert_eq!(a.tail(), &[]);
- a = vec![11, 12];
+ a = vec![11i, 12];
assert_eq!(a.tail(), &[12]);
}
#[test]
fn test_tailn() {
- let mut a = vec![11, 12, 13];
+ let mut a = vec![11i, 12, 13];
assert_eq!(a.tailn(0), &[11, 12, 13]);
- a = vec![11, 12, 13];
+ a = vec![11i, 12, 13];
assert_eq!(a.tailn(2), &[13]);
}
#[test]
fn test_init() {
- let mut a = vec![11];
+ let mut a = vec![11i];
assert_eq!(a.init(), &[]);
- a = vec![11, 12];
+ a = vec![11i, 12];
assert_eq!(a.init(), &[11]);
}
#[test]
fn test_initn() {
- let mut a = vec![11, 12, 13];
+ let mut a = vec![11i, 12, 13];
assert_eq!(a.as_slice().initn(0), &[11, 12, 13]);
- a = vec![11, 12, 13];
+ a = vec![11i, 12, 13];
assert_eq!(a.as_slice().initn(2), &[11]);
}
fn test_last() {
let mut a = vec![];
assert_eq!(a.as_slice().last(), None);
- a = vec![11];
+ a = vec![11i];
assert_eq!(a.as_slice().last().unwrap(), &11);
- a = vec![11, 12];
+ a = vec![11i, 12];
assert_eq!(a.as_slice().last().unwrap(), &12);
}
#[test]
fn test_slice() {
// Test fixed length vector.
- let vec_fixed = [1, 2, 3, 4];
+ let vec_fixed = [1i, 2, 3, 4];
let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
assert_eq!(v_a.len(), 3u);
let v_a = v_a.as_slice();
assert_eq!(v_a[2], 4);
// Test on stack.
- let vec_stack = &[1, 2, 3];
+ let vec_stack = &[1i, 2, 3];
let v_b = vec_stack.slice(1u, 3u).to_owned();
assert_eq!(v_b.len(), 2u);
let v_b = v_b.as_slice();
assert_eq!(v_b[1], 3);
// Test `Box<[T]>`
- let vec_unique = vec![1, 2, 3, 4, 5, 6];
+ let vec_unique = vec![1i, 2, 3, 4, 5, 6];
let v_d = vec_unique.slice(1u, 6u).to_owned();
assert_eq!(v_d.len(), 5u);
let v_d = v_d.as_slice();
#[test]
fn test_slice_from() {
- let vec = &[1, 2, 3, 4];
+ let vec = &[1i, 2, 3, 4];
assert_eq!(vec.slice_from(0), vec);
assert_eq!(vec.slice_from(2), &[3, 4]);
assert_eq!(vec.slice_from(4), &[]);
#[test]
fn test_slice_to() {
- let vec = &[1, 2, 3, 4];
+ let vec = &[1i, 2, 3, 4];
assert_eq!(vec.slice_to(4), vec);
assert_eq!(vec.slice_to(2), &[1, 2]);
assert_eq!(vec.slice_to(0), &[]);
#[test]
fn test_pop() {
- let mut v = vec![5];
+ let mut v = vec![5i];
let e = v.pop();
assert_eq!(v.len(), 0);
assert_eq!(e, Some(5));
#[test]
fn test_swap_remove() {
- let mut v = vec![1, 2, 3, 4, 5];
+ let mut v = vec![1i, 2, 3, 4, 5];
let mut e = v.swap_remove(0);
assert_eq!(e, Some(1));
- assert_eq!(v, vec![5, 2, 3, 4]);
+ assert_eq!(v, vec![5i, 2, 3, 4]);
e = v.swap_remove(3);
assert_eq!(e, Some(4));
- assert_eq!(v, vec![5, 2, 3]);
+ assert_eq!(v, vec![5i, 2, 3]);
e = v.swap_remove(3);
assert_eq!(e, None);
- assert_eq!(v, vec![5, 2, 3]);
+ assert_eq!(v, vec![5i, 2, 3]);
}
#[test]
fn test_push() {
// Test on-stack push().
let mut v = vec![];
- v.push(1);
+ v.push(1i);
assert_eq!(v.len(), 1u);
assert_eq!(v.as_slice()[0], 1);
// Test on-heap push().
- v.push(2);
+ v.push(2i);
assert_eq!(v.len(), 2u);
assert_eq!(v.as_slice()[0], 1);
assert_eq!(v.as_slice()[1], 2);
fn test_grow() {
// Test on-stack grow().
let mut v = vec![];
- v.grow(2u, &1);
+ v.grow(2u, &1i);
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
}
// Test on-heap grow().
- v.grow(3u, &2);
+ v.grow(3u, &2i);
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);
#[test]
fn test_grow_set() {
- let mut v = vec![1, 2, 3];
+ let mut v = vec![1i, 2, 3];
v.grow_set(4u, &4, 5);
let v = v.as_slice();
assert_eq!(v.len(), 5u);
#[test]
fn test_truncate() {
- let mut v = vec![box 6,box 5,box 4];
+ let mut v = vec![box 6i,box 5,box 4];
v.truncate(1);
let v = v.as_slice();
assert_eq!(v.len(), 1);
#[test]
fn test_clear() {
- let mut v = vec![box 6,box 5,box 4];
+ let mut v = vec![box 6i,box 5,box 4];
v.clear();
assert_eq!(v.len(), 0);
// If the unsafe block didn't drop things properly, we blow up here.
assert_eq!(v, b);
}
case(vec![], vec![]);
- case(vec![1], vec![1]);
- case(vec![1,1], vec![1]);
- case(vec![1,2,3], vec![1,2,3]);
- case(vec![1,1,2,3], vec![1,2,3]);
- case(vec![1,2,2,3], vec![1,2,3]);
- case(vec![1,2,3,3], vec![1,2,3]);
- case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
+ case(vec![1u], vec![1]);
+ case(vec![1u,1], vec![1]);
+ case(vec![1u,2,3], vec![1,2,3]);
+ case(vec![1u,1,2,3], vec![1,2,3]);
+ case(vec![1u,2,2,3], vec![1,2,3]);
+ case(vec![1u,2,3,3], vec![1,2,3]);
+ case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
}
#[test]
fn test_dedup_unique() {
- let mut v0 = vec![box 1, box 1, box 2, box 3];
+ let mut v0 = vec![box 1i, box 1, box 2, box 3];
v0.dedup();
- let mut v1 = vec![box 1, box 2, box 2, box 3];
+ let mut v1 = vec![box 1i, box 2, box 2, box 3];
v1.dedup();
- let mut v2 = vec![box 1, box 2, box 3, box 3];
+ let mut v2 = vec![box 1i, box 2, box 3, box 3];
v2.dedup();
/*
* If the boxed pointers were leaked or otherwise misused, valgrind
#[test]
fn test_dedup_shared() {
- let mut v0 = vec![box 1, box 1, box 2, box 3];
+ let mut v0 = vec![box 1i, box 1, box 2, box 3];
v0.dedup();
- let mut v1 = vec![box 1, box 2, box 2, box 3];
+ let mut v1 = vec![box 1i, box 2, box 2, box 3];
v1.dedup();
- let mut v2 = vec![box 1, box 2, box 3, box 3];
+ let mut v2 = vec![box 1i, box 2, box 3, box 3];
v2.dedup();
/*
* If the pointers were leaked or otherwise misused, valgrind and/or
#[test]
fn test_retain() {
- let mut v = vec![1, 2, 3, 4, 5];
+ let mut v = vec![1u, 2, 3, 4, 5];
v.retain(is_odd);
- assert_eq!(v, vec![1, 3, 5]);
+ assert_eq!(v, vec![1u, 3, 5]);
}
#[test]
fn test_element_swaps() {
- let mut v = [1, 2, 3];
+ let mut v = [1i, 2, 3];
for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
v.swap(a, b);
match i {
assert_eq!(it.next(), None);
}
{
- let v = [1, 2, 3];
+ let v = [1i, 2, 3];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 3*2);
#[test]
fn test_lexicographic_permutations() {
- let v : &mut[int] = &mut[1, 2, 3, 4, 5];
+ let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
assert!(v.prev_permutation() == false);
assert!(v.next_permutation());
assert_eq!(v, &mut[1, 2, 3, 5, 4]);
assert!(v.next_permutation());
assert_eq!(v, &mut[1, 2, 4, 5, 3]);
- let v : &mut[int] = &mut[1, 0, 0, 0];
+ let v : &mut[int] = &mut[1i, 0, 0, 0];
assert!(v.next_permutation() == false);
assert!(v.prev_permutation());
assert_eq!(v, &mut[0, 1, 0, 0]);
assert!(empty.prev_permutation() == false);
assert_eq!(empty, &mut[]);
- let one_elem : &mut[int] = &mut[4];
+ let one_elem : &mut[int] = &mut[4i];
assert!(one_elem.prev_permutation() == false);
assert_eq!(one_elem, &mut[4]);
assert!(one_elem.next_permutation() == false);
assert_eq!(one_elem, &mut[4]);
- let two_elem : &mut[int] = &mut[1, 2];
+ let two_elem : &mut[int] = &mut[1i, 2];
assert!(two_elem.prev_permutation() == false);
assert_eq!(two_elem, &mut[1, 2]);
assert!(two_elem.next_permutation());
#[test]
fn test_position_elem() {
- assert!([].position_elem(&1).is_none());
+ assert!([].position_elem(&1i).is_none());
- let v1 = vec![1, 2, 3, 3, 2, 5];
+ let v1 = vec![1i, 2, 3, 3, 2, 5];
assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
#[test]
fn test_bsearch_elem() {
- assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
- assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
- assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
- assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
- assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
- assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
- assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
- assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
- assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
+ assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
+ assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
+ assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
+ assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
- assert_eq!([2,4,6,8].bsearch_elem(&1), None);
- assert_eq!([2,4,6,8].bsearch_elem(&5), None);
- assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
- assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
+ assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
+ assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
+ assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
+ assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
- assert_eq!([2,4,6].bsearch_elem(&1), None);
- assert_eq!([2,4,6].bsearch_elem(&5), None);
- assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
- assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
+ assert_eq!([2i,4,6].bsearch_elem(&1), None);
+ assert_eq!([2i,4,6].bsearch_elem(&5), None);
+ assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
+ assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
- assert_eq!([2,4].bsearch_elem(&1), None);
- assert_eq!([2,4].bsearch_elem(&5), None);
- assert_eq!([2,4].bsearch_elem(&2), Some(0));
- assert_eq!([2,4].bsearch_elem(&4), Some(1));
+ assert_eq!([2i,4].bsearch_elem(&1), None);
+ assert_eq!([2i,4].bsearch_elem(&5), None);
+ assert_eq!([2i,4].bsearch_elem(&2), Some(0));
+ assert_eq!([2i,4].bsearch_elem(&4), Some(1));
- assert_eq!([2].bsearch_elem(&1), None);
- assert_eq!([2].bsearch_elem(&5), None);
- assert_eq!([2].bsearch_elem(&2), Some(0));
+ assert_eq!([2i].bsearch_elem(&1), None);
+ assert_eq!([2i].bsearch_elem(&5), None);
+ assert_eq!([2i].bsearch_elem(&2), Some(0));
- assert_eq!([].bsearch_elem(&1), None);
- assert_eq!([].bsearch_elem(&5), None);
+ assert_eq!([].bsearch_elem(&1i), None);
+ assert_eq!([].bsearch_elem(&5i), None);
- assert!([1,1,1,1,1].bsearch_elem(&1) != None);
- assert!([1,1,1,1,2].bsearch_elem(&1) != None);
- assert!([1,1,1,2,2].bsearch_elem(&1) != None);
- assert!([1,1,2,2,2].bsearch_elem(&1) != None);
- assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
+ assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
+ assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
+ assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
+ assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
+ assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
- assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
- assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
+ assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
}
#[test]
fn test_reverse() {
- let mut v: Vec<int> = vec![10, 20];
+ let mut v: Vec<int> = vec![10i, 20];
assert_eq!(*v.get(0), 10);
assert_eq!(*v.get(1), 20);
v.reverse();
#[test]
fn test_sort() {
for len in range(4u, 25) {
- for _ in range(0, 100) {
+ for _ in range(0i, 100) {
let mut v = task_rng().gen_iter::<uint>().take(len)
.collect::<Vec<uint>>();
let mut v1 = v.clone();
#[test]
fn test_sort_stability() {
- for len in range(4, 25) {
- for _ in range(0 , 10) {
- let mut counts = [0, .. 10];
+ for len in range(4i, 25) {
+ for _ in range(0u, 10) {
+ let mut counts = [0i, .. 10];
// create a vector like [(6, 1), (5, 1), (6, 2), ...],
// where the first item of each tuple is random, but
#[test]
fn test_partition() {
assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+ assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+ assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+ assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_partitioned() {
assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+ assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+ assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+ assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_concat() {
let v: [Vec<int>, ..0] = [];
assert_eq!(v.concat_vec(), vec![]);
- assert_eq!([vec![1], vec![2,3]].concat_vec(), vec![1, 2, 3]);
+ assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
- assert_eq!([&[1], &[2,3]].concat_vec(), vec![1, 2, 3]);
+ assert_eq!([&[1i], &[2i,3i]].concat_vec(), vec![1, 2, 3]);
}
#[test]
fn test_connect() {
let v: [Vec<int>, ..0] = [];
assert_eq!(v.connect_vec(&0), vec![]);
- assert_eq!([vec![1], vec![2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
- assert_eq!([vec![1], vec![2], vec![3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
+ assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
+ assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
- assert_eq!([&[1], &[2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
- assert_eq!([&[1], &[2], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
+ assert_eq!([&[1i], &[2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
+ assert_eq!([&[1i], &[2i], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
}
#[test]
fn test_shift() {
- let mut x = vec![1, 2, 3];
+ let mut x = vec![1i, 2, 3];
assert_eq!(x.shift(), Some(1));
- assert_eq!(&x, &vec![2, 3]);
+ assert_eq!(&x, &vec![2i, 3]);
assert_eq!(x.shift(), Some(2));
assert_eq!(x.shift(), Some(3));
assert_eq!(x.shift(), None);
#[test]
fn test_unshift() {
- let mut x = vec![1, 2, 3];
+ let mut x = vec![1i, 2, 3];
x.unshift(0);
assert_eq!(x, vec![0, 1, 2, 3]);
}
#[test]
fn test_insert() {
- let mut a = vec![1, 2, 4];
+ let mut a = vec![1i, 2, 4];
a.insert(2, 3);
assert_eq!(a, vec![1, 2, 3, 4]);
- let mut a = vec![1, 2, 3];
+ let mut a = vec![1i, 2, 3];
a.insert(0, 0);
assert_eq!(a, vec![0, 1, 2, 3]);
- let mut a = vec![1, 2, 3];
+ let mut a = vec![1i, 2, 3];
a.insert(3, 4);
assert_eq!(a, vec![1, 2, 3, 4]);
let mut a = vec![];
- a.insert(0, 1);
+ a.insert(0, 1i);
assert_eq!(a, vec![1]);
}
#[test]
#[should_fail]
fn test_insert_oob() {
- let mut a = vec![1, 2, 3];
+ let mut a = vec![1i, 2, 3];
a.insert(4, 5);
}
#[test]
fn test_remove() {
- let mut a = vec![1,2,3,4];
+ let mut a = vec![1i,2,3,4];
assert_eq!(a.remove(2), Some(3));
- assert_eq!(a, vec![1,2,4]);
+ assert_eq!(a, vec![1i,2,4]);
assert_eq!(a.remove(2), Some(4));
- assert_eq!(a, vec![1,2]);
+ assert_eq!(a, vec![1i,2]);
assert_eq!(a.remove(2), None);
- assert_eq!(a, vec![1,2]);
+ assert_eq!(a, vec![1i,2]);
assert_eq!(a.remove(0), Some(1));
- assert_eq!(a, vec![2]);
+ assert_eq!(a, vec![2i]);
assert_eq!(a.remove(0), Some(2));
assert_eq!(a, vec![]);
#[test]
fn test_slice_2() {
- let v = vec![1, 2, 3, 4, 5];
+ let v = vec![1i, 2, 3, 4, 5];
let v = v.slice(1u, 3u);
assert_eq!(v.len(), 2u);
assert_eq!(v[0], 2);
fn test_from_fn_fail() {
Vec::from_fn(100, |v| {
if v == 50 { fail!() }
- box 0
+ box 0i
});
}
if i == 50 {
fail!()
}
- (box 0, Rc::new(0))
+ (box 0i, Rc::new(0i))
})
}
#[test]
#[should_fail]
fn test_permute_fail() {
- let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
- (box 0, Rc::new(0)), (box 0, Rc::new(0))];
+ let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
+ (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
let mut i = 0;
for _ in v.permutations() {
if i == 2 {
#[should_fail]
fn test_copy_memory_oob() {
unsafe {
- let mut a = [1, 2, 3, 4];
- let b = [1, 2, 3, 4, 5];
+ let mut a = [1i, 2, 3, 4];
+ let b = [1i, 2, 3, 4, 5];
a.copy_memory(b);
}
}
#[test]
fn test_total_ord() {
- [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
- [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
- [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
- [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
- [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
+ [1i, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
+ [1i, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
+ [1i, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
+ [1i, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
+ [2i, 2].cmp(& &[1, 2, 3, 4]) == Greater;
}
#[test]
fn test_iterator() {
- let xs = [1, 2, 5, 10, 11];
+ let xs = [1i, 2, 5, 10, 11];
let mut it = xs.iter();
assert_eq!(it.size_hint(), (5, Some(5)));
assert_eq!(it.next().unwrap(), &1);
#[test]
fn test_random_access_iterator() {
- let xs = [1, 2, 5, 10, 11];
+ let xs = [1i, 2, 5, 10, 11];
let mut it = xs.iter();
assert_eq!(it.indexable(), 5);
#[test]
fn test_iter_size_hints() {
- let mut xs = [1, 2, 5, 10, 11];
+ let mut xs = [1i, 2, 5, 10, 11];
assert_eq!(xs.iter().size_hint(), (5, Some(5)));
assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
}
#[test]
fn test_iter_clone() {
- let xs = [1, 2, 5];
+ let xs = [1i, 2, 5];
let mut it = xs.iter();
it.next();
let mut jt = it.clone();
#[test]
fn test_mut_iterator() {
- let mut xs = [1, 2, 3, 4, 5];
+ let mut xs = [1i, 2, 3, 4, 5];
for x in xs.mut_iter() {
*x += 1;
}
#[test]
fn test_rev_iterator() {
- let xs = [1, 2, 5, 10, 11];
+ let xs = [1i, 2, 5, 10, 11];
let ys = [11, 10, 5, 2, 1];
let mut i = 0;
for &x in xs.iter().rev() {
#[test]
fn test_move_from() {
- let mut a = [1,2,3,4,5];
- let b = vec![6,7,8];
+ let mut a = [1i,2,3,4,5];
+ let b = vec![6i,7,8];
assert_eq!(a.move_from(b, 0, 3), 3);
- assert!(a == [6,7,8,4,5]);
- let mut a = [7,2,8,1];
- let b = vec![3,1,4,1,5,9];
+ assert!(a == [6i,7,8,4,5]);
+ let mut a = [7i,2,8,1];
+ let b = vec![3i,1,4,1,5,9];
assert_eq!(a.move_from(b, 0, 6), 4);
- assert!(a == [3,1,4,1]);
- let mut a = [1,2,3,4];
- let b = vec![5,6,7,8,9,0];
+ assert!(a == [3i,1,4,1]);
+ let mut a = [1i,2,3,4];
+ let b = vec![5i,6,7,8,9,0];
assert_eq!(a.move_from(b, 2, 3), 1);
- assert!(a == [7,2,3,4]);
- let mut a = [1,2,3,4,5];
- let b = vec![5,6,7,8,9,0];
+ assert!(a == [7i,2,3,4]);
+ let mut a = [1i,2,3,4,5];
+ let b = vec![5i,6,7,8,9,0];
assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
- assert!(a == [1,2,6,7,5]);
+ assert!(a == [1i,2,6,7,5]);
}
#[test]
fn test_copy_from() {
- let mut a = [1,2,3,4,5];
- let b = [6,7,8];
+ let mut a = [1i,2,3,4,5];
+ let b = [6i,7,8];
assert_eq!(a.copy_from(b), 3);
- assert!(a == [6,7,8,4,5]);
- let mut c = [7,2,8,1];
- let d = [3,1,4,1,5,9];
+ assert!(a == [6i,7,8,4,5]);
+ let mut c = [7i,2,8,1];
+ let d = [3i,1,4,1,5,9];
assert_eq!(c.copy_from(d), 4);
- assert!(c == [3,1,4,1]);
+ assert!(c == [3i,1,4,1]);
}
#[test]
fn test_reverse_part() {
- let mut values = [1,2,3,4,5];
+ let mut values = [1i,2,3,4,5];
values.mut_slice(1, 4).reverse();
assert!(values == [1,4,3,2,5]);
}
)
let empty: Vec<int> = vec![];
test_show_vec!(empty, "[]".to_string());
- test_show_vec!(vec![1], "[1]".to_string());
- test_show_vec!(vec![1, 2, 3], "[1, 2, 3]".to_string());
+ test_show_vec!(vec![1i], "[1]".to_string());
+ test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
"[[], [1], [1, 1]]".to_string());
let empty_mut: &mut [int] = &mut[];
test_show_vec!(empty_mut, "[]".to_string());
- test_show_vec!(&mut[1], "[1]".to_string());
- test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_string());
+ test_show_vec!(&mut[1i], "[1]".to_string());
+ test_show_vec!(&mut[1i, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
"[[], [1], [1, 1]]".to_string());
}
fn test_iter_zero_sized() {
let mut v = vec![Foo, Foo, Foo];
assert_eq!(v.len(), 3);
- let mut cnt = 0;
+ let mut cnt = 0u;
for f in v.iter() {
assert!(*f == Foo);
#[test]
fn test_shrink_to_fit() {
let mut xs = vec![0, 1, 2, 3];
- for i in range(4, 100) {
+ for i in range(4i, 100) {
xs.push(i)
}
assert_eq!(xs.capacity(), 128);
xs.shrink_to_fit();
assert_eq!(xs.capacity(), 100);
- assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
+ assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
}
#[test]
#[test]
fn test_mut_splitator() {
- let mut xs = [0,1,0,2,3,0,0,4,5,0];
+ let mut xs = [0i,1,0,2,3,0,0,4,5,0];
assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
for slice in xs.mut_split(|x| *x == 0) {
slice.reverse();
}
assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
- let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
+ let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
for slice in xs.mut_split(|x| *x == 0).take(5) {
slice.reverse();
}
#[test]
fn test_mut_splitator_rev() {
- let mut xs = [1,2,0,3,4,0,0,5,6,0];
+ let mut xs = [1i,2,0,3,4,0,0,5,6,0];
for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
slice.reverse();
}
#[test]
fn test_get_mut() {
- let mut v = [0,1,2];
+ let mut v = [0i,1,2];
assert_eq!(v.get_mut(3), None);
v.get_mut(1).map(|e| *e = 7);
assert_eq!(v[1], 7);
#[test]
#[should_fail]
fn test_mut_chunks_0() {
- let mut v = [1, 2, 3, 4];
+ let mut v = [1i, 2, 3, 4];
let _it = v.mut_chunks(0);
}
#[test]
fn test_mut_last() {
- let mut x = [1, 2, 3, 4, 5];
+ let mut x = [1i, 2, 3, 4, 5];
let h = x.mut_last();
assert_eq!(*h.unwrap(), 5);
#[bench]
fn mut_iterator(b: &mut Bencher) {
- let mut v = Vec::from_elem(100, 0);
+ let mut v = Vec::from_elem(100, 0i);
b.iter(|| {
- let mut i = 0;
+ let mut i = 0i;
for x in v.mut_iter() {
*x = i;
i += 1;
#[bench]
fn concat(b: &mut Bencher) {
- let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
+ let xss: Vec<Vec<uint>> =
+ Vec::from_fn(100, |i| range(0u, i).collect());
b.iter(|| {
xss.as_slice().concat_vec()
});
#[bench]
fn connect(b: &mut Bencher) {
- let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
+ let xss: Vec<Vec<uint>> =
+ Vec::from_fn(100, |i| range(0u, i).collect());
b.iter(|| {
xss.as_slice().connect_vec(&0)
});
let mut rng = weak_rng();
b.iter(|| {
let mut v = Vec::from_elem(30, (0u, 0u));
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
let l = v.len();
v.insert(rng.gen::<uint>() % (l + 1),
(1, 1));
let mut rng = weak_rng();
b.iter(|| {
let mut v = Vec::from_elem(130, (0u, 0u));
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
let l = v.len();
v.remove(rng.gen::<uint>() % l);
}
#[test]
fn test_find_mut() {
let mut m = SmallIntMap::new();
- assert!(m.insert(1, 12));
+ assert!(m.insert(1, 12i));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
let new = 100;
let mut map = SmallIntMap::new();
assert_eq!(map.len(), 0);
assert!(map.is_empty());
- assert!(map.insert(5, 20));
+ assert!(map.insert(5, 20i));
assert_eq!(map.len(), 1);
assert!(!map.is_empty());
assert!(map.insert(11, 12));
#[test]
fn test_clear() {
let mut map = SmallIntMap::new();
- assert!(map.insert(5, 20));
+ assert!(map.insert(5, 20i));
assert!(map.insert(11, 12));
assert!(map.insert(14, 22));
map.clear();
#[test]
fn test_swap() {
let mut m = SmallIntMap::new();
- assert_eq!(m.swap(1, 2), None);
- assert_eq!(m.swap(1, 3), Some(2));
- assert_eq!(m.swap(1, 4), Some(3));
+ assert_eq!(m.swap(1, 2i), None);
+ assert_eq!(m.swap(1, 3i), Some(2));
+ assert_eq!(m.swap(1, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = SmallIntMap::new();
- m.insert(1, 2);
+ m.insert(1, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
fn test_iterator() {
let mut m = SmallIntMap::new();
- assert!(m.insert(0, 1));
+ assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
fn test_iterator_size_hints() {
let mut m = SmallIntMap::new();
- assert!(m.insert(0, 1));
+ assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
fn test_mut_iterator() {
let mut m = SmallIntMap::new();
- assert!(m.insert(0, 1));
+ assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
fn test_rev_iterator() {
let mut m = SmallIntMap::new();
- assert!(m.insert(0, 1));
+ assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
fn test_mut_rev_iterator() {
let mut m = SmallIntMap::new();
- assert!(m.insert(0, 1));
+ assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
#[test]
fn test_move_iter() {
let mut m = SmallIntMap::new();
- m.insert(1, box 2);
+ m.insert(1, box 2i);
let mut called = false;
for (k, v) in m.move_iter() {
assert!(!called);
called = true;
assert_eq!(k, 1);
- assert_eq!(v, box 2);
+ assert_eq!(v, box 2i);
}
assert!(called);
- m.insert(2, box 1);
+ m.insert(2, box 1i);
}
#[test]
let mut map = SmallIntMap::new();
let empty = SmallIntMap::<int>::new();
- map.insert(1, 2);
- map.insert(3, 4);
+ map.insert(1, 2i);
+ map.insert(3, 4i);
let map_str = map.to_str();
let map_str = map_str.as_slice();
}
}
+impl<S: Str> Add<S, String> for String {
+ fn add(&self, other: &S) -> String {
+ let mut s = self.to_string();
+ s.push_str(other.as_slice());
+ return s;
+ }
+}
+
#[cfg(test)]
mod tests {
use std::prelude::*;
assert_eq!(s.len(), 0);
assert_eq!(s.as_slice(), "");
}
+
+ #[test]
+ fn test_str_add() {
+ let a = String::from_str("12345");
+ let b = a + "2";
+ let b = b + String::from_str("2");
+ assert_eq!(b.len(), 7);
+ assert_eq!(b.as_slice(), "1234522");
+ }
}
#[test]
fn find_not_found() {
let mut m = TreeMap::new();
- assert!(m.insert(1, 2));
- assert!(m.insert(5, 3));
- assert!(m.insert(9, 3));
+ assert!(m.insert(1i, 2i));
+ assert!(m.insert(5i, 3i));
+ assert!(m.insert(9i, 3i));
assert_eq!(m.find(&2), None);
}
#[test]
fn test_find_mut() {
let mut m = TreeMap::new();
- assert!(m.insert(1, 12));
+ assert!(m.insert(1i, 12i));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
let new = 100;
#[test]
fn insert_replace() {
let mut m = TreeMap::new();
- assert!(m.insert(5, 2));
+ assert!(m.insert(5i, 2i));
assert!(m.insert(2, 9));
assert!(!m.insert(2, 11));
assert_eq!(m.find(&2).unwrap(), &11);
fn test_clear() {
let mut m = TreeMap::new();
m.clear();
- assert!(m.insert(5, 11));
+ assert!(m.insert(5i, 11i));
assert!(m.insert(12, -3));
assert!(m.insert(19, 2));
m.clear();
let mut rng: rand::IsaacRng = rand::SeedableRng::from_seed(&[42]);
- for _ in range(0, 3) {
- for _ in range(0, 90) {
+ for _ in range(0u, 3) {
+ for _ in range(0u, 90) {
let k = rng.gen();
let v = rng.gen();
if !ctrl.iter().any(|x| x == &(k, v)) {
}
}
- for _ in range(0, 30) {
+ for _ in range(0u, 30) {
let r = rng.gen_range(0, ctrl.len());
let (key, _) = ctrl.remove(r).unwrap();
assert!(map.remove(&key));
#[test]
fn test_len() {
let mut m = TreeMap::new();
- assert!(m.insert(3, 6));
+ assert!(m.insert(3i, 6i));
assert_eq!(m.len(), 1);
assert!(m.insert(0, 0));
assert_eq!(m.len(), 2);
fn test_iterator() {
let mut m = TreeMap::new();
- assert!(m.insert(3, 6));
+ assert!(m.insert(3i, 6i));
assert!(m.insert(0, 0));
assert!(m.insert(4, 8));
assert!(m.insert(2, 4));
#[test]
fn test_interval_iteration() {
let mut m = TreeMap::new();
- for i in range(1, 100) {
+ for i in range(1i, 100i) {
assert!(m.insert(i * 2, i * 4));
}
- for i in range(1, 198) {
+ for i in range(1i, 198i) {
let mut lb_it = m.lower_bound(&i);
let (&k, &v) = lb_it.next().unwrap();
let lb = i + i % 2;
fn test_rev_iter() {
let mut m = TreeMap::new();
- assert!(m.insert(3, 6));
+ assert!(m.insert(3i, 6i));
assert!(m.insert(0, 0));
assert!(m.insert(4, 8));
assert!(m.insert(2, 4));
fn test_mut_interval_iter() {
let mut m_lower = TreeMap::new();
let mut m_upper = TreeMap::new();
- for i in range(1, 100) {
+ for i in range(1i, 100i) {
assert!(m_lower.insert(i * 2, i * 4));
assert!(m_upper.insert(i * 2, i * 4));
}
- for i in range(1, 199) {
+ for i in range(1i, 199) {
let mut lb_it = m_lower.mut_lower_bound(&i);
let (&k, v) = lb_it.next().unwrap();
let lb = i + i % 2;
assert_eq!(lb, k);
*v -= k;
}
- for i in range(0, 198) {
+ for i in range(0i, 198) {
let mut ub_it = m_upper.mut_upper_bound(&i);
let (&k, v) = ub_it.next().unwrap();
let ub = i + 2 - i % 2;
let mut b = TreeMap::new();
assert!(a == b);
- assert!(a.insert(0, 5));
+ assert!(a.insert(0i, 5i));
assert!(a != b);
assert!(b.insert(0, 4));
assert!(a != b);
let mut b = TreeMap::new();
assert!(!(a < b) && !(b < a));
- assert!(b.insert(0, 5));
+ assert!(b.insert(0i, 5i));
assert!(a < b);
assert!(a.insert(0, 7));
assert!(!(a < b) && b < a);
let mut b = TreeMap::new();
assert!(a <= b && a >= b);
- assert!(a.insert(1, 1));
+ assert!(a.insert(1i, 1i));
assert!(a > b && a >= b);
assert!(b < a && b <= a);
assert!(b.insert(2, 2));
#[test]
fn test_lazy_iterator() {
let mut m = TreeMap::new();
- let (x1, y1) = (2, 5);
+ let (x1, y1) = (2i, 5i);
let (x2, y2) = (9, 12);
let (x3, y3) = (20, -3);
let (x4, y4) = (29, 5);
#[test]
fn test_from_iter() {
- let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
+ let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: TreeMap<int, int> = xs.iter().map(|&x| x).collect();
fn test_clear() {
let mut s = TreeSet::new();
s.clear();
- assert!(s.insert(5));
+ assert!(s.insert(5i));
assert!(s.insert(12));
assert!(s.insert(19));
s.clear();
let mut ys = TreeSet::new();
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
- assert!(xs.insert(5));
- assert!(ys.insert(11));
+ assert!(xs.insert(5i));
+ assert!(ys.insert(11i));
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(7));
#[test]
fn test_subset_and_superset() {
let mut a = TreeSet::new();
- assert!(a.insert(0));
+ assert!(a.insert(0i));
assert!(a.insert(5));
assert!(a.insert(11));
assert!(a.insert(7));
let mut b = TreeSet::new();
- assert!(b.insert(0));
+ assert!(b.insert(0i));
assert!(b.insert(7));
assert!(b.insert(19));
assert!(b.insert(250));
fn test_iterator() {
let mut m = TreeSet::new();
- assert!(m.insert(3));
+ assert!(m.insert(3i));
assert!(m.insert(0));
assert!(m.insert(4));
assert!(m.insert(2));
fn test_rev_iter() {
let mut m = TreeSet::new();
- assert!(m.insert(3));
+ assert!(m.insert(3i));
assert!(m.insert(0));
assert!(m.insert(4));
assert!(m.insert(2));
#[test]
fn test_move_iter() {
- let s: TreeSet<int> = range(0, 5).collect();
+ let s: TreeSet<int> = range(0i, 5).collect();
let mut n = 0;
for x in s.move_iter() {
#[test]
fn test_move_iter_size_hint() {
- let s: TreeSet<int> = vec!(0, 1).move_iter().collect();
+ let s: TreeSet<int> = vec!(0i, 1).move_iter().collect();
let mut it = s.move_iter();
fn test_clone_eq() {
let mut m = TreeSet::new();
- m.insert(1);
+ m.insert(1i);
m.insert(2);
assert!(m.clone() == m);
#[test]
fn test_swap() {
let mut m = TreeMap::new();
- assert_eq!(m.swap(1, 2), None);
- assert_eq!(m.swap(1, 3), Some(2));
- assert_eq!(m.swap(1, 4), Some(3));
+ assert_eq!(m.swap(1u, 2i), None);
+ assert_eq!(m.swap(1u, 3i), Some(2));
+ assert_eq!(m.swap(1u, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = TreeMap::new();
- m.insert(1, 2);
+ m.insert(1u, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
#[test]
fn test_from_iter() {
- let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
+ let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
let set: TreeSet<int> = xs.iter().map(|&x| x).collect();
#[test]
fn test_find_mut() {
let mut m = TrieMap::new();
- assert!(m.insert(1, 12));
- assert!(m.insert(2, 8));
- assert!(m.insert(5, 14));
+ assert!(m.insert(1u, 12i));
+ assert!(m.insert(2u, 8i));
+ assert!(m.insert(5u, 14i));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
fn test_find_mut_missing() {
let mut m = TrieMap::new();
assert!(m.find_mut(&0).is_none());
- assert!(m.insert(1, 12));
+ assert!(m.insert(1u, 12i));
assert!(m.find_mut(&0).is_none());
assert!(m.insert(2, 8));
assert!(m.find_mut(&0).is_none());
#[test]
fn test_swap() {
let mut m = TrieMap::new();
- assert_eq!(m.swap(1, 2), None);
- assert_eq!(m.swap(1, 3), Some(2));
- assert_eq!(m.swap(1, 4), Some(3));
+ assert_eq!(m.swap(1u, 2i), None);
+ assert_eq!(m.swap(1u, 3i), Some(2));
+ assert_eq!(m.swap(1u, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = TrieMap::new();
- m.insert(1, 2);
+ m.insert(1u, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
fn bench_iter_small(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
m.insert(rng.gen(), rng.gen());
}
fn bench_iter_large(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
fn bench_lower_bound(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
b.iter(|| {
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
m.lower_bound(rng.gen());
}
});
fn bench_upper_bound(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
b.iter(|| {
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
m.upper_bound(rng.gen());
}
});
let mut rng = weak_rng();
b.iter(|| {
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
m.insert(rng.gen(), [1, .. 10]);
}
})
let mut rng = weak_rng();
b.iter(|| {
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
// only have the last few bits set.
m.insert(rng.gen::<uint>() & 0xff_ff, [1, .. 10]);
}
let mut rng = weak_rng();
b.iter(|| {
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
m.insert(rng.gen(), ());
}
})
let mut rng = weak_rng();
b.iter(|| {
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
// only have the last few bits set.
m.insert(rng.gen::<uint>() & 0xff_ff, ());
}
/// ```rust
/// # use std::vec::Vec;
/// let mut vec = Vec::new();
-/// vec.push(1);
-/// vec.push(2);
+/// vec.push(1i);
+/// vec.push(2i);
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec.get(0), &1);
/// The `vec!` macro is provided to make initialization more convenient:
///
/// ```rust
-/// let mut vec = vec!(1, 2, 3);
+/// let mut vec = vec!(1i, 2i, 3i);
/// vec.push(4);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3, 4);
+ /// let vec = vec!(1i, 2i, 3i, 4i);
/// let (even, odd) = vec.partition(|&n| n % 2 == 0);
/// assert_eq!(even, vec!(2, 4));
/// assert_eq!(odd, vec!(1, 3));
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2);
- /// let vec = vec.append([3, 4]);
+ /// let vec = vec!(1i, 2i);
+ /// let vec = vec.append([3i, 4i]);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
#[inline]
///
/// ```rust
/// # use std::vec::Vec;
- /// let slice = [1, 2, 3];
+ /// let slice = [1i, 2, 3];
/// let vec = Vec::from_slice(slice);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1);
- /// vec.push_all([2, 3, 4]);
+ /// let mut vec = vec!(1i);
+ /// vec.push_all([2i, 3, 4]);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3, 4);
+ /// let vec = vec!(1i, 2, 3, 4);
/// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
- /// assert_eq!(even, vec!(2, 4));
- /// assert_eq!(odd, vec!(1, 3));
+ /// assert_eq!(even, vec!(2i, 4));
+ /// assert_eq!(odd, vec!(1i, 3));
/// ```
pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
}
}
+#[unstable]
impl<T:Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
let len = self.len;
///
/// ```rust
/// # use std::vec::Vec;
- /// let mut vec: Vec<int> = vec!(1);
+ /// let mut vec: Vec<int> = vec!(1i);
/// vec.reserve_additional(10);
/// assert!(vec.capacity() >= 11);
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// vec.reserve(10);
/// assert!(vec.capacity() >= 10);
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// vec.shrink_to_fit();
/// ```
pub fn shrink_to_fit(&mut self) {
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// assert_eq!(vec.pop(), Some(3));
/// assert_eq!(vec, vec!(1, 2));
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2);
+ /// let mut vec = vec!(1i, 2);
/// vec.push(3);
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2);
+ /// let vec = vec!(1i, 2);
/// let vec = vec.append_one(3);
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3, 4);
+ /// let mut vec = vec!(1i, 2, 3, 4);
/// vec.truncate(2);
/// assert_eq!(vec, vec!(1, 2));
/// ```
/// ```rust
/// fn foo(slice: &mut [int]) {}
///
- /// let mut vec = vec!(1, 2);
+ /// let mut vec = vec!(1i, 2);
/// foo(vec.as_mut_slice());
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.get(1) == &2);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// *vec.get_mut(1) = 4;
- /// assert_eq!(vec, vec!(1, 4, 3));
+ /// assert_eq!(vec, vec!(1i, 4, 3));
/// ```
#[inline]
pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// for num in vec.iter() {
/// println!("{}", *num);
/// }
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// for num in vec.mut_iter() {
/// *num = 0;
/// }
/// ```rust
/// let mut v = vec!(5i, 4, 1, 3, 2);
/// v.sort_by(|a, b| a.cmp(b));
- /// assert_eq!(v, vec!(1, 2, 3, 4, 5));
+ /// assert_eq!(v, vec!(1i, 2, 3, 4, 5));
///
/// // reverse sorting
/// v.sort_by(|a, b| b.cmp(a));
- /// assert_eq!(v, vec!(5, 4, 3, 2, 1));
+ /// assert_eq!(v, vec!(5i, 4, 3, 2, 1));
/// ```
#[inline]
pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3, 4);
+ /// let vec = vec!(1i, 2, 3, 4);
/// assert!(vec.slice(0, 2) == [1, 2]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.tail() == [2, 3]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3, 4);
+ /// let vec = vec!(1i, 2, 3, 4);
/// assert!(vec.tailn(2) == [3, 4]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.last() == Some(&3));
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// *vec.mut_last().unwrap() = 4;
- /// assert_eq!(vec, vec!(1, 2, 4));
+ /// assert_eq!(vec, vec!(1i, 2, 4));
/// ```
#[inline]
pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// vec.unshift(4);
/// assert_eq!(vec, vec!(4, 1, 2, 3));
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// assert!(vec.shift() == Some(1));
/// assert_eq!(vec, vec!(2, 3));
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3);
+ /// let mut vec = vec!(1i, 2, 3);
/// vec.insert(1, 4);
/// assert_eq!(vec, vec!(1, 4, 2, 3));
/// ```
/// # Example
///
/// ```rust
- /// let mut v = vec!(1, 2, 3);
+ /// let mut v = vec!(1i, 2, 3);
/// assert_eq!(v.remove(1), Some(2));
/// assert_eq!(v, vec!(1, 3));
///
/// # Example
///
/// ```rust
- /// let mut vec = vec!(box 1);
+ /// let mut vec = vec!(box 1i);
/// vec.push_all_move(vec!(box 2, box 3, box 4));
/// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
/// ```
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3, 4);
+ /// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice(0, 2) == [1, 2]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3, 4);
+ /// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice_from(2) == [3, 4]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3, 4);
+ /// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice_to(2) == [1, 2]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 3, 4, 5, 6);
+ /// let mut vec = vec!(1i, 2, 3, 4, 5, 6);
///
/// // scoped to restrict the lifetime of the borrows
/// {
/// # Example
///
/// ```rust
- /// let mut v = vec!(1, 2, 3);
+ /// let mut v = vec!(1i, 2, 3);
/// v.reverse();
- /// assert_eq!(v, vec!(3, 2, 1));
+ /// assert_eq!(v, vec!(3i, 2, 1));
/// ```
#[inline]
pub fn reverse(&mut self) {
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.slice_from(1) == [2, 3]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.slice_to(2) == [1, 2]);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let vec = vec!(1, 2, 3);
+ /// let vec = vec!(1i, 2, 3);
/// assert!(vec.contains(&1));
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut vec = vec!(1, 2, 2, 3, 2);
+ /// let mut vec = vec!(1i, 2, 2, 3, 2);
/// vec.dedup();
- /// assert_eq!(vec, vec!(1, 2, 3, 2));
+ /// assert_eq!(vec, vec!(1i, 2, 3, 2));
/// ```
pub fn dedup(&mut self) {
unsafe {
/// ```rust
/// fn foo(slice: &[int]) {}
///
- /// let vec = vec!(1, 2);
+ /// let vec = vec!(1i, 2);
/// foo(vec.as_slice());
/// ```
#[inline]
v.reserve_additional(2);
assert!(v.capacity() >= 2);
- for i in range(0, 16) {
+ for i in range(0i, 16) {
v.push(i);
}
let mut v = Vec::new();
let mut w = Vec::new();
- v.extend(range(0, 3));
- for i in range(0, 3) { w.push(i) }
+ v.extend(range(0i, 3));
+ for i in range(0i, 3) { w.push(i) }
assert_eq!(v, w);
- v.extend(range(3, 10));
- for i in range(3, 10) { w.push(i) }
+ v.extend(range(3i, 10));
+ for i in range(3i, 10) { w.push(i) }
assert_eq!(v, w);
}
#[test]
fn test_clone() {
let v: Vec<int> = vec!();
- let w = vec!(1, 2, 3);
+ let w = vec!(1i, 2, 3);
assert_eq!(v, v.clone());
#[test]
fn test_clone_from() {
let mut v = vec!();
- let three = vec!(box 1, box 2, box 3);
- let two = vec!(box 4, box 5);
+ let three = vec!(box 1i, box 2, box 3);
+ let two = vec!(box 4i, box 5);
// zero, long
v.clone_from(&three);
assert_eq!(v, three);
#[test]
fn test_partition() {
assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+ assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+ assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+ assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_partitioned() {
assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
- assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+ assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+ assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+ assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_zip_unzip() {
- let z1 = vec![(1, 4), (2, 5), (3, 6)];
+ let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
let (left, right) = unzip(z1.iter().map(|&x| x));
fn test_unsafe_ptrs() {
unsafe {
// Test on-stack copy-from-buf.
- let a = [1, 2, 3];
+ let a = [1i, 2, 3];
let ptr = a.as_ptr();
let b = raw::from_buf(ptr, 3u);
assert_eq!(b, vec![1, 2, 3]);
// Test on-heap copy-from-buf.
- let c = vec![1, 2, 3, 4, 5];
+ let c = vec![1i, 2, 3, 4, 5];
let ptr = c.as_ptr();
let d = raw::from_buf(ptr, 5u);
assert_eq!(d, vec![1, 2, 3, 4, 5]);
#[bench]
fn bench_from_slice_5(b: &mut Bencher) {
b.iter(|| {
- let v: Vec<int> = Vec::from_slice([1, 2, 3, 4, 5]);
+ let v: Vec<int> = Vec::from_slice([1i, 2, 3, 4, 5]);
assert!(v.as_slice() == [1, 2, 3, 4, 5]);
})
}
#[bench]
fn bench_as_ref(b: &mut Bencher) {
b.iter(|| {
- let mut x = 0; let mut y = &mut x as &mut Any;
+ let mut x = 0i;
+ let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.as_ref::<int>() == Some(&0));
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Operations on boolean values (`bool` type)
-//!
-//! A `to_bit` conversion function.
+//! The boolean type
#![doc(primitive = "bool")]
-use num::{Int, one, zero};
-
-/////////////////////////////////////////////////////////////////////////////
-// Freestanding functions
-/////////////////////////////////////////////////////////////////////////////
-
-/// Convert a `bool` to an integer.
-///
-/// # Examples
-///
-/// ```rust
-/// use std::bool;
-///
-/// assert_eq!(bool::to_bit::<u8>(true), 1u8);
-/// assert_eq!(bool::to_bit::<u8>(false), 0u8);
-/// ```
-#[inline]
-pub fn to_bit<N: Int>(p: bool) -> N {
- if p { one() } else { zero() }
-}
-
-#[cfg(test)]
-mod tests {
- use realstd::prelude::*;
- use super::to_bit;
-
- #[test]
- fn test_to_bit() {
- assert_eq!(to_bit::<u8>(true), 1u8);
- assert_eq!(to_bit::<u8>(false), 0u8);
- }
-
- #[test]
- fn test_eq() {
- assert_eq!(false.eq(&true), false);
- assert_eq!(false == false, true);
- assert_eq!(false != true, true);
- assert_eq!(false.ne(&false), false);
- }
-
- #[test]
- fn test_bitand() {
- assert_eq!(false.bitand(&false), false);
- assert_eq!(true.bitand(&false), false);
- assert_eq!(false.bitand(&true), false);
- assert_eq!(true.bitand(&true), true);
-
- assert_eq!(false & false, false);
- assert_eq!(true & false, false);
- assert_eq!(false & true, false);
- assert_eq!(true & true, true);
- }
-
- #[test]
- fn test_bitor() {
- assert_eq!(false.bitor(&false), false);
- assert_eq!(true.bitor(&false), true);
- assert_eq!(false.bitor(&true), true);
- assert_eq!(true.bitor(&true), true);
-
- assert_eq!(false | false, false);
- assert_eq!(true | false, true);
- assert_eq!(false | true, true);
- assert_eq!(true | true, true);
- }
-
- #[test]
- fn test_bitxor() {
- assert_eq!(false.bitxor(&false), false);
- assert_eq!(true.bitxor(&false), true);
- assert_eq!(false.bitxor(&true), true);
- assert_eq!(true.bitxor(&true), false);
-
- assert_eq!(false ^ false, false);
- assert_eq!(true ^ false, true);
- assert_eq!(false ^ true, true);
- assert_eq!(true ^ true, false);
- }
-
- #[test]
- fn test_not() {
- assert_eq!(!true, false);
- assert_eq!(!false, true);
- }
-
- #[test]
- fn test_to_str() {
- let s = false.to_str();
- assert_eq!(s.as_slice(), "false");
- let s = true.to_str();
- assert_eq!(s.as_slice(), "true");
- }
-
- #[test]
- fn test_ord() {
- assert!(true > false);
- assert!(!(false > true));
-
- assert!(false < true);
- assert!(!(true < false));
-
- assert!(false <= false);
- assert!(false >= false);
- assert!(true <= true);
- assert!(true >= true);
-
- assert!(false <= true);
- assert!(!(false >= true));
- assert!(true >= false);
- assert!(!(true <= false));
- }
-
- #[test]
- fn test_totalord() {
- assert!(true.cmp(&true) == Equal);
- assert!(false.cmp(&false) == Equal);
- assert!(true.cmp(&false) == Greater);
- assert!(false.cmp(&true) == Less);
- }
-}
}
}
+#[unstable]
impl<T:Copy> Clone for Cell<T> {
fn clone(&self) -> Cell<T> {
Cell::new(self.get())
}
}
+#[unstable]
impl<T: Clone> Clone for RefCell<T> {
fn clone(&self) -> RefCell<T> {
RefCell::new(self.borrow().clone())
#[test]
fn smoketest_cell() {
- let x = Cell::new(10);
+ let x = Cell::new(10i);
assert!(x == Cell::new(10));
assert!(x.get() == 10);
x.set(20);
assert!(x == Cell::new(20));
assert!(x.get() == 20);
- let y = Cell::new((30, 40));
+ let y = Cell::new((30i, 40i));
assert!(y == Cell::new((30, 40)));
assert!(y.get() == (30, 40));
}
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
+ let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
*/
+#![unstable]
+
/// A common trait for cloning an object.
pub trait Clone {
/// Returns a copy of the value. The contents of owned pointers
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline(always)]
+ #[experimental = "this function is mostly unused"]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
macro_rules! extern_fn_clone(
($($A:ident),*) => (
+ #[experimental = "this may not be sufficient for fns with region parameters"]
impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType {
/// Return a copy of a function pointer
#[inline]
#[test]
fn test_clone_from() {
- let a = box 5;
- let mut b = box 10;
+ let a = box 5i;
+ let mut b = box 10i;
realclone_from(&mut b, &a);
assert_eq!(*b, 5);
}
#[test]
fn test_success() {
- let mut i = 0;
+ let mut i = 0i;
try_finally(
&mut i, (),
|i, ()| {
#[test]
#[should_fail]
fn test_fail() {
- let mut i = 0;
+ let mut i = 0i;
try_finally(
&mut i, (),
|i, ()| {
///
/// ~~~
/// use std::fmt::radix;
-/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
+/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ~~~
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
assert!(format!("{:o}", 1u64).as_slice() == "1");
// Test a larger number
- assert!(format!("{:t}", 55).as_slice() == "110111");
- assert!(format!("{:o}", 55).as_slice() == "67");
- assert!(format!("{:d}", 55).as_slice() == "55");
- assert!(format!("{:x}", 55).as_slice() == "37");
- assert!(format!("{:X}", 55).as_slice() == "37");
+ assert!(format!("{:t}", 55i).as_slice() == "110111");
+ assert!(format!("{:o}", 55i).as_slice() == "67");
+ assert!(format!("{:d}", 55i).as_slice() == "55");
+ assert!(format!("{:x}", 55i).as_slice() == "37");
+ assert!(format!("{:X}", 55i).as_slice() == "37");
}
#[test]
#[test]
fn test_format_int_flags() {
- assert!(format!("{:3d}", 1).as_slice() == " 1");
- assert!(format!("{:>3d}", 1).as_slice() == " 1");
- assert!(format!("{:>+3d}", 1).as_slice() == " +1");
- assert!(format!("{:<3d}", 1).as_slice() == "1 ");
- assert!(format!("{:#d}", 1).as_slice() == "1");
- assert!(format!("{:#x}", 10).as_slice() == "0xa");
- assert!(format!("{:#X}", 10).as_slice() == "0xA");
- assert!(format!("{:#5x}", 10).as_slice() == " 0xa");
- assert!(format!("{:#o}", 10).as_slice() == "0o12");
- assert!(format!("{:08x}", 10).as_slice() == "0000000a");
- assert!(format!("{:8x}", 10).as_slice() == " a");
- assert!(format!("{:<8x}", 10).as_slice() == "a ");
- assert!(format!("{:>8x}", 10).as_slice() == " a");
- assert!(format!("{:#08x}", 10).as_slice() == "0x00000a");
- assert!(format!("{:08d}", -10).as_slice() == "-0000010");
+ assert!(format!("{:3d}", 1i).as_slice() == " 1");
+ assert!(format!("{:>3d}", 1i).as_slice() == " 1");
+ assert!(format!("{:>+3d}", 1i).as_slice() == " +1");
+ assert!(format!("{:<3d}", 1i).as_slice() == "1 ");
+ assert!(format!("{:#d}", 1i).as_slice() == "1");
+ assert!(format!("{:#x}", 10i).as_slice() == "0xa");
+ assert!(format!("{:#X}", 10i).as_slice() == "0xA");
+ assert!(format!("{:#5x}", 10i).as_slice() == " 0xa");
+ assert!(format!("{:#o}", 10i).as_slice() == "0o12");
+ assert!(format!("{:08x}", 10i).as_slice() == "0000000a");
+ assert!(format!("{:8x}", 10i).as_slice() == " a");
+ assert!(format!("{:<8x}", 10i).as_slice() == "a ");
+ assert!(format!("{:>8x}", 10i).as_slice() == " a");
+ assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a");
+ assert!(format!("{:08d}", -10i).as_slice() == "-0000010");
assert!(format!("{:x}", -1u8).as_slice() == "ff");
assert!(format!("{:X}", -1u8).as_slice() == "FF");
assert!(format!("{:t}", -1u8).as_slice() == "11111111");
#[test]
fn test_format_int_sign_padding() {
- assert!(format!("{:+5d}", 1).as_slice() == " +1");
- assert!(format!("{:+5d}", -1).as_slice() == " -1");
- assert!(format!("{:05d}", 1).as_slice() == "00001");
- assert!(format!("{:05d}", -1).as_slice() == "-0001");
- assert!(format!("{:+05d}", 1).as_slice() == "+0001");
- assert!(format!("{:+05d}", -1).as_slice() == "-0001");
+ assert!(format!("{:+5d}", 1i).as_slice() == " +1");
+ assert!(format!("{:+5d}", -1i).as_slice() == " -1");
+ assert!(format!("{:05d}", 1i).as_slice() == "00001");
+ assert!(format!("{:05d}", -1i).as_slice() == "-0001");
+ assert!(format!("{:+05d}", 1i).as_slice() == "+0001");
+ assert!(format!("{:+05d}", -1i).as_slice() == "-0001");
}
#[test]
#[test]
fn test_format_radix() {
- assert!(format!("{:04}", radix(3, 2)).as_slice() == "0011");
- assert!(format!("{}", radix(55, 36)).as_slice() == "1j");
+ assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011");
+ assert!(format!("{}", radix(55i, 36)).as_slice() == "1j");
}
#[test]
translated to the `loop` below.
```rust
-let values = vec![1, 2, 3];
+let values = vec![1i, 2, 3];
// "Syntactical sugar" taking advantage of an iterator
for &x in values.iter() {
/// # Example
///
/// ```rust
- /// let a = [0];
- /// let b = [1];
+ /// let a = [0i];
+ /// let b = [1i];
/// let mut it = a.iter().chain(b.iter());
/// assert_eq!(it.next().unwrap(), &0);
/// assert_eq!(it.next().unwrap(), &1);
/// # Example
///
/// ```rust
- /// let a = [0];
- /// let b = [1];
+ /// let a = [0i];
+ /// let b = [1i];
/// let mut it = a.iter().zip(b.iter());
/// assert_eq!(it.next().unwrap(), (&0, &1));
/// assert!(it.next().is_none());
/// # Example
///
/// ```rust
- /// let a = [1, 2];
+ /// let a = [1i, 2];
/// let mut it = a.iter().map(|&x| 2 * x);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 4);
/// # Example
///
/// ```rust
- /// let a = [1, 2];
+ /// let a = [1i, 2];
/// let mut it = a.iter().filter(|&x| *x > 1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
/// # Example
///
/// ```rust
- /// let a = [1, 2];
+ /// let a = [1i, 2];
/// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
/// # Example
///
/// ```rust
- /// let a = [100, 200];
+ /// let a = [100i, 200];
/// let mut it = a.iter().enumerate();
/// assert_eq!(it.next().unwrap(), (0, &100));
/// assert_eq!(it.next().unwrap(), (1, &200));
/// # Example
///
/// ```rust
- /// let xs = [100, 200, 300];
+ /// let xs = [100i, 200, 300];
/// let mut it = xs.iter().map(|x| *x).peekable();
/// assert_eq!(it.peek().unwrap(), &100);
/// assert_eq!(it.next().unwrap(), 100);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 2, 1];
+ /// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().skip_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &3);
/// assert_eq!(it.next().unwrap(), &2);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 2, 1];
+ /// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().take_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().skip(3);
/// assert_eq!(it.next().unwrap(), &4);
/// assert_eq!(it.next().unwrap(), &5);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().take(3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().scan(1, |fac, &x| {
/// *fac = *fac * x;
/// Some(*fac)
/// }
/// sum
/// }
- /// let x = vec![1,2,3,7,8,9];
+ /// let x = vec![1i,2,3,7,8,9];
/// assert_eq!(process(x.move_iter()), 1006);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let mut xs = range(0, 10);
+ /// let mut xs = range(0u, 10);
/// // sum the first five values
/// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
/// assert!(partial_sum == 10);
/// # Example
///
/// ```rust
- /// range(0, 5).advance(|x| {print!("{} ", x); true});
+ /// range(0u, 5).advance(|x| {print!("{} ", x); true});
/// ```
#[inline]
fn advance(&mut self, f: |A| -> bool) -> bool {
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.nth(2).unwrap() == &3);
/// assert!(it.nth(2) == None);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().last().unwrap() == &5);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
/// ```
#[inline]
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.count() == 5);
/// assert!(it.count() == 0);
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().all(|x| *x > 0));
/// assert!(!a.iter().all(|x| *x > 2));
/// ```
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.any(|x| *x == 3));
/// assert!(!it.any(|x| *x == 3));
/// ```rust
/// use std::iter::AdditiveIterator;
///
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15);
/// ```
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().max().unwrap() == &5);
/// ```
fn max(&mut self) -> Option<A>;
/// # Example
///
/// ```rust
- /// let a = [1, 2, 3, 4, 5];
+ /// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().min().unwrap() == &1);
/// ```
fn min(&mut self) -> Option<A>;
/// let r: MinMaxResult<int> = NoElements;
/// assert_eq!(r.into_option(), None)
///
- /// let r = OneElement(1);
+ /// let r = OneElement(1i);
/// assert_eq!(r.into_option(), Some((1,1)));
///
- /// let r = MinMax(1,2);
+ /// let r = MinMax(1i,2i);
/// assert_eq!(r.into_option(), Some((1,2)));
/// ```
pub fn into_option(self) -> Option<(T,T)> {
/// ```rust
/// use std::iter::{CloneableIterator, count};
///
- /// let a = count(1,1).take(1);
+ /// let a = count(1i,1i).take(1);
/// let mut cy = a.cycle();
/// assert_eq!(cy.next(), Some(1));
/// assert_eq!(cy.next(), Some(1));
use slice::ImmutableVector;
let empty: [int, ..0] = [];
- let xs = [1,2,3];
- let ys = [1,2,0];
+ let xs = [1i,2,3];
+ let ys = [1i,2,0];
assert!(!lt(xs.iter(), ys.iter()));
assert!(!le(xs.iter(), ys.iter()));
assert!(!ge(empty.iter(), xs.iter()));
// Sequence with NaN
- let u = [1.0, 2.0];
- let v = [0.0/0.0, 3.0];
+ let u = [1.0f64, 2.0];
+ let v = [0.0f64/0.0, 3.0];
assert!(!lt(u.iter(), v.iter()));
assert!(!le(u.iter(), v.iter()));
assert!(!gt(u.iter(), v.iter()));
assert!(!ge(u.iter(), v.iter()));
- let a = [0.0/0.0];
- let b = [1.0];
- let c = [2.0];
+ let a = [0.0f64/0.0];
+ let b = [1.0f64];
+ let c = [2.0f64];
assert!(lt(a.iter(), b.iter()) == (a[0] < b[0]));
assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
#[test]
fn test_counter_from_iter() {
- let it = count(0, 5).take(10);
+ let it = count(0i, 5).take(10);
let xs: Vec<int> = FromIterator::from_iter(it);
assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}
#[test]
fn test_iterator_nth() {
- let v = &[0, 1, 2, 3, 4];
+ let v = &[0i, 1, 2, 3, 4];
for i in range(0u, v.len()) {
assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
}
#[test]
fn test_iterator_last() {
- let v = &[0, 1, 2, 3, 4];
+ let v = &[0i, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
}
#[test]
fn test_iterator_len() {
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().count(), 4);
assert_eq!(v.slice(0, 10).iter().count(), 10);
assert_eq!(v.slice(0, 0).iter().count(), 0);
#[test]
fn test_iterator_sum() {
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
#[test]
fn test_iterator_product() {
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
#[test]
fn test_iterator_max() {
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
assert_eq!(v.iter().map(|&x| x).max(), Some(10));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
#[test]
fn test_iterator_min() {
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
assert_eq!(v.iter().map(|&x| x).min(), Some(0));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
#[test]
fn test_iterator_size_hint() {
- let c = count(0, 1);
- let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
- let v2 = &[10, 11, 12];
+ let c = count(0i, 1);
+ let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+ let v2 = &[10i, 11, 12];
let vi = v.iter();
assert_eq!(c.size_hint(), (uint::MAX, None));
#[test]
fn test_collect() {
- let a = vec![1, 2, 3, 4, 5];
+ let a = vec![1i, 2, 3, 4, 5];
let b: Vec<int> = a.iter().map(|&x| x).collect();
assert!(a == b);
}
#[test]
fn test_all() {
- let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
+ let v: Box<&[int]> = box &[1i, 2, 3, 4, 5];
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
#[test]
fn test_any() {
- let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
+ let v: Box<&[int]> = box &[1i, 2, 3, 4, 5];
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
#[test]
fn test_find() {
- let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
+ let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11];
assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
assert!(v.iter().find(|x| *x % 12 == 0).is_none());
#[test]
fn test_position() {
- let v = &[1, 3, 9, 27, 103, 14, 11];
+ let v = &[1i, 3, 9, 27, 103, 14, 11];
assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
assert!(v.iter().position(|x| *x % 12 == 0).is_none());
#[test]
fn test_count() {
- let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
+ let xs = &[1i, 2, 2, 1, 5, 9, 0, 2];
assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3);
assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1);
assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0);
#[test]
fn test_max_by() {
- let xs: &[int] = &[-3, 0, 1, 5, -10];
+ let xs: &[int] = &[-3i, 0, 1, 5, -10];
assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
}
#[test]
fn test_min_by() {
- let xs: &[int] = &[-3, 0, 1, 5, -10];
+ let xs: &[int] = &[-3i, 0, 1, 5, -10];
assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
}
#[test]
fn test_by_ref() {
- let mut xs = range(0, 10);
+ let mut xs = range(0i, 10);
// sum the first five values
let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
assert_eq!(partial_sum, 10);
#[test]
fn test_rev() {
- let xs = [2, 4, 6, 8, 10, 12, 14, 16];
+ let xs = [2i, 4, 6, 8, 10, 12, 14, 16];
let mut it = xs.iter();
it.next();
it.next();
#[test]
fn test_double_ended_map() {
- let xs = [1, 2, 3, 4, 5, 6];
+ let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x * -1);
assert_eq!(it.next(), Some(-1));
assert_eq!(it.next(), Some(-2));
#[test]
fn test_double_ended_enumerate() {
- let xs = [1, 2, 3, 4, 5, 6];
+ let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x).enumerate();
assert_eq!(it.next(), Some((0, 1)));
assert_eq!(it.next(), Some((1, 2)));
#[test]
fn test_double_ended_zip() {
- let xs = [1, 2, 3, 4, 5, 6];
- let ys = [1, 2, 3, 7];
+ let xs = [1i, 2, 3, 4, 5, 6];
+ let ys = [1i, 2, 3, 7];
let a = xs.iter().map(|&x| x);
let b = ys.iter().map(|&x| x);
let mut it = a.zip(b);
#[test]
fn test_double_ended_filter() {
- let xs = [1, 2, 3, 4, 5, 6];
+ let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter(|&x| *x & 1 == 0);
assert_eq!(it.next_back().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &4);
#[test]
fn test_double_ended_filter_map() {
- let xs = [1, 2, 3, 4, 5, 6];
+ let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
assert_eq!(it.next_back().unwrap(), 12);
assert_eq!(it.next_back().unwrap(), 8);
#[test]
fn test_double_ended_chain() {
- let xs = [1, 2, 3, 4, 5];
- let ys = [7, 9, 11];
+ let xs = [1i, 2, 3, 4, 5];
+ let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter()).rev();
assert_eq!(it.next().unwrap(), &11)
assert_eq!(it.next().unwrap(), &9)
fn test_rposition() {
fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
- let v = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
+ let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
assert_eq!(v.iter().rposition(f), Some(3u));
assert!(v.iter().rposition(g).is_none());
#[test]
#[should_fail]
fn test_rposition_fail() {
- let v = [(box 0, box(GC) 0), (box 0, box(GC) 0),
- (box 0, box(GC) 0), (box 0, box(GC) 0)];
- let mut i = 0;
+ let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i),
+ (box 0i, box(GC) 0i), (box 0i, box(GC) 0i)];
+ let mut i = 0i;
v.iter().rposition(|_elt| {
if i == 2 {
fail!()
{
let mut b = a.clone();
assert_eq!(len, b.indexable());
- let mut n = 0;
+ let mut n = 0u;
for (i, elt) in a.enumerate() {
assert!(Some(elt) == b.idx(i));
n += 1;
#[test]
fn test_double_ended_flat_map() {
let u = [0u,1];
- let v = [5,6,7,8];
+ let v = [5u,6,7,8];
let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
assert_eq!(it.next_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &5);
#[test]
fn test_random_access_chain() {
- let xs = [1, 2, 3, 4, 5];
- let ys = [7, 9, 11];
+ let xs = [1i, 2, 3, 4, 5];
+ let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter());
assert_eq!(it.idx(0).unwrap(), &1);
assert_eq!(it.idx(5).unwrap(), &7);
#[test]
fn test_random_access_enumerate() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
check_randacc_iter(xs.iter().enumerate(), xs.len());
}
#[test]
fn test_random_access_rev() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
check_randacc_iter(xs.iter().rev(), xs.len());
let mut it = xs.iter().rev();
it.next();
#[test]
fn test_random_access_zip() {
- let xs = [1, 2, 3, 4, 5];
- let ys = [7, 9, 11];
+ let xs = [1i, 2, 3, 4, 5];
+ let ys = [7i, 9, 11];
check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
}
#[test]
fn test_random_access_take() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().take(3), 3);
check_randacc_iter(xs.iter().take(20), xs.len());
#[test]
fn test_random_access_skip() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
check_randacc_iter(empty.iter().skip(2), 0);
#[test]
fn test_random_access_inspect() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
// test .map and .inspect that don't implement Clone
let mut it = xs.iter().inspect(|_| {});
#[test]
fn test_random_access_map() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
let mut it = xs.iter().map(|x| *x);
assert_eq!(xs.len(), it.indexable());
#[test]
fn test_random_access_cycle() {
- let xs = [1, 2, 3, 4, 5];
+ let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().cycle().take(27), 27);
check_randacc_iter(empty.iter().cycle(), 0);
assert!(range(-10i, -1).collect::<Vec<int>>() ==
vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
assert!(range(0i, 5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]);
- assert_eq!(range(200, -5).count(), 0);
- assert_eq!(range(200, -5).rev().count(), 0);
- assert_eq!(range(200, 200).count(), 0);
- assert_eq!(range(200, 200).rev().count(), 0);
+ assert_eq!(range(200i, -5).count(), 0);
+ assert_eq!(range(200i, -5).rev().count(), 0);
+ assert_eq!(range(200i, 200).count(), 0);
+ assert_eq!(range(200i, 200).rev().count(), 0);
assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
vec![0i, 1, 2, 3, 4, 5]);
assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() ==
vec![5i, 4, 3, 2, 1, 0]);
- assert_eq!(range_inclusive(200, -5).count(), 0);
- assert_eq!(range_inclusive(200, -5).rev().count(), 0);
- assert!(range_inclusive(200, 200).collect::<Vec<int>>() == vec![200]);
- assert!(range_inclusive(200, 200).rev().collect::<Vec<int>>() == vec![200]);
+ assert_eq!(range_inclusive(200i, -5).count(), 0);
+ assert_eq!(range_inclusive(200i, -5).rev().count(), 0);
+ assert!(range_inclusive(200i, 200).collect::<Vec<int>>() == vec![200]);
+ assert!(range_inclusive(200i, 200).rev().collect::<Vec<int>>() == vec![200]);
}
#[test]
vec![20, 14, 8, 2]);
assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
- assert!(range_step(200, -5, 1).collect::<Vec<int>>() == vec![]);
- assert!(range_step(200, 200, 1).collect::<Vec<int>>() == vec![]);
+ assert!(range_step(200i, -5, 1).collect::<Vec<int>>() == vec![]);
+ assert!(range_step(200i, 200, 1).collect::<Vec<int>>() == vec![]);
}
#[test]
vec![20, 14, 8, 2]);
assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
- assert!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>() ==
+ assert!(range_step_inclusive(200i, -5, 1).collect::<Vec<int>>() ==
vec![]);
- assert!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>() ==
+ assert!(range_step_inclusive(200i, 200, 1).collect::<Vec<int>>() ==
vec![200]);
}
#[test]
fn test_reverse() {
- let mut ys = [1, 2, 3, 4, 5];
+ let mut ys = [1i, 2, 3, 4, 5];
ys.mut_iter().reverse_();
assert!(ys == [5, 4, 3, 2, 1]);
}
#[test]
fn test_peekable_is_empty() {
- let a = [1];
+ let a = [1i];
let mut it = a.iter().peekable();
assert!( !it.is_empty() );
it.next();
let r: MinMaxResult<int> = NoElements;
assert_eq!(r.into_option(), None)
- let r = OneElement(1);
+ let r = OneElement(1i);
assert_eq!(r.into_option(), Some((1,1)));
- let r = MinMax(1,2);
+ let r = MinMax(1i,2);
assert_eq!(r.into_option(), Some((1,2)));
}
}
/// ```
/// use std::cell::RefCell;
///
-/// let x = RefCell::new(1);
+/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
#[test]
fn test_swap() {
- let mut x = 31337;
- let mut y = 42;
+ let mut x = 31337i;
+ let mut y = 42i;
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);
trait Foo {}
impl Foo for int {}
- let a = box 100 as Box<Foo>;
+ let a = box 100i as Box<Foo>;
unsafe {
let x: raw::TraitObject = transmute(a);
assert!(*(x.data as *int) == 100);
//! Operations and constants for signed 16-bits integers (`i16` type)
+#![unstable]
#![doc(primitive = "i16")]
int_module!(i16, 16)
//! Operations and constants for signed 32-bits integers (`i32` type)
+#![unstable]
#![doc(primitive = "i32")]
int_module!(i32, 32)
//! Operations and constants for signed 64-bits integers (`i64` type)
+#![unstable]
#![doc(primitive = "i64")]
int_module!(i64, 64)
//! Operations and constants for signed 8-bits integers (`i8` type)
+#![unstable]
#![doc(primitive = "i8")]
int_module!(i8, 8)
//! Operations and constants for architecture-sized signed integers (`int` type)
+#![unstable]
#![doc(primitive = "int")]
#[cfg(target_word_size = "32")] int_module!(int, 32)
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
+#[unstable]
pub static BITS : uint = $bits;
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
+#[unstable]
pub static BYTES : uint = ($bits / 8);
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::min_value` function.
+#[unstable]
pub static MIN: $T = (-1 as $T) << (BITS - 1);
// FIXME(#9837): Compute MIN like this so the high bits that shouldn't exist are 0.
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::max_value` function.
+#[unstable]
pub static MAX: $T = !MIN;
#[cfg(test)]
/// ```rust
/// use std::num;
///
-/// assert_eq!(num::pow(2, 4), 16);
+/// assert_eq!(num::pow(2i, 4), 16);
/// ```
#[inline]
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
/// ```
/// use std::num;
///
-/// let twenty: f32 = num::cast(0x14).unwrap();
+/// let twenty: f32 = num::cast(0x14i).unwrap();
/// assert_eq!(twenty, 20f32);
/// ```
///
/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
- assert_eq!(ten.add(&two), cast(12).unwrap());
- assert_eq!(ten.sub(&two), cast(8).unwrap());
- assert_eq!(ten.mul(&two), cast(20).unwrap());
- assert_eq!(ten.div(&two), cast(5).unwrap());
- assert_eq!(ten.rem(&two), cast(0).unwrap());
+ assert_eq!(ten.add(&two), cast(12i).unwrap());
+ assert_eq!(ten.sub(&two), cast(8i).unwrap());
+ assert_eq!(ten.mul(&two), cast(20i).unwrap());
+ assert_eq!(ten.div(&two), cast(5i).unwrap());
+ assert_eq!(ten.rem(&two), cast(0i).unwrap());
assert_eq!(ten.add(&two), ten + two);
assert_eq!(ten.sub(&two), ten - two);
//! Operations and constants for unsigned 16-bits integers (`u16` type)
+#![unstable]
#![doc(primitive = "u16")]
uint_module!(u16, i16, 16)
//! Operations and constants for unsigned 32-bits integers (`u32` type)
+#![unstable]
#![doc(primitive = "u32")]
uint_module!(u32, i32, 32)
//! Operations and constants for unsigned 64-bits integer (`u64` type)
+#![unstable]
#![doc(primitive = "u64")]
uint_module!(u64, i64, 64)
//! Operations and constants for unsigned 8-bits integers (`u8` type)
+#![unstable]
#![doc(primitive = "u8")]
uint_module!(u8, i8, 8)
//! Operations and constants for architecture-sized unsigned integers (`uint` type)
+#![unstable]
#![doc(primitive = "uint")]
uint_module!(uint, int, ::int::BITS)
macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (
+#[unstable]
pub static BITS : uint = $bits;
+#[unstable]
pub static BYTES : uint = ($bits / 8);
+#[unstable]
pub static MIN: $T = 0 as $T;
+#[unstable]
pub static MAX: $T = 0 as $T - 1 as $T;
#[cfg(test)]
macro_rules! shl_impl(
($($t:ty)*) => ($(
- #[cfg(not(test))]
+ #[cfg(stage0)]
impl Shl<$t, $t> for $t {
#[inline]
fn shl(&self, other: &$t) -> $t { (*self) << (*other) }
}
+ #[cfg(not(stage0), not(test))]
+ impl Shl<$t, $t> for $t {
+ #[inline]
+ fn shl(&self, other: &$t) -> $t {
+ (*self) << (*other as uint)
+ }
+ }
)*)
)
macro_rules! shr_impl(
($($t:ty)*) => ($(
- #[cfg(not(test))]
+ #[cfg(stage0, not(test))]
impl Shr<$t, $t> for $t {
#[inline]
fn shr(&self, other: &$t) -> $t { (*self) >> (*other) }
}
+ #[cfg(not(stage0), not(test))]
+ impl Shr<$t, $t> for $t {
+ #[inline]
+ fn shr(&self, other: &$t) -> $t { (*self) >> (*other as uint) }
+ }
)*)
)
/// let good_year = from_str(good_year_from_input).unwrap_or_default();
/// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
///
- /// assert_eq!(1909, good_year);
- /// assert_eq!(0, bad_year);
+ /// assert_eq!(1909i, good_year);
+ /// assert_eq!(0i, bad_year);
/// ```
#[inline]
pub fn unwrap_or_default(self) -> T {
t.clone()
}
- let i = Rc::new(RefCell::new(0));
+ let i = Rc::new(RefCell::new(0i));
{
let x = r(realclone(&i));
let opt = Some(x);
#[test]
fn test_option_dance() {
let x = Some(());
- let mut y = Some(5);
+ let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take_unwrap();
#[test]
fn test_and() {
- let x: Option<int> = Some(1);
- assert_eq!(x.and(Some(2)), Some(2));
+ let x: Option<int> = Some(1i);
+ assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
- assert_eq!(x.and(Some(2)), None);
+ assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_option_while_some() {
- let mut i = 0;
+ let mut i = 0i;
Some(10).while_some(|j| {
i += 1;
if j > 0 {
#[test]
fn test_unwrap() {
- assert_eq!(Some(1).unwrap(), 1);
+ assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
fn test_filtered() {
- let some_stuff = Some(42);
+ let some_stuff = Some(42i);
let modified_stuff = some_stuff.filtered(|&x| {x < 10});
assert_eq!(some_stuff.unwrap(), 42);
assert!(modified_stuff.is_none());
#[test]
fn test_iter() {
- let val = 5;
+ let val = 5i;
let x = Some(val);
let mut it = x.iter();
#[test]
fn test_mut_iter() {
- let val = 5;
- let new_val = 11;
+ let val = 5i;
+ let new_val = 11i;
let mut x = Some(val);
{
#[test]
fn test_ord() {
- let small = Some(1.0);
- let big = Some(5.0);
- let nan = Some(0.0/0.0);
+ let small = Some(1.0f64);
+ let big = Some(5.0f64);
+ let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
#[test]
fn test_collect() {
- let v: Option<Vec<int>> = collect(range(0, 0)
- .map(|_| Some(0)));
+ let v: Option<Vec<int>> = collect(range(0i, 0)
+ .map(|_| Some(0i)));
assert!(v == Some(vec![]));
- let v: Option<Vec<int>> = collect(range(0, 3)
+ let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| Some(x)));
assert!(v == Some(vec![0, 1, 2]));
- let v: Option<Vec<int>> = collect(range(0, 3)
+ let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| if x > 1 { None } else { Some(x) }));
assert!(v == None);
#[test]
fn test_ptr_addition() {
unsafe {
- let xs = Vec::from_elem(16, 5);
+ let xs = Vec::from_elem(16, 5i);
let mut ptr = xs.as_ptr();
let end = ptr.offset(16);
m_ptr = m_ptr.offset(1);
}
- assert!(xs_mut == Vec::from_elem(16, 10));
+ assert!(xs_mut == Vec::from_elem(16, 10i));
}
}
];
let arr_ptr = arr.as_ptr();
- let mut ctr = 0;
- let mut iteration_count = 0;
+ let mut ctr = 0u;
+ let mut iteration_count = 0u;
array_each(arr_ptr, |e| {
let actual = str::raw::from_c_str(e);
let expected = expected_arr[ctr].with_ref(|buf| {
#[test]
pub fn test_and() {
- assert_eq!(op1().and(Ok(667)).unwrap(), 667);
+ assert_eq!(op1().and(Ok(667i)).unwrap(), 667);
assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(),
"bad");
- assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
+ assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(),
"sadface");
}
#[test]
fn test_collect() {
- let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
+ let v: Result<Vec<int>, ()> = collect(range(0i, 0).map(|_| Ok::<int, ()>(0)));
assert!(v == Ok(vec![]));
- let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
+ let v: Result<Vec<int>, ()> = collect(range(0i, 3).map(|x| Ok::<int, ()>(x)));
assert!(v == Ok(vec![0, 1, 2]));
- let v: Result<Vec<int>, int> = collect(range(0, 3)
+ let v: Result<Vec<int>, int> = collect(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(x) }));
assert!(v == Err(2));
// test that it does not take more elements than it needs
- let mut functions = [|| Ok(()), || Err(1), || fail!()];
+ let mut functions = [|| Ok(()), || Err(1i), || fail!()];
let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
assert!(v == Err(1));
#[test]
fn test_fold() {
- assert_eq!(fold_(range(0, 0)
+ assert_eq!(fold_(range(0i, 0)
.map(|_| Ok::<(), ()>(()))),
Ok(()));
- assert_eq!(fold(range(0, 3)
+ assert_eq!(fold(range(0i, 3)
.map(|x| Ok::<int, ()>(x)),
0, |a, b| a + b),
Ok(3));
- assert_eq!(fold_(range(0, 3)
+ assert_eq!(fold_(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(()) })),
Err(2));
// test that it does not take more elements than it needs
- let mut functions = [|| Ok(()), || Err(1), || fail!()];
+ let mut functions = [|| Ok(()), || Err(1i), || fail!()];
assert_eq!(fold_(functions.mut_iter()
.map(|f| (*f)())),
#[test]
pub fn test_unwrap_or() {
- let ok: Result<int, &'static str> = Ok(100);
+ let ok: Result<int, &'static str> = Ok(100i);
let ok_err: Result<int, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
pub fn test_unwrap_or_else() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
- 50
+ 50i
} else {
fail!("BadBad")
}
pub fn test_unwrap_or_else_failure() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
- 50
+ 50i
} else {
fail!("BadBad")
}
* `[3,4]`):
*
* ```rust
- * let v = &[1,2,3,4];
+ * let v = &[1i, 2, 3, 4];
* for win in v.windows(2) {
* println!("{}", win);
* }
* `[3,4]`, `[5]`):
*
* ```rust
- * let v = &[1,2,3,4,5];
+ * let v = &[1i, 2, 3, 4, 5];
* for win in v.chunks(2) {
* println!("{}", win);
* }
/// # Example
///
/// ```rust
- /// let mut v = [1, 2, 3, 4, 5, 6];
+ /// let mut v = [1i, 2, 3, 4, 5, 6];
///
/// // scoped to restrict the lifetime of the borrows
/// {
/// let (left, right) = v.mut_split_at(0);
/// assert!(left == &mut []);
- /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
+ /// assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
/// }
///
/// {
/// let (left, right) = v.mut_split_at(2);
- /// assert!(left == &mut [1, 2]);
- /// assert!(right == &mut [3, 4, 5, 6]);
+ /// assert!(left == &mut [1i, 2]);
+ /// assert!(right == &mut [3i, 4, 5, 6]);
/// }
///
/// {
/// let (left, right) = v.mut_split_at(6);
- /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
+ /// assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
/// assert!(right == &mut []);
/// }
/// ```
/// # Example
///
/// ```rust
- /// let mut v = [1, 2, 3];
+ /// let mut v = [1i, 2, 3];
/// v.reverse();
- /// assert!(v == [3, 2, 1]);
+ /// assert!(v == [3i, 2, 1]);
/// ```
fn reverse(self);
/// ```rust
/// use std::slice::MutableCloneableVector;
///
- /// let mut dst = [0, 0, 0];
- /// let src = [1, 2];
+ /// let mut dst = [0i, 0, 0];
+ /// let src = [1i, 2];
///
/// assert!(dst.copy_from(src) == 2);
/// assert!(dst == [1, 2, 0]);
///
- /// let src2 = [3, 4, 5, 6];
+ /// let src2 = [3i, 4, 5, 6];
/// assert!(dst.copy_from(src2) == 3);
- /// assert!(dst == [3, 4, 5]);
+ /// assert!(dst == [3i, 4, 5]);
/// ```
fn copy_from(self, &[T]) -> uint;
}
period = period2;
}
- let byteset = needle.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a);
+ let byteset = needle.iter()
+ .fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
if needle.slice_to(critPos) == needle.slice_from(needle.len() - critPos) {
TwoWaySearcher {
}
// Quickly skip by large portions unrelated to our substring
- if (self.byteset >> (haystack[self.position + needle.len() - 1] & 0x3f)) & 1 == 0 {
+ if (self.byteset >>
+ ((haystack[self.position + needle.len() - 1] & 0x3f)
+ as uint)) & 1 == 0 {
self.position += needle.len();
continue 'search;
}
//! Using methods:
//!
//! ```
-//! let pair = ("pi", 3.14);
+//! let pair = ("pi", 3.14f64);
//! assert_eq!(pair.val0(), "pi");
-//! assert_eq!(pair.val1(), 3.14);
+//! assert_eq!(pair.val1(), 3.14f64);
//! ```
//!
//! Using traits implemented for tuples:
//! ```
//! use std::default::Default;
//!
-//! let a = (1, 2);
-//! let b = (3, 4);
+//! let a = (1i, 2i);
+//! let b = (3i, 4i);
//! assert!(a != b);
//!
//! let c = b.clone();
)+
}
+ #[unstable]
impl<$($T:Clone),+> Clone for ($($T,)+) {
fn clone(&self) -> ($($T,)+) {
($(self.$refN().clone(),)+)
#[test]
fn test_clone() {
- let a = (1, "2");
+ let a = (1i, "2");
let b = a.clone();
assert_eq!(a, b);
}
fn test_tuple_cmp() {
let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u));
- let nan = 0.0/0.0;
+ let nan = 0.0f64/0.0;
// PartialEq
assert_eq!(small, small);
assert!(big >= small);
assert!(big >= big);
- assert!(!((1.0, 2.0) < (nan, 3.0)));
- assert!(!((1.0, 2.0) <= (nan, 3.0)));
- assert!(!((1.0, 2.0) > (nan, 3.0)));
- assert!(!((1.0, 2.0) >= (nan, 3.0)));
- assert!(((1.0, 2.0) < (2.0, nan)));
- assert!(!((2.0, 2.0) < (2.0, nan)));
+ assert!(!((1.0f64, 2.0f64) < (nan, 3.0)));
+ assert!(!((1.0f64, 2.0f64) <= (nan, 3.0)));
+ assert!(!((1.0f64, 2.0f64) > (nan, 3.0)));
+ assert!(!((1.0f64, 2.0f64) >= (nan, 3.0)));
+ assert!(((1.0f64, 2.0f64) < (2.0, nan)));
+ assert!(!((2.0f64, 2.0f64) < (2.0, nan)));
// Ord
assert!(small.cmp(&small) == Equal);
#[test]
fn test_show() {
- let s = format!("{}", (1,));
+ let s = format!("{}", (1i,));
assert_eq!(s.as_slice(), "(1,)");
- let s = format!("{}", (1, true));
+ let s = format!("{}", (1i, true));
assert_eq!(s.as_slice(), "(1, true)");
- let s = format!("{}", (1, "hi", true));
+ let s = format!("{}", (1i, "hi", true));
assert_eq!(s.as_slice(), "(1, hi, true)");
}
}
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
let mut input = vec![];
- for _ in range(0, 2000) {
+ for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
fn test_range_pattern() {
let pat = Pattern::new("a[0-9]b");
- for i in range(0, 10) {
+ for i in range(0u, 10) {
assert!(pat.matches(format!("a{}b", i).as_slice()));
}
assert!(!pat.matches("a_b"));
let pat = Pattern::new("a[!0-9]b");
- for i in range(0, 10) {
+ for i in range(0u, 10) {
assert!(!pat.matches(format!("a{}b", i).as_slice()));
}
assert!(pat.matches("a_b"));
event_loop_factory: basic::event_loop,
});
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
pool.spawn(TaskOpts::new(), proc() {
let (tx, rx) = channel();
spawn(proc() {
fn multithreading() {
run(proc() {
let mut rxs = vec![];
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
let (tx, rx) = channel();
spawn(proc() {
tx.send(());
fn single_threaded_yield() {
use std::task::deschedule;
run(proc() {
- for _ in range(0, 5) { deschedule(); }
+ for _ in range(0u, 5) { deschedule(); }
});
}
// Testing that a task in one scheduler can block in foreign code
// without affecting other schedulers
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
let mut pool = pool();
let (start_tx, start_rx) = channel();
let (fin_tx, fin_rx) = channel();
fn yield_test() {
let (tx, rx) = channel();
spawn_opts(TaskOpts::new(), proc() {
- for _ in range(0, 10) { task::deschedule(); }
+ for _ in range(0u, 10) { task::deschedule(); }
tx.send(());
});
rx.recv();
error!("this is printed by default");
if log_enabled!(log::INFO) {
- let x = 3 * 4; // expensive computation
+ let x = 3i * 4i; // expensive computation
info!("the answer was: {}", x);
}
}
/// # fn main() {
/// log!(log::DEBUG, "this is a debug message");
/// log!(log::WARN, "this is a warning {}", "message");
-/// log!(6, "this is a custom logging level: {level}", level=6);
+/// log!(6, "this is a custom logging level: {level}", level=6u);
/// # }
/// ```
#[macro_export]
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
-/// # let error = 3;
+/// # let error = 3u;
/// error!("the build has failed with error code: {}", error);
/// # }
/// ```
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
-/// # let code = 3;
+/// # let code = 3u;
/// warn!("you may like to know that a process exited with: {}", code);
/// # }
/// ```
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
-/// # let ret = 3;
+/// # let ret = 3i;
/// info!("this function is about to return: {}", ret);
/// # }
/// ```
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
-/// debug!("x = {x}, y = {y}", x=10, y=20);
+/// debug!("x = {x}, y = {y}", x=10i, y=20i);
/// # }
/// ```
#[macro_export]
}
pub fn fd_set(set: &mut fd_set, fd: i32) {
- set.fds_bits[(fd / 32) as uint] |= 1 << (fd % 32);
+ set.fds_bits[(fd / 32) as uint] |= 1 << ((fd % 32) as uint);
}
}
fn yield_test() {
let (tx, rx) = channel();
spawn(proc() {
- for _ in range(0, 10) { task::deschedule(); }
+ for _ in range(0u, 10) { task::deschedule(); }
tx.send(());
});
rx.recv();
fn test_rand_range() {
let mut rng = task_rng();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
&FromPrimitive::from_uint(237).unwrap()),
FromPrimitive::from_uint(236).unwrap());
let l = FromPrimitive::from_uint(403469000 + 2352).unwrap();
let u = FromPrimitive::from_uint(403469000 + 3513).unwrap();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let n: BigUint = rng.gen_biguint_below(&u);
assert!(n < u);
fn test_rand_range() {
let mut rng = task_rng();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
&FromPrimitive::from_uint(237).unwrap()),
FromPrimitive::from_uint(236).unwrap());
fn check(l: BigInt, u: BigInt) {
let mut rng = task_rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let n: BigInt = rng.gen_bigint_range(&l, &u);
assert!(n >= l);
assert!(n < u);
let n = { let one : BigUint = One::one(); one << 1000 };
b.iter(|| {
let mut m = n.clone();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
m = m >> 1;
}
})
html_root_url = "http://doc.rust-lang.org/",
html_playground_url = "http://play.rust-lang.org/")]
+#![allow(deprecated)] // from_str_radix
+
extern crate rand;
pub use bigint::{BigInt, BigUint};
// check our constants are what Ratio::new etc. would make.
assert_eq!(_0, Zero::zero());
assert_eq!(_1, One::one());
- assert_eq!(_2, Ratio::from_integer(2));
- assert_eq!(_1_2, Ratio::new(1,2));
- assert_eq!(_3_2, Ratio::new(3,2));
- assert_eq!(_neg1_2, Ratio::new(-1,2));
+ assert_eq!(_2, Ratio::from_integer(2i));
+ assert_eq!(_1_2, Ratio::new(1i,2i));
+ assert_eq!(_3_2, Ratio::new(3i,2i));
+ assert_eq!(_neg1_2, Ratio::new(-1i,2i));
}
#[test]
#[test]
#[should_fail]
fn test_new_zero() {
- let _a = Ratio::new(1,0);
+ let _a = Ratio::new(1i,0);
}
}
test(_1, _1_2, _1_2);
- test(_1_2, _3_2, Ratio::new(3,4));
- test(_1_2, _neg1_2, Ratio::new(-1, 4));
+ test(_1_2, _3_2, Ratio::new(3i,4i));
+ test(_1_2, _neg1_2, Ratio::new(-1i, 4i));
}
#[test]
test16(_2, "2/1".to_string());
test16(_neg1_2, "-1/2".to_string());
test16(_neg1_2 / _2, "-1/4".to_string());
- test16(Ratio::new(13,15), "d/f".to_string());
+ test16(Ratio::new(13i,15i), "d/f".to_string());
test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_string());
}
test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
test(684729.48391f64, ("367611342500051", "536870912"));
- test(-8573.5918555, ("-4713381968463931", "549755813888"));
+ test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
}
fn test_exp() {
let mut exp = Exp::new(10.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
assert!(exp.sample(&mut rng) >= 0.0);
assert!(exp.ind_sample(&mut rng) >= 0.0);
}
fn test_chi_squared_one() {
let mut chi = ChiSquared::new(1.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
fn test_chi_squared_small() {
let mut chi = ChiSquared::new(0.5);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
fn test_chi_squared_large() {
let mut chi = ChiSquared::new(30.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
fn test_f() {
let mut f = FisherF::new(2.0, 32.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
f.sample(&mut rng);
f.ind_sample(&mut rng);
}
fn test_t() {
let mut t = StudentT::new(11.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
t.sample(&mut rng);
t.ind_sample(&mut rng);
}
/// Weighted { weight: 1, item: 'c' });
/// let wc = WeightedChoice::new(items.as_mut_slice());
/// let mut rng = rand::task_rng();
-/// for _ in range(0, 16) {
+/// for _ in range(0u, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(&mut rng));
/// }
}}
);
- t!(vec!(Weighted { weight: 1, item: 10}), [10]);
+ t!(vec!(Weighted { weight: 1, item: 10i}), [10]);
// skip some
- t!(vec!(Weighted { weight: 0, item: 20},
- Weighted { weight: 2, item: 21},
- Weighted { weight: 0, item: 22},
- Weighted { weight: 1, item: 23}),
+ t!(vec!(Weighted { weight: 0, item: 20i},
+ Weighted { weight: 2, item: 21i},
+ Weighted { weight: 0, item: 22i},
+ Weighted { weight: 1, item: 23i}),
[21,21, 23]);
// different weights
- t!(vec!(Weighted { weight: 4, item: 30},
- Weighted { weight: 3, item: 31}),
+ t!(vec!(Weighted { weight: 4, item: 30i},
+ Weighted { weight: 3, item: 31i}),
[30,30,30,30, 31,31,31]);
// check that we're binary searching
// correctly with some vectors of odd
// length.
- t!(vec!(Weighted { weight: 1, item: 40},
- Weighted { weight: 1, item: 41},
- Weighted { weight: 1, item: 42},
- Weighted { weight: 1, item: 43},
- Weighted { weight: 1, item: 44}),
+ t!(vec!(Weighted { weight: 1, item: 40i},
+ Weighted { weight: 1, item: 41i},
+ Weighted { weight: 1, item: 42i},
+ Weighted { weight: 1, item: 43i},
+ Weighted { weight: 1, item: 44i}),
[40, 41, 42, 43, 44]);
- t!(vec!(Weighted { weight: 1, item: 50},
- Weighted { weight: 1, item: 51},
- Weighted { weight: 1, item: 52},
- Weighted { weight: 1, item: 53},
- Weighted { weight: 1, item: 54},
- Weighted { weight: 1, item: 55},
- Weighted { weight: 1, item: 56}),
+ t!(vec!(Weighted { weight: 1, item: 50i},
+ Weighted { weight: 1, item: 51i},
+ Weighted { weight: 1, item: 52i},
+ Weighted { weight: 1, item: 53i},
+ Weighted { weight: 1, item: 54i},
+ Weighted { weight: 1, item: 55i},
+ Weighted { weight: 1, item: 56i}),
[50, 51, 52, 53, 54, 55, 56]);
}
}
#[test] #[should_fail]
fn test_weighted_choice_zero_weight() {
- WeightedChoice::new(&mut [Weighted { weight: 0, item: 0},
- Weighted { weight: 0, item: 1}]);
+ WeightedChoice::new(&mut [Weighted { weight: 0, item: 0i},
+ Weighted { weight: 0, item: 1i}]);
}
#[test] #[should_fail]
fn test_weighted_choice_weight_overflows() {
let x = (-1) as uint / 2; // x + x + 2 is the overflow
- WeightedChoice::new(&mut [Weighted { weight: x, item: 0 },
- Weighted { weight: 1, item: 1 },
- Weighted { weight: x, item: 2 },
- Weighted { weight: 1, item: 3 }]);
+ WeightedChoice::new(&mut [Weighted { weight: x, item: 0i },
+ Weighted { weight: 1, item: 1i },
+ Weighted { weight: x, item: 2i },
+ Weighted { weight: 1, item: 3i }]);
}
}
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}
/// let between = Range::new(10u, 10000u);
/// let mut rng = rand::task_rng();
/// let mut sum = 0;
-/// for _ in range(0, 1000) {
+/// for _ in range(0u, 1000) {
/// sum += between.ind_sample(&mut rng);
/// }
/// println!("{}", sum);
#[should_fail]
#[test]
fn test_range_bad_limits_equal() {
- Range::new(10, 10);
+ Range::new(10i, 10i);
}
#[should_fail]
#[test]
fn test_range_bad_limits_flipped() {
- Range::new(10, 5);
+ Range::new(10i, 5i);
}
#[test]
(Bounded::min_value(), Bounded::max_value())];
for &(low, high) in v.iter() {
let mut sampler: Range<$ty> = Range::new(low, high);
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let v = sampler.sample(&mut rng);
assert!(low <= v && v < high);
let v = sampler.ind_sample(&mut rng);
(-1e35, 1e35)];
for &(low, high) in v.iter() {
let mut sampler: Range<$ty> = Range::new(low, high);
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let v = sampler.sample(&mut rng);
assert!(low <= v && v < high);
let v = sampler.ind_sample(&mut rng);
use {Rng, SeedableRng, Rand};
static RAND_SIZE_LEN: u32 = 8;
-static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
+static RAND_SIZE: u32 = 1 << (RAND_SIZE_LEN as uint);
+static RAND_SIZE_UINT: uint = 1 << (RAND_SIZE_LEN as uint);
/// A random number generator that uses the ISAAC algorithm[1].
///
/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
pub struct IsaacRng {
cnt: u32,
- rsl: [u32, .. RAND_SIZE],
- mem: [u32, .. RAND_SIZE],
+ rsl: [u32, ..RAND_SIZE_UINT],
+ mem: [u32, ..RAND_SIZE_UINT],
a: u32,
b: u32,
c: u32
}
static EMPTY: IsaacRng = IsaacRng {
cnt: 0,
- rsl: [0, .. RAND_SIZE],
- mem: [0, .. RAND_SIZE],
+ rsl: [0, ..RAND_SIZE_UINT],
+ mem: [0, ..RAND_SIZE_UINT],
a: 0, b: 0, c: 0
};
}}
);
- for _ in range(0, 4) { mix!(); }
+ for _ in range(0u, 4) {
+ mix!();
+ }
if use_rsl {
macro_rules! memloop (
/// Refills the output buffer (`self.rsl`)
#[inline]
+ #[allow(unsigned_negate)]
fn isaac(&mut self) {
self.c += 1;
// abbreviations
let mut a = self.a;
let mut b = self.b + self.c;
- static MIDPOINT: uint = RAND_SIZE as uint / 2;
+ static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
macro_rules! ind (($x:expr) => {
- self.mem[(($x >> 2) & (RAND_SIZE - 1)) as uint]
+ self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))]
});
- macro_rules! rngstep(
+ macro_rules! rngstepp(
($j:expr, $shift:expr) => {{
let base = $j;
- let mix = if $shift < 0 {
- a >> -$shift as uint
- } else {
- a << $shift as uint
- };
+ let mix = a << $shift as uint;
let x = self.mem[base + mr_offset];
a = (a ^ mix) + self.mem[base + m2_offset];
let y = ind!(x) + a + b;
self.mem[base + mr_offset] = y;
- b = ind!(y >> RAND_SIZE_LEN) + x;
+ b = ind!(y >> RAND_SIZE_LEN as uint) + x;
+ self.rsl[base + mr_offset] = b;
+ }}
+ );
+ macro_rules! rngstepn(
+ ($j:expr, $shift:expr) => {{
+ let base = $j;
+ let mix = a >> $shift as uint;
+
+ let x = self.mem[base + mr_offset];
+ a = (a ^ mix) + self.mem[base + m2_offset];
+ let y = ind!(x) + a + b;
+ self.mem[base + mr_offset] = y;
+
+ b = ind!(y >> RAND_SIZE_LEN as uint) + x;
self.rsl[base + mr_offset] = b;
}}
);
let r = [(0, MIDPOINT), (MIDPOINT, 0)];
for &(mr_offset, m2_offset) in r.iter() {
for i in range_step(0u, MIDPOINT, 4) {
- rngstep!(i + 0, 13);
- rngstep!(i + 1, -6);
- rngstep!(i + 2, 2);
- rngstep!(i + 3, -16);
+ rngstepp!(i + 0, 13);
+ rngstepn!(i + 1, 6);
+ rngstepp!(i + 2, 2);
+ rngstepn!(i + 3, 16);
}
}
}}
);
- for _ in range(0, 4) { mix!(); }
+ for _ in range(0u, 4) {
+ mix!();
+ }
+
if use_rsl {
macro_rules! memloop (
($arr:expr) => {{
*self.mem.unsafe_ref(($x as uint >> 3) & (RAND_SIZE_64 - 1))
}
);
- macro_rules! rngstep(
+ macro_rules! rngstepp(
+ ($j:expr, $shift:expr) => {{
+ let base = base + $j;
+ let mix = a ^ (a << $shift as uint);
+ let mix = if $j == 0 {!mix} else {mix};
+
+ unsafe {
+ let x = *self.mem.unsafe_ref(base + mr_offset);
+ a = mix + *self.mem.unsafe_ref(base + m2_offset);
+ let y = ind!(x) + a + b;
+ self.mem.unsafe_set(base + mr_offset, y);
+
+ b = ind!(y >> RAND_SIZE_64_LEN) + x;
+ self.rsl.unsafe_set(base + mr_offset, b);
+ }
+ }}
+ );
+ macro_rules! rngstepn(
($j:expr, $shift:expr) => {{
let base = base + $j;
- let mix = a ^ (if $shift < 0 {
- a >> -$shift as uint
- } else {
- a << $shift as uint
- });
+ let mix = a ^ (a >> $shift as uint);
let mix = if $j == 0 {!mix} else {mix};
unsafe {
for &(mr_offset, m2_offset) in MP_VEC.iter() {
for base in range(0, MIDPOINT / 4).map(|i| i * 4) {
- rngstep!(0, 21);
- rngstep!(1, -5);
- rngstep!(2, 12);
- rngstep!(3, -33);
+ rngstepp!(0, 21);
+ rngstepn!(1, 5);
+ rngstepp!(2, 12);
+ rngstepn!(3, 33);
}
}
let seed = &[12345, 67890, 54321, 9876];
let mut rb: IsaacRng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
- for _ in range(0, 10000) { rb.next_u32(); }
+ for _ in range(0u, 10000) { rb.next_u32(); }
let v = Vec::from_fn(10, |_| rb.next_u32());
assert_eq!(v,
let seed = &[12345, 67890, 54321, 9876];
let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
- for _ in range(0, 10000) { rb.next_u64(); }
+ for _ in range(0u, 10000) { rb.next_u64(); }
let v = Vec::from_fn(10, |_| rb.next_u64());
assert_eq!(v,
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
- /// let m: f64 = rng.gen_range(-40.0, 1.3e5);
+ /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
/// ```
/// use std::rand::{task_rng, Rng};
///
- /// let choices = [1, 2, 4, 8, 16, 32];
+ /// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
- /// let mut y = [1,2,3];
+ /// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
// this is unlikely to catch an incorrect implementation that
// generates exactly 0 or 1, but it keeps it sane.
let mut rng = task_rng();
- for _ in range(0, 1_000) {
+ for _ in range(0u, 1_000) {
// strict inequalities
let Open01(f) = rng.gen::<Open01<f64>>();
assert!(0.0 < f && f < 1.0);
#[test]
fn rand_closed() {
let mut rng = task_rng();
- for _ in range(0, 1_000) {
+ for _ in range(0u, 1_000) {
// strict inequalities
let Closed01(f) = rng.gen::<Closed01<f64>>();
assert!(0.0 <= f && f <= 1.0);
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}
// The default library location, we need this to find the runtime.
// The location of crates will be determined as needed.
let lib_path = sess.target_filesearch().get_lib_path();
- cmd.arg("-L").arg(lib_path);
+ cmd.arg("-L").arg(&lib_path);
cmd.arg("-o").arg(out_filename).arg(obj_filename);
// Stack growth requires statically linking a __morestack function. Note
- // that this is listed *before* all other libraries, even though it may be
- // used to resolve symbols in other libraries. The only case that this
- // wouldn't be pulled in by the object file is if the object file had no
- // functions.
+ // that this is listed *before* all other libraries. Due to the usage of the
+ // --as-needed flag below, the standard library may only be useful for its
+ // rust_stack_exhausted function. In this case, we must ensure that the
+ // libmorestack.a file appears *before* the standard library (so we put it
+ // at the very front).
//
- // If we're building an executable, there must be at least one function (the
- // main function), and if we're building a dylib then we don't need it for
- // later libraries because they're all dylibs (not rlibs).
+ // Most of the time this is sufficient, except for when LLVM gets super
+ // clever. If, for example, we have a main function `fn main() {}`, LLVM
+ // will optimize out calls to `__morestack` entirely because the function
+ // doesn't need any stack at all!
//
- // I'm honestly not entirely sure why this needs to come first. Apparently
- // the --as-needed flag above sometimes strips out libstd from the command
- // line, but inserting this farther to the left makes the
- // "rust_stack_exhausted" symbol an outstanding undefined symbol, which
- // flags libstd as a required library (or whatever provides the symbol).
- cmd.arg("-lmorestack");
+ // To get around this snag, we specially tell the linker to always include
+ // all contents of this library. This way we're guaranteed that the linker
+ // will include the __morestack symbol 100% of the time, always resolving
+ // references to it even if the object above didn't use it.
+ match sess.targ_cfg.os {
+ abi::OsMacos | abi::OsiOS => {
+ let morestack = lib_path.join("libmorestack.a");
+
+ let mut v = "-Wl,-force_load,".as_bytes().to_owned();
+ v.push_all(morestack.as_vec());
+ cmd.arg(v.as_slice());
+ }
+ _ => {
+ cmd.args(["-Wl,--whole-archive", "-lmorestack",
+ "-Wl,--no-whole-archive"]);
+ }
+ }
// When linking a dynamic library, we put the metadata into a section of the
// executable. This metadata is in a separate object file from the main
let hash = state.result();
return Svh {
- hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
+ hash: range_step(0u, 64u, 4u).map(|i| hex(hash >> i)).collect()
};
fn hex(b: u64) -> char {
use back::link;
use back::target_strs;
use back::{arm, x86, x86_64, mips, mipsel};
-use middle::lint;
+use lint;
use syntax::abi;
use syntax::ast;
pub gc: bool,
pub optimize: OptLevel,
pub debuginfo: DebugInfoLevel,
- pub lint_opts: Vec<(lint::Lint, lint::Level)> ,
+ pub lint_opts: Vec<(String, lint::Level)>,
+ pub describe_lints: bool,
pub output_types: Vec<back::link::OutputType> ,
// This was mutable for rustpkg, which updates search paths based on the
// parsed code. It remains mutable in case its replacements wants to use
optimize: No,
debuginfo: NoDebugInfo,
lint_opts: Vec::new(),
+ describe_lints: false,
output_types: Vec::new(),
addl_lib_search_paths: RefCell::new(HashSet::new()),
maybe_sysroot: None,
optmulti("F", "forbid", "Set lint forbidden", "OPT"),
optmulti("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
optmulti("Z", "", "Set internal debugging options", "FLAG"),
- optflag("v", "version", "Print version info and exit"),
+ optflagopt("v", "version", "Print version info and exit", "verbose"),
optopt("", "color", "Configure coloring of output:
auto = colorize, if output goes to a tty (default);
always = always colorize output;
let no_trans = matches.opt_present("no-trans");
let no_analysis = matches.opt_present("no-analysis");
- let lint_levels = [lint::Allow, lint::Warn,
- lint::Deny, lint::Forbid];
- let mut lint_opts = Vec::new();
- let lint_dict = lint::get_lint_dict();
- for level in lint_levels.iter() {
- let level_name = lint::level_to_str(*level);
-
- let level_short = level_name.slice_chars(0, 1);
- let level_short = level_short.to_ascii().to_upper().into_str();
- let flags = matches.opt_strs(level_short.as_slice())
- .move_iter()
- .collect::<Vec<_>>()
- .append(matches.opt_strs(level_name).as_slice());
- for lint_name in flags.iter() {
- let lint_name = lint_name.replace("-", "_").into_string();
- match lint_dict.find_equiv(&lint_name) {
- None => {
- early_error(format!("unknown {} flag: {}",
- level_name,
- lint_name).as_slice());
- }
- Some(lint) => {
- lint_opts.push((lint.lint, *level));
- }
+ let mut lint_opts = vec!();
+ let mut describe_lints = false;
+
+ for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() {
+ for lint_name in matches.opt_strs(level.as_str()).move_iter() {
+ if lint_name.as_slice() == "help" {
+ describe_lints = true;
+ } else {
+ lint_opts.push((lint_name.replace("-", "_").into_string(), level));
}
}
}
optimize: opt_level,
debuginfo: debuginfo,
lint_opts: lint_opts,
+ describe_lints: describe_lints,
output_types: output_types,
addl_lib_search_paths: RefCell::new(addl_lib_search_paths),
maybe_sysroot: sysroot_opt,
use metadata::creader;
use middle::cfg;
use middle::cfg::graphviz::LabelledCFG;
-use middle::{trans, freevars, stability, kind, ty, typeck, lint, reachable};
+use middle::{trans, freevars, stability, kind, ty, typeck, reachable};
use middle::dependency_format;
use middle;
use plugin::load::Plugins;
use plugin::registry::Registry;
use plugin;
+use lint;
use util::common::time;
use util::ppaux;
use util::nodemap::{NodeSet};
&sess);
let id = link::find_crate_id(krate.attrs.as_slice(),
outputs.out_filestem.as_slice());
- let (expanded_crate, ast_map) =
- phase_2_configure_and_expand(&sess, krate, &id);
+ let (expanded_crate, ast_map)
+ = match phase_2_configure_and_expand(&sess, krate, &id) {
+ None => return,
+ Some(p) => p,
+ };
+
(outputs, expanded_crate, ast_map)
};
write_out_deps(&sess, input, &outputs, &expanded_crate);
/// syntax expansion, secondary `cfg` expansion, synthesis of a test
/// harness if one is to be provided and injection of a dependency on the
/// standard library and prelude.
+///
+/// Returns `None` if we're aborting after handling -W help.
pub fn phase_2_configure_and_expand(sess: &Session,
mut krate: ast::Crate,
crate_id: &CrateId)
- -> (ast::Crate, syntax::ast_map::Map) {
+ -> Option<(ast::Crate, syntax::ast_map::Map)> {
let time_passes = sess.time_passes();
*sess.crate_types.borrow_mut() = collect_crate_types(sess, krate.attrs.as_slice());
}
});
- let Registry { syntax_exts, .. } = registry;
+ let Registry { syntax_exts, lint_passes, .. } = registry;
+
+ {
+ let mut ls = sess.lint_store.borrow_mut();
+ for pass in lint_passes.move_iter() {
+ ls.register_pass(Some(sess), true, pass);
+ }
+ }
+
+ // Lint plugins are registered; now we can process command line flags.
+ if sess.opts.describe_lints {
+ super::describe_lints(&*sess.lint_store.borrow(), true);
+ return None;
+ }
+ sess.lint_store.borrow_mut().process_command_line(sess);
+
+ // Abort if there are errors from lint processing or a plugin registrar.
+ sess.abort_if_errors();
krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
|(krate, macros, syntax_exts)| {
krate.encode(&mut json).unwrap();
}
- (krate, map)
+ Some((krate, map))
}
pub struct CrateAnalysis {
});
time(time_passes, "lint checking", (), |_|
- lint::check_crate(&ty_cx, &exported_items, krate));
+ lint::check_crate(&ty_cx, krate, &exported_items));
CrateAnalysis {
exp_map2: exp_map2,
let (krate, ast_map, is_expanded) = match ppm {
PpmExpanded | PpmExpandedIdentified | PpmTyped | PpmFlowGraph(_) => {
- let (krate, ast_map) = phase_2_configure_and_expand(&sess,
- krate,
- &id);
+ let (krate, ast_map)
+ = match phase_2_configure_and_expand(&sess, krate, &id) {
+ None => return,
+ Some(p) => p,
+ };
(krate, Some(ast_map), true)
}
_ => (krate, None, false)
}
Some(ref n) if n.equiv(&("bin")) => Some(config::CrateTypeExecutable),
Some(_) => {
- session.add_lint(lint::UnknownCrateType,
+ session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPE,
ast::CRATE_NODE_ID,
a.span,
"invalid `crate_type` \
None
}
_ => {
- session.add_lint(lint::UnknownCrateType,
+ session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPE,
ast::CRATE_NODE_ID,
a.span,
"`crate_type` requires a \
use back::link;
use driver::driver::{Input, FileInput, StrInput};
use driver::session::{Session, build_session};
-use middle::lint;
+use lint::Lint;
+use lint;
use metadata;
use std::any::AnyRefExt;
-use std::cmp;
use std::io;
use std::os;
use std::str;
Some(matches) => matches,
None => return
};
+ let sopts = config::build_session_options(&matches);
let (input, input_file_path) = match matches.free.len() {
- 0u => early_error("no input filename given"),
+ 0u => {
+ if sopts.describe_lints {
+ let mut ls = lint::LintStore::new();
+ ls.register_builtin(None);
+ describe_lints(&ls, false);
+ return;
+ }
+ early_error("no input filename given");
+ }
1u => {
let ifile = matches.free.get(0).as_slice();
if ifile == "-" {
_ => early_error("multiple input filenames provided")
};
- let sopts = config::build_session_options(&matches);
let sess = build_session(sopts, input_file_path);
let cfg = config::build_configuration(&sess);
let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
driver::compile_input(sess, cfg, &input, &odir, &ofile);
}
-pub fn version(command: &str) {
- let vers = match option_env!("CFG_VERSION") {
- Some(vers) => vers,
- None => "unknown version"
+/// Prints version information and returns None on success or an error
+/// message on failure.
+pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
+ let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
+ None => false,
+ Some("verbose") => true,
+ Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
- println!("{} {}", command, vers);
- println!("host: {}", driver::host_triple());
+
+ println!("{} {}", binary, env!("CFG_VERSION"));
+ if verbose {
+ println!("binary: {}", binary);
+ println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
+ println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
+ println!("host: {}", driver::host_triple());
+ println!("release: {}", env!("CFG_RELEASE"));
+ }
+ None
}
fn usage() {
config::optgroups().as_slice()));
}
-fn describe_warnings() {
+fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
-");
- let lint_dict = lint::get_lint_dict();
- let mut lint_dict = lint_dict.move_iter()
- .map(|(k, v)| (v, k))
- .collect::<Vec<(lint::LintSpec, &'static str)> >();
- lint_dict.as_mut_slice().sort();
+");
- let mut max_key = 0;
- for &(_, name) in lint_dict.iter() {
- max_key = cmp::max(name.len(), max_key);
- }
- fn padded(max: uint, s: &str) -> String {
- format!("{}{}", " ".repeat(max - s.len()), s)
+ fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
+ let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
+ lints.sort_by(|x: &&Lint, y: &&Lint| {
+ match x.default_level.cmp(&y.default_level) {
+ // The sort doesn't case-fold but it's doubtful we care.
+ Equal => x.name.cmp(&y.name),
+ r => r,
+ }
+ });
+ lints
}
- println!("\nAvailable lint checks:\n");
- println!(" {} {:7.7s} {}",
- padded(max_key, "name"), "default", "meaning");
- println!(" {} {:7.7s} {}\n",
- padded(max_key, "----"), "-------", "-------");
- for (spec, name) in lint_dict.move_iter() {
- let name = name.replace("_", "-");
- println!(" {} {:7.7s} {}",
- padded(max_key, name.as_slice()),
- lint::level_to_str(spec.default),
- spec.desc);
+
+ let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
+ let plugin = sort_lints(plugin);
+ let builtin = sort_lints(builtin);
+
+ // FIXME (#7043): We should use the width in character cells rather than
+ // the number of codepoints.
+ let max_name_len = plugin.iter().chain(builtin.iter())
+ .map(|&s| s.name.char_len())
+ .max().unwrap_or(0);
+ let padded = |x: &str| {
+ " ".repeat(max_name_len - x.char_len()).append(x)
+ };
+
+ println!("Lint checks provided by rustc:\n");
+ println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
+ println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
+
+ let print_lints = |lints: Vec<&Lint>| {
+ for lint in lints.move_iter() {
+ let name = lint.name_lower().replace("_", "-");
+ println!(" {} {:7.7s} {}",
+ padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
+ }
+ println!("\n");
+ };
+
+ print_lints(builtin);
+
+ match (loaded_plugins, plugin.len()) {
+ (false, 0) => {
+ println!("Compiler plugins can provide additional lints. To see a listing of these, \
+ re-run `rustc -W help` with a crate filename.");
+ }
+ (false, _) => fail!("didn't load lint plugins but got them anyway!"),
+ (true, 0) => println!("This crate does not load any lint plugins."),
+ (true, _) => {
+ println!("Lint checks provided by plugins loaded by this crate:\n");
+ print_lints(plugin);
+ }
}
- println!("");
}
fn describe_debug_flags() {
return None;
}
- let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
- matches.opt_strs("warn").as_slice());
- if lint_flags.iter().any(|x| x.as_slice() == "help") {
- describe_warnings();
- return None;
- }
+ // Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| x.as_slice() == "help") {
return None;
}
- if matches.opt_present("v") || matches.opt_present("version") {
- version("rustc");
- return None;
+ if matches.opt_present("version") {
+ match version("rustc", &matches) {
+ Some(err) => early_error(err.as_slice()),
+ None => return None
+ }
}
Some(matches)
use front;
use metadata::cstore::CStore;
use metadata::filesearch;
-use middle::lint;
+use lint;
use util::nodemap::NodeMap;
use syntax::ast::NodeId;
// expected to be absolute. `None` means that there is no source file.
pub local_crate_source_file: Option<Path>,
pub working_dir: Path,
- pub lints: RefCell<NodeMap<Vec<(lint::Lint, codemap::Span, String)>>>,
+ pub lint_store: RefCell<lint::LintStore>,
+ pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
pub node_id: Cell<ast::NodeId>,
pub crate_types: RefCell<Vec<config::CrateType>>,
pub features: front::feature_gate::Features,
self.diagnostic().handler().unimpl(msg)
}
pub fn add_lint(&self,
- lint: lint::Lint,
+ lint: &'static lint::Lint,
id: ast::NodeId,
sp: Span,
msg: String) {
+ let lint_id = lint::LintId::of(lint);
let mut lints = self.lints.borrow_mut();
match lints.find_mut(&id) {
- Some(arr) => { arr.push((lint, sp, msg)); return; }
+ Some(arr) => { arr.push((lint_id, sp, msg)); return; }
None => {}
}
- lints.insert(id, vec!((lint, sp, msg)));
+ lints.insert(id, vec!((lint_id, sp, msg)));
}
pub fn next_node_id(&self) -> ast::NodeId {
self.reserve_node_ids(1)
}
);
- Session {
+ let sess = Session {
targ_cfg: target_cfg,
opts: sopts,
cstore: CStore::new(token::get_ident_interner()),
default_sysroot: default_sysroot,
local_crate_source_file: local_crate_source_file,
working_dir: os::getcwd(),
+ lint_store: RefCell::new(lint::LintStore::new()),
lints: RefCell::new(NodeMap::new()),
node_id: Cell::new(1),
crate_types: RefCell::new(Vec::new()),
features: front::feature_gate::Features::new(),
recursion_limit: Cell::new(64),
- }
+ };
+
+ sess.lint_store.borrow_mut().register_builtin(Some(&sess));
+ sess
}
// Seems out of place, but it uses session, so I'm putting it here
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.
-use middle::lint;
+use lint;
use syntax::abi::RustIntrinsic;
use syntax::ast::NodeId;
directive not necessary");
}
None => {
- sess.add_lint(lint::UnknownFeatures,
+ sess.add_lint(lint::builtin::UNKNOWN_FEATURES,
ast::CRATE_NODE_ID,
mi.span,
"unknown feature".to_string());
pub mod check_match;
pub mod check_const;
pub mod check_static;
- pub mod lint;
pub mod borrowck;
pub mod dataflow;
pub mod mem_categorization;
pub mod plugin;
+pub mod lint;
+
pub mod util {
pub mod common;
pub mod ppaux;
pub mod llvmdeps;
}
+// A private module so that macro-expanded idents like
+// `::rustc::lint::Lint` will also work in `rustc` itself.
+//
+// `libstd` uses the same trick.
+#[doc(hidden)]
+mod rustc {
+ pub use lint;
+}
+
pub fn main() {
let args = std::os::args().iter()
.map(|x| x.to_string())
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Lints built in to rustc.
+//!
+//! This is a sibling of `lint::context` in order to ensure that
+//! lints implemented here use the same public API as lint plugins.
+//!
+//! To add a new lint to rustc, declare it here using `declare_lint!()`.
+//! Then add code to emit the new lint in the appropriate circumstances.
+//! You can do that in an existing `LintPass` if it makes sense, or in
+//! a new `LintPass`, or using `Session::add_lint` elsewhere in the
+//! compiler. Only do the latter if the check can't be written cleanly
+//! as a `LintPass`.
+//!
+//! If you define a new `LintPass`, you will also need to add it to the
+//! `add_builtin!` or `add_builtin_with_new!` invocation in `context.rs`.
+//! Use the former for unit-like structs and the latter for structs with
+//! a `pub fn new()`.
+
+use metadata::csearch;
+use middle::def::*;
+use middle::trans::adt; // for `adt::is_ffi_safe`
+use middle::typeck::astconv::ast_ty_to_ty;
+use middle::typeck::infer;
+use middle::{typeck, ty, def, pat_util};
+use util::ppaux::{ty_to_str};
+use util::nodemap::NodeSet;
+use lint::{Context, LintPass, LintArray};
+
+use std::cmp;
+use std::collections::HashMap;
+use std::i16;
+use std::i32;
+use std::i64;
+use std::i8;
+use std::u16;
+use std::u32;
+use std::u64;
+use std::u8;
+use std::gc::Gc;
+use syntax::abi;
+use syntax::ast_map;
+use syntax::attr::AttrMetaMethods;
+use syntax::attr;
+use syntax::codemap::Span;
+use syntax::parse::token;
+use syntax::{ast, ast_util, visit};
+
+declare_lint!(WHILE_TRUE, Warn,
+ "suggest using `loop { }` instead of `while true { }`")
+
+pub struct WhileTrue;
+
+impl LintPass for WhileTrue {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(WHILE_TRUE)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ ast::ExprWhile(cond, _) => {
+ match cond.node {
+ ast::ExprLit(lit) => {
+ match lit.node {
+ ast::LitBool(true) => {
+ cx.span_lint(WHILE_TRUE, e.span,
+ "denote infinite loops with loop \
+ { ... }");
+ }
+ _ => {}
+ }
+ }
+ _ => ()
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(UNNECESSARY_TYPECAST, Allow,
+ "detects unnecessary type casts, that can be removed")
+
+pub struct UnusedCasts;
+
+impl LintPass for UnusedCasts {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNNECESSARY_TYPECAST)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ ast::ExprCast(expr, ty) => {
+ let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), &*ty);
+ if ty::get(ty::expr_ty(cx.tcx, &*expr)).sty == ty::get(t_t).sty {
+ cx.span_lint(UNNECESSARY_TYPECAST, ty.span, "unnecessary type cast");
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(UNSIGNED_NEGATE, Warn,
+ "using an unary minus operator on unsigned type")
+
+declare_lint!(TYPE_LIMITS, Warn,
+ "comparisons made useless by limits of the types involved")
+
+declare_lint!(TYPE_OVERFLOW, Warn,
+ "literal out of range for its type")
+
+pub struct TypeLimits {
+ /// Id of the last visited negated expression
+ negated_expr_id: ast::NodeId,
+}
+
+impl TypeLimits {
+ pub fn new() -> TypeLimits {
+ TypeLimits {
+ negated_expr_id: -1,
+ }
+ }
+}
+
+impl LintPass for TypeLimits {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNSIGNED_NEGATE, TYPE_LIMITS, TYPE_OVERFLOW)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ ast::ExprUnary(ast::UnNeg, expr) => {
+ match expr.node {
+ ast::ExprLit(lit) => {
+ match lit.node {
+ ast::LitUint(..) => {
+ cx.span_lint(UNSIGNED_NEGATE, e.span,
+ "negation of unsigned int literal may \
+ be unintentional");
+ },
+ _ => ()
+ }
+ },
+ _ => {
+ let t = ty::expr_ty(cx.tcx, &*expr);
+ match ty::get(t).sty {
+ ty::ty_uint(_) => {
+ cx.span_lint(UNSIGNED_NEGATE, e.span,
+ "negation of unsigned int variable may \
+ be unintentional");
+ },
+ _ => ()
+ }
+ }
+ };
+ // propagate negation, if the negation itself isn't negated
+ if self.negated_expr_id != e.id {
+ self.negated_expr_id = expr.id;
+ }
+ },
+ ast::ExprParen(expr) if self.negated_expr_id == e.id => {
+ self.negated_expr_id = expr.id;
+ },
+ ast::ExprBinary(binop, l, r) => {
+ if is_comparison(binop) && !check_limits(cx.tcx, binop, &*l, &*r) {
+ cx.span_lint(TYPE_LIMITS, e.span,
+ "comparison is useless due to type limits");
+ }
+ },
+ ast::ExprLit(lit) => {
+ match ty::get(ty::expr_ty(cx.tcx, e)).sty {
+ ty::ty_int(t) => {
+ let int_type = if t == ast::TyI {
+ cx.sess().targ_cfg.int_type
+ } else { t };
+ let (min, max) = int_ty_range(int_type);
+ let mut lit_val: i64 = match lit.node {
+ ast::LitInt(v, _) => v,
+ ast::LitUint(v, _) => v as i64,
+ ast::LitIntUnsuffixed(v) => v,
+ _ => fail!()
+ };
+ if self.negated_expr_id == e.id {
+ lit_val *= -1;
+ }
+ if lit_val < min || lit_val > max {
+ cx.span_lint(TYPE_OVERFLOW, e.span,
+ "literal out of range for its type");
+ }
+ },
+ ty::ty_uint(t) => {
+ let uint_type = if t == ast::TyU {
+ cx.sess().targ_cfg.uint_type
+ } else { t };
+ let (min, max) = uint_ty_range(uint_type);
+ let lit_val: u64 = match lit.node {
+ ast::LitByte(_v) => return, // _v is u8, within range by definition
+ ast::LitInt(v, _) => v as u64,
+ ast::LitUint(v, _) => v,
+ ast::LitIntUnsuffixed(v) => v as u64,
+ _ => fail!()
+ };
+ if lit_val < min || lit_val > max {
+ cx.span_lint(TYPE_OVERFLOW, e.span,
+ "literal out of range for its type");
+ }
+ },
+
+ _ => ()
+ };
+ },
+ _ => ()
+ };
+
+ fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
+ min: T, max: T) -> bool {
+ match binop {
+ ast::BiLt => v > min && v <= max,
+ ast::BiLe => v >= min && v < max,
+ ast::BiGt => v >= min && v < max,
+ ast::BiGe => v > min && v <= max,
+ ast::BiEq | ast::BiNe => v >= min && v <= max,
+ _ => fail!()
+ }
+ }
+
+ fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
+ match binop {
+ ast::BiLt => ast::BiGt,
+ ast::BiLe => ast::BiGe,
+ ast::BiGt => ast::BiLt,
+ ast::BiGe => ast::BiLe,
+ _ => binop
+ }
+ }
+
+ // for int & uint, be conservative with the warnings, so that the
+ // warnings are consistent between 32- and 64-bit platforms
+ fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
+ match int_ty {
+ ast::TyI => (i64::MIN, i64::MAX),
+ ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
+ ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
+ ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
+ ast::TyI64 => (i64::MIN, i64::MAX)
+ }
+ }
+
+ fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
+ match uint_ty {
+ ast::TyU => (u64::MIN, u64::MAX),
+ ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
+ ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
+ ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
+ ast::TyU64 => (u64::MIN, u64::MAX)
+ }
+ }
+
+ fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
+ l: &ast::Expr, r: &ast::Expr) -> bool {
+ let (lit, expr, swap) = match (&l.node, &r.node) {
+ (&ast::ExprLit(_), _) => (l, r, true),
+ (_, &ast::ExprLit(_)) => (r, l, false),
+ _ => return true
+ };
+ // Normalize the binop so that the literal is always on the RHS in
+ // the comparison
+ let norm_binop = if swap { rev_binop(binop) } else { binop };
+ match ty::get(ty::expr_ty(tcx, expr)).sty {
+ ty::ty_int(int_ty) => {
+ let (min, max) = int_ty_range(int_ty);
+ let lit_val: i64 = match lit.node {
+ ast::ExprLit(li) => match li.node {
+ ast::LitInt(v, _) => v,
+ ast::LitUint(v, _) => v as i64,
+ ast::LitIntUnsuffixed(v) => v,
+ _ => return true
+ },
+ _ => fail!()
+ };
+ is_valid(norm_binop, lit_val, min, max)
+ }
+ ty::ty_uint(uint_ty) => {
+ let (min, max): (u64, u64) = uint_ty_range(uint_ty);
+ let lit_val: u64 = match lit.node {
+ ast::ExprLit(li) => match li.node {
+ ast::LitInt(v, _) => v as u64,
+ ast::LitUint(v, _) => v,
+ ast::LitIntUnsuffixed(v) => v as u64,
+ _ => return true
+ },
+ _ => fail!()
+ };
+ is_valid(norm_binop, lit_val, min, max)
+ }
+ _ => true
+ }
+ }
+
+ fn is_comparison(binop: ast::BinOp) -> bool {
+ match binop {
+ ast::BiEq | ast::BiLt | ast::BiLe |
+ ast::BiNe | ast::BiGe | ast::BiGt => true,
+ _ => false
+ }
+ }
+ }
+}
+
+declare_lint!(CTYPES, Warn,
+ "proper use of libc types in foreign modules")
+
+pub struct CTypes;
+
+impl LintPass for CTypes {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(CTYPES)
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ fn check_ty(cx: &Context, ty: &ast::Ty) {
+ match ty.node {
+ ast::TyPath(_, _, id) => {
+ match cx.tcx.def_map.borrow().get_copy(&id) {
+ def::DefPrimTy(ast::TyInt(ast::TyI)) => {
+ cx.span_lint(CTYPES, ty.span,
+ "found rust type `int` in foreign module, while \
+ libc::c_int or libc::c_long should be used");
+ }
+ def::DefPrimTy(ast::TyUint(ast::TyU)) => {
+ cx.span_lint(CTYPES, ty.span,
+ "found rust type `uint` in foreign module, while \
+ libc::c_uint or libc::c_ulong should be used");
+ }
+ def::DefTy(def_id) => {
+ if !adt::is_ffi_safe(cx.tcx, def_id) {
+ cx.span_lint(CTYPES, ty.span,
+ "found enum type without foreign-function-safe \
+ representation annotation in foreign module");
+ // hmm... this message could be more helpful
+ }
+ }
+ _ => ()
+ }
+ }
+ ast::TyPtr(ref mt) => { check_ty(cx, &*mt.ty) }
+ _ => {}
+ }
+ }
+
+ fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
+ for input in decl.inputs.iter() {
+ check_ty(cx, &*input.ty);
+ }
+ check_ty(cx, &*decl.output)
+ }
+
+ match it.node {
+ ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
+ for ni in nmod.items.iter() {
+ match ni.node {
+ ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, &*decl),
+ ast::ForeignItemStatic(t, _) => check_ty(cx, &*t)
+ }
+ }
+ }
+ _ => {/* nothing to do */ }
+ }
+ }
+}
+
+declare_lint!(MANAGED_HEAP_MEMORY, Allow,
+ "use of managed (@ type) heap memory")
+
+declare_lint!(OWNED_HEAP_MEMORY, Allow,
+ "use of owned (Box type) heap memory")
+
+declare_lint!(HEAP_MEMORY, Allow,
+ "use of any (Box type or @ type) heap memory")
+
+pub struct HeapMemory;
+
+impl HeapMemory {
+ fn check_heap_type(&self, cx: &Context, span: Span, ty: ty::t) {
+ let mut n_box = 0;
+ let mut n_uniq = 0;
+ ty::fold_ty(cx.tcx, ty, |t| {
+ match ty::get(t).sty {
+ ty::ty_box(_) => {
+ n_box += 1;
+ }
+ ty::ty_uniq(_) |
+ ty::ty_closure(box ty::ClosureTy {
+ store: ty::UniqTraitStore,
+ ..
+ }) => {
+ n_uniq += 1;
+ }
+
+ _ => ()
+ };
+ t
+ });
+
+ if n_uniq > 0 {
+ let s = ty_to_str(cx.tcx, ty);
+ let m = format!("type uses owned (Box type) pointers: {}", s);
+ cx.span_lint(OWNED_HEAP_MEMORY, span, m.as_slice());
+ cx.span_lint(HEAP_MEMORY, span, m.as_slice());
+ }
+
+ if n_box > 0 {
+ let s = ty_to_str(cx.tcx, ty);
+ let m = format!("type uses managed (@ type) pointers: {}", s);
+ cx.span_lint(MANAGED_HEAP_MEMORY, span, m.as_slice());
+ cx.span_lint(HEAP_MEMORY, span, m.as_slice());
+ }
+ }
+}
+
+impl LintPass for HeapMemory {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(MANAGED_HEAP_MEMORY, OWNED_HEAP_MEMORY, HEAP_MEMORY)
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ match it.node {
+ ast::ItemFn(..) |
+ ast::ItemTy(..) |
+ ast::ItemEnum(..) |
+ ast::ItemStruct(..) =>
+ self.check_heap_type(cx, it.span,
+ ty::node_id_to_type(cx.tcx, it.id)),
+ _ => ()
+ }
+
+ // If it's a struct, we also have to check the fields' types
+ match it.node {
+ ast::ItemStruct(struct_def, _) => {
+ for struct_field in struct_def.fields.iter() {
+ self.check_heap_type(cx, struct_field.span,
+ ty::node_id_to_type(cx.tcx, struct_field.node.id));
+ }
+ }
+ _ => ()
+ }
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ let ty = ty::expr_ty(cx.tcx, e);
+ self.check_heap_type(cx, e.span, ty);
+ }
+}
+
+declare_lint!(RAW_POINTER_DERIVING, Warn,
+ "uses of #[deriving] with raw pointers are rarely correct")
+
+struct RawPtrDerivingVisitor<'a> {
+ cx: &'a Context<'a>
+}
+
+impl<'a> visit::Visitor<()> for RawPtrDerivingVisitor<'a> {
+ fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
+ static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
+ match ty.node {
+ ast::TyPtr(..) => self.cx.span_lint(RAW_POINTER_DERIVING, ty.span, MSG),
+ _ => {}
+ }
+ visit::walk_ty(self, ty, ());
+ }
+ // explicit override to a no-op to reduce code bloat
+ fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
+ fn visit_block(&mut self, _: &ast::Block, _: ()) {}
+}
+
+pub struct RawPointerDeriving {
+ checked_raw_pointers: NodeSet,
+}
+
+impl RawPointerDeriving {
+ pub fn new() -> RawPointerDeriving {
+ RawPointerDeriving {
+ checked_raw_pointers: NodeSet::new(),
+ }
+ }
+}
+
+impl LintPass for RawPointerDeriving {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(RAW_POINTER_DERIVING)
+ }
+
+ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
+ if !attr::contains_name(item.attrs.as_slice(), "automatically_derived") {
+ return
+ }
+ let did = match item.node {
+ ast::ItemImpl(..) => {
+ match ty::get(ty::node_id_to_type(cx.tcx, item.id)).sty {
+ ty::ty_enum(did, _) => did,
+ ty::ty_struct(did, _) => did,
+ _ => return,
+ }
+ }
+ _ => return,
+ };
+ if !ast_util::is_local(did) { return }
+ let item = match cx.tcx.map.find(did.node) {
+ Some(ast_map::NodeItem(item)) => item,
+ _ => return,
+ };
+ if !self.checked_raw_pointers.insert(item.id) { return }
+ match item.node {
+ ast::ItemStruct(..) | ast::ItemEnum(..) => {
+ let mut visitor = RawPtrDerivingVisitor { cx: cx };
+ visit::walk_item(&mut visitor, &*item, ());
+ }
+ _ => {}
+ }
+ }
+}
+
+declare_lint!(UNUSED_ATTRIBUTE, Warn,
+ "detects attributes that were not used by the compiler")
+
+pub struct UnusedAttribute;
+
+impl LintPass for UnusedAttribute {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNUSED_ATTRIBUTE)
+ }
+
+ fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
+ static ATTRIBUTE_WHITELIST: &'static [&'static str] = &'static [
+ // FIXME: #14408 whitelist docs since rustdoc looks at them
+ "doc",
+
+ // FIXME: #14406 these are processed in trans, which happens after the
+ // lint pass
+ "cold",
+ "inline",
+ "link",
+ "link_name",
+ "link_section",
+ "no_builtins",
+ "no_mangle",
+ "no_split_stack",
+ "packed",
+ "static_assert",
+ "thread_local",
+
+ // not used anywhere (!?) but apparently we want to keep them around
+ "comment",
+ "desc",
+ "license",
+
+ // FIXME: #14407 these are only looked at on-demand so we can't
+ // guarantee they'll have already been checked
+ "deprecated",
+ "experimental",
+ "frozen",
+ "locked",
+ "must_use",
+ "stable",
+ "unstable",
+ ];
+
+ static CRATE_ATTRS: &'static [&'static str] = &'static [
+ "crate_type",
+ "feature",
+ "no_start",
+ "no_main",
+ "no_std",
+ "crate_id",
+ "desc",
+ "comment",
+ "license",
+ "copyright",
+ "no_builtins",
+ ];
+
+ for &name in ATTRIBUTE_WHITELIST.iter() {
+ if attr.check_name(name) {
+ break;
+ }
+ }
+
+ if !attr::is_used(attr) {
+ cx.span_lint(UNUSED_ATTRIBUTE, attr.span, "unused attribute");
+ if CRATE_ATTRS.contains(&attr.name().get()) {
+ let msg = match attr.node.style {
+ ast::AttrOuter => "crate-level attribute should be an inner \
+ attribute: add an exclamation mark: #![foo]",
+ ast::AttrInner => "crate-level attribute should be in the \
+ root module",
+ };
+ cx.span_lint(UNUSED_ATTRIBUTE, attr.span, msg);
+ }
+ }
+ }
+}
+
+declare_lint!(PATH_STATEMENT, Warn,
+ "path statements with no effect")
+
+pub struct PathStatement;
+
+impl LintPass for PathStatement {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(PATH_STATEMENT)
+ }
+
+ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
+ match s.node {
+ ast::StmtSemi(expr, _) => {
+ match expr.node {
+ ast::ExprPath(_) => cx.span_lint(PATH_STATEMENT, s.span,
+ "path statement with no effect"),
+ _ => ()
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(UNUSED_MUST_USE, Warn,
+ "unused result of a type flagged as #[must_use]")
+
+declare_lint!(UNUSED_RESULT, Allow,
+ "unused result of an expression in a statement")
+
+pub struct UnusedResult;
+
+impl LintPass for UnusedResult {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNUSED_MUST_USE, UNUSED_RESULT)
+ }
+
+ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
+ let expr = match s.node {
+ ast::StmtSemi(expr, _) => expr,
+ _ => return
+ };
+ let t = ty::expr_ty(cx.tcx, &*expr);
+ match ty::get(t).sty {
+ ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
+ _ => {}
+ }
+ match expr.node {
+ ast::ExprRet(..) => return,
+ _ => {}
+ }
+
+ let t = ty::expr_ty(cx.tcx, &*expr);
+ let mut warned = false;
+ match ty::get(t).sty {
+ ty::ty_struct(did, _) |
+ ty::ty_enum(did, _) => {
+ if ast_util::is_local(did) {
+ match cx.tcx.map.get(did.node) {
+ ast_map::NodeItem(it) => {
+ if attr::contains_name(it.attrs.as_slice(),
+ "must_use") {
+ cx.span_lint(UNUSED_MUST_USE, s.span,
+ "unused result which must be used");
+ warned = true;
+ }
+ }
+ _ => {}
+ }
+ } else {
+ csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| {
+ if attr::contains_name(attrs.as_slice(), "must_use") {
+ cx.span_lint(UNUSED_MUST_USE, s.span,
+ "unused result which must be used");
+ warned = true;
+ }
+ });
+ }
+ }
+ _ => {}
+ }
+ if !warned {
+ cx.span_lint(UNUSED_RESULT, s.span, "unused result");
+ }
+ }
+}
+
+declare_lint!(NON_CAMEL_CASE_TYPES, Warn,
+ "types, variants and traits should have camel case names")
+
+pub struct NonCamelCaseTypes;
+
+impl LintPass for NonCamelCaseTypes {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(NON_CAMEL_CASE_TYPES)
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ fn is_camel_case(ident: ast::Ident) -> bool {
+ let ident = token::get_ident(ident);
+ assert!(!ident.get().is_empty());
+ let ident = ident.get().trim_chars('_');
+
+ // start with a non-lowercase letter rather than non-uppercase
+ // ones (some scripts don't have a concept of upper/lowercase)
+ !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
+ }
+
+ fn to_camel_case(s: &str) -> String {
+ s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
+ if i == 0 { c.to_uppercase() }
+ else { c }
+ )).collect()
+ }
+
+ fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
+ let s = token::get_ident(ident);
+
+ if !is_camel_case(ident) {
+ cx.span_lint(NON_CAMEL_CASE_TYPES, span,
+ format!("{} `{}` should have a camel case name such as `{}`",
+ sort, s, to_camel_case(s.get())).as_slice());
+ }
+ }
+
+ match it.node {
+ ast::ItemTy(..) | ast::ItemStruct(..) => {
+ check_case(cx, "type", it.ident, it.span)
+ }
+ ast::ItemTrait(..) => {
+ check_case(cx, "trait", it.ident, it.span)
+ }
+ ast::ItemEnum(ref enum_definition, _) => {
+ check_case(cx, "type", it.ident, it.span);
+ for variant in enum_definition.variants.iter() {
+ check_case(cx, "variant", variant.node.name, variant.span);
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+#[deriving(PartialEq)]
+enum MethodContext {
+ TraitDefaultImpl,
+ TraitImpl,
+ PlainImpl
+}
+
+fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
+ let did = ast::DefId {
+ krate: ast::LOCAL_CRATE,
+ node: m.id
+ };
+
+ match cx.tcx.methods.borrow().find_copy(&did) {
+ None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
+ Some(md) => {
+ match md.container {
+ ty::TraitContainer(..) => TraitDefaultImpl,
+ ty::ImplContainer(cid) => {
+ match ty::impl_trait_ref(cx.tcx, cid) {
+ Some(..) => TraitImpl,
+ None => PlainImpl
+ }
+ }
+ }
+ }
+ }
+}
+
+declare_lint!(NON_SNAKE_CASE_FUNCTIONS, Warn,
+ "methods and functions should have snake case names")
+
+pub struct NonSnakeCaseFunctions;
+
+impl NonSnakeCaseFunctions {
+ fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
+ fn is_snake_case(ident: ast::Ident) -> bool {
+ let ident = token::get_ident(ident);
+ assert!(!ident.get().is_empty());
+ let ident = ident.get().trim_chars('_');
+
+ let mut allow_underscore = true;
+ ident.chars().all(|c| {
+ allow_underscore = match c {
+ c if c.is_lowercase() || c.is_digit() => true,
+ '_' if allow_underscore => false,
+ _ => return false,
+ };
+ true
+ })
+ }
+
+ fn to_snake_case(str: &str) -> String {
+ let mut words = vec![];
+ for s in str.split('_') {
+ let mut buf = String::new();
+ if s.is_empty() { continue; }
+ for ch in s.chars() {
+ if !buf.is_empty() && ch.is_uppercase() {
+ words.push(buf);
+ buf = String::new();
+ }
+ buf.push_char(ch.to_lowercase());
+ }
+ words.push(buf);
+ }
+ words.connect("_")
+ }
+
+ let s = token::get_ident(ident);
+
+ if !is_snake_case(ident) {
+ cx.span_lint(NON_SNAKE_CASE_FUNCTIONS, span,
+ format!("{} `{}` should have a snake case name such as `{}`",
+ sort, s, to_snake_case(s.get())).as_slice());
+ }
+ }
+}
+
+impl LintPass for NonSnakeCaseFunctions {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(NON_SNAKE_CASE_FUNCTIONS)
+ }
+
+ fn check_fn(&mut self, cx: &Context,
+ fk: &visit::FnKind, _: &ast::FnDecl,
+ _: &ast::Block, span: Span, _: ast::NodeId) {
+ match *fk {
+ visit::FkMethod(ident, _, m) => match method_context(cx, m) {
+ PlainImpl
+ => self.check_snake_case(cx, "method", ident, span),
+ TraitDefaultImpl
+ => self.check_snake_case(cx, "trait method", ident, span),
+ _ => (),
+ },
+ visit::FkItemFn(ident, _, _, _)
+ => self.check_snake_case(cx, "function", ident, span),
+ _ => (),
+ }
+ }
+
+ fn check_ty_method(&mut self, cx: &Context, t: &ast::TypeMethod) {
+ self.check_snake_case(cx, "trait method", t.ident, t.span);
+ }
+}
+
+declare_lint!(NON_UPPERCASE_STATICS, Allow,
+ "static constants should have uppercase identifiers")
+
+pub struct NonUppercaseStatics;
+
+impl LintPass for NonUppercaseStatics {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(NON_UPPERCASE_STATICS)
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ match it.node {
+ // only check static constants
+ ast::ItemStatic(_, ast::MutImmutable, _) => {
+ let s = token::get_ident(it.ident);
+ // check for lowercase letters rather than non-uppercase
+ // ones (some scripts don't have a concept of
+ // upper/lowercase)
+ if s.get().chars().any(|c| c.is_lowercase()) {
+ cx.span_lint(NON_UPPERCASE_STATICS, it.span,
+ format!("static constant `{}` should have an uppercase name \
+ such as `{}`",
+ s.get(), s.get().chars().map(|c| c.to_uppercase())
+ .collect::<String>().as_slice()).as_slice());
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+declare_lint!(NON_UPPERCASE_PATTERN_STATICS, Warn,
+ "static constants in match patterns should be all caps")
+
+pub struct NonUppercasePatternStatics;
+
+impl LintPass for NonUppercasePatternStatics {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(NON_UPPERCASE_PATTERN_STATICS)
+ }
+
+ fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
+ // Lint for constants that look like binding identifiers (#7526)
+ match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
+ (&ast::PatIdent(_, ref path, _), Some(&def::DefStatic(_, false))) => {
+ // last identifier alone is right choice for this lint.
+ let ident = path.segments.last().unwrap().identifier;
+ let s = token::get_ident(ident);
+ if s.get().chars().any(|c| c.is_lowercase()) {
+ cx.span_lint(NON_UPPERCASE_PATTERN_STATICS, path.span,
+ format!("static constant in pattern `{}` should have an uppercase \
+ name such as `{}`",
+ s.get(), s.get().chars().map(|c| c.to_uppercase())
+ .collect::<String>().as_slice()).as_slice());
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+declare_lint!(UPPERCASE_VARIABLES, Warn,
+ "variable and structure field names should start with a lowercase character")
+
+pub struct UppercaseVariables;
+
+impl LintPass for UppercaseVariables {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UPPERCASE_VARIABLES)
+ }
+
+ fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
+ match &p.node {
+ &ast::PatIdent(_, ref path, _) => {
+ match cx.tcx.def_map.borrow().find(&p.id) {
+ Some(&def::DefLocal(_, _)) | Some(&def::DefBinding(_, _)) |
+ Some(&def::DefArg(_, _)) => {
+ // last identifier alone is right choice for this lint.
+ let ident = path.segments.last().unwrap().identifier;
+ let s = token::get_ident(ident);
+ if s.get().len() > 0 && s.get().char_at(0).is_uppercase() {
+ cx.span_lint(UPPERCASE_VARIABLES, path.span,
+ "variable names should start with \
+ a lowercase character");
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
+ _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
+ for sf in s.fields.iter() {
+ match sf.node {
+ ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
+ let s = token::get_ident(ident);
+ if s.get().char_at(0).is_uppercase() {
+ cx.span_lint(UPPERCASE_VARIABLES, sf.span,
+ "structure field names should start with \
+ a lowercase character");
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+}
+
+declare_lint!(UNNECESSARY_PARENS, Warn,
+ "`if`, `match`, `while` and `return` do not need parentheses")
+
+pub struct UnnecessaryParens;
+
+impl UnnecessaryParens {
+ fn check_unnecessary_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str) {
+ match value.node {
+ ast::ExprParen(_) => {
+ cx.span_lint(UNNECESSARY_PARENS, value.span,
+ format!("unnecessary parentheses around {}", msg).as_slice())
+ }
+ _ => {}
+ }
+ }
+}
+
+impl LintPass for UnnecessaryParens {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNNECESSARY_PARENS)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ let (value, msg) = match e.node {
+ ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
+ ast::ExprWhile(cond, _) => (cond, "`while` condition"),
+ ast::ExprMatch(head, _) => (head, "`match` head expression"),
+ ast::ExprRet(Some(value)) => (value, "`return` value"),
+ ast::ExprAssign(_, value) => (value, "assigned value"),
+ ast::ExprAssignOp(_, _, value) => (value, "assigned value"),
+ _ => return
+ };
+ self.check_unnecessary_parens_core(cx, &*value, msg);
+ }
+
+ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
+ let (value, msg) = match s.node {
+ ast::StmtDecl(decl, _) => match decl.node {
+ ast::DeclLocal(local) => match local.init {
+ Some(value) => (value, "assigned value"),
+ None => return
+ },
+ _ => return
+ },
+ _ => return
+ };
+ self.check_unnecessary_parens_core(cx, &*value, msg);
+ }
+}
+
+declare_lint!(UNUSED_UNSAFE, Warn,
+ "unnecessary use of an `unsafe` block")
+
+pub struct UnusedUnsafe;
+
+impl LintPass for UnusedUnsafe {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNUSED_UNSAFE)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ // Don't warn about generated blocks, that'll just pollute the output.
+ ast::ExprBlock(ref blk) => {
+ if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
+ !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
+ cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(UNSAFE_BLOCK, Allow,
+ "usage of an `unsafe` block")
+
+pub struct UnsafeBlock;
+
+impl LintPass for UnsafeBlock {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNSAFE_BLOCK)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ // Don't warn about generated blocks, that'll just pollute the output.
+ ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
+ cx.span_lint(UNSAFE_BLOCK, blk.span, "usage of an `unsafe` block");
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(UNUSED_MUT, Warn,
+ "detect mut variables which don't need to be mutable")
+
+pub struct UnusedMut;
+
+impl UnusedMut {
+ fn check_unused_mut_pat(&self, cx: &Context, pats: &[Gc<ast::Pat>]) {
+ // collect all mutable pattern and group their NodeIDs by their Identifier to
+ // avoid false warnings in match arms with multiple patterns
+ let mut mutables = HashMap::new();
+ for &p in pats.iter() {
+ pat_util::pat_bindings(&cx.tcx.def_map, &*p, |mode, id, _, path| {
+ match mode {
+ ast::BindByValue(ast::MutMutable) => {
+ if path.segments.len() != 1 {
+ cx.sess().span_bug(p.span,
+ "mutable binding that doesn't consist \
+ of exactly one segment");
+ }
+ let ident = path.segments.get(0).identifier;
+ if !token::get_ident(ident).get().starts_with("_") {
+ mutables.insert_or_update_with(ident.name as uint,
+ vec!(id), |_, old| { old.push(id); });
+ }
+ }
+ _ => {
+ }
+ }
+ });
+ }
+
+ let used_mutables = cx.tcx.used_mut_nodes.borrow();
+ for (_, v) in mutables.iter() {
+ if !v.iter().any(|e| used_mutables.contains(e)) {
+ cx.span_lint(UNUSED_MUT, cx.tcx.map.span(*v.get(0)),
+ "variable does not need to be mutable");
+ }
+ }
+ }
+}
+
+impl LintPass for UnusedMut {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNUSED_MUT)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ match e.node {
+ ast::ExprMatch(_, ref arms) => {
+ for a in arms.iter() {
+ self.check_unused_mut_pat(cx, a.pats.as_slice())
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
+ match s.node {
+ ast::StmtDecl(d, _) => {
+ match d.node {
+ ast::DeclLocal(l) => {
+ self.check_unused_mut_pat(cx, &[l.pat]);
+ },
+ _ => {}
+ }
+ },
+ _ => {}
+ }
+ }
+
+ fn check_fn(&mut self, cx: &Context,
+ _: &visit::FnKind, decl: &ast::FnDecl,
+ _: &ast::Block, _: Span, _: ast::NodeId) {
+ for a in decl.inputs.iter() {
+ self.check_unused_mut_pat(cx, &[a.pat]);
+ }
+ }
+}
+
+enum Allocation {
+ VectorAllocation,
+ BoxAllocation
+}
+
+declare_lint!(UNNECESSARY_ALLOCATION, Warn,
+ "detects unnecessary allocations that can be eliminated")
+
+pub struct UnnecessaryAllocation;
+
+impl LintPass for UnnecessaryAllocation {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(UNNECESSARY_ALLOCATION)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ // Warn if string and vector literals with sigils, or boxing expressions,
+ // are immediately borrowed.
+ let allocation = match e.node {
+ ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
+ match e2.node {
+ ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
+ VectorAllocation
+ }
+ ast::ExprVec(..) => VectorAllocation,
+ _ => return
+ }
+ }
+ ast::ExprUnary(ast::UnUniq, _) |
+ ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
+
+ _ => return
+ };
+
+ match cx.tcx.adjustments.borrow().find(&e.id) {
+ Some(adjustment) => {
+ match *adjustment {
+ ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
+ match (allocation, autoref) {
+ (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
+ cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
+ "unnecessary allocation, the sigil can be removed");
+ }
+ (BoxAllocation,
+ Some(ty::AutoPtr(_, ast::MutImmutable))) => {
+ cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
+ "unnecessary allocation, use & instead");
+ }
+ (BoxAllocation,
+ Some(ty::AutoPtr(_, ast::MutMutable))) => {
+ cx.span_lint(UNNECESSARY_ALLOCATION, e.span,
+ "unnecessary allocation, use &mut instead");
+ }
+ _ => ()
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => ()
+ }
+ }
+}
+
+declare_lint!(MISSING_DOC, Allow,
+ "detects missing documentation for public members")
+
+pub struct MissingDoc {
+ /// Stack of IDs of struct definitions.
+ struct_def_stack: Vec<ast::NodeId>,
+
+ /// Stack of whether #[doc(hidden)] is set
+ /// at each level which has lint attributes.
+ doc_hidden_stack: Vec<bool>,
+}
+
+impl MissingDoc {
+ pub fn new() -> MissingDoc {
+ MissingDoc {
+ struct_def_stack: vec!(),
+ doc_hidden_stack: vec!(false),
+ }
+ }
+
+ fn doc_hidden(&self) -> bool {
+ *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
+ }
+
+ fn check_missing_doc_attrs(&self,
+ cx: &Context,
+ id: Option<ast::NodeId>,
+ attrs: &[ast::Attribute],
+ sp: Span,
+ desc: &'static str) {
+ // If we're building a test harness, then warning about
+ // documentation is probably not really relevant right now.
+ if cx.sess().opts.test { return }
+
+ // `#[doc(hidden)]` disables missing_doc check.
+ if self.doc_hidden() { return }
+
+ // Only check publicly-visible items, using the result from the privacy pass.
+ // It's an option so the crate root can also use this function (it doesn't
+ // have a NodeId).
+ match id {
+ Some(ref id) if !cx.exported_items.contains(id) => return,
+ _ => ()
+ }
+
+ let has_doc = attrs.iter().any(|a| {
+ match a.node.value.node {
+ ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
+ _ => false
+ }
+ });
+ if !has_doc {
+ cx.span_lint(MISSING_DOC, sp,
+ format!("missing documentation for {}", desc).as_slice());
+ }
+ }
+}
+
+impl LintPass for MissingDoc {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(MISSING_DOC)
+ }
+
+ fn enter_lint_attrs(&mut self, _: &Context, attrs: &[ast::Attribute]) {
+ let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
+ attr.check_name("doc") && match attr.meta_item_list() {
+ None => false,
+ Some(l) => attr::contains_name(l.as_slice(), "hidden"),
+ }
+ });
+ self.doc_hidden_stack.push(doc_hidden);
+ }
+
+ fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
+ self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
+ }
+
+ fn check_struct_def(&mut self, _: &Context,
+ _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+ self.struct_def_stack.push(id);
+ }
+
+ fn check_struct_def_post(&mut self, _: &Context,
+ _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+ let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
+ assert!(popped == id);
+ }
+
+ fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
+ self.check_missing_doc_attrs(cx, None, krate.attrs.as_slice(),
+ krate.span, "crate");
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ let desc = match it.node {
+ ast::ItemFn(..) => "a function",
+ ast::ItemMod(..) => "a module",
+ ast::ItemEnum(..) => "an enum",
+ ast::ItemStruct(..) => "a struct",
+ ast::ItemTrait(..) => "a trait",
+ _ => return
+ };
+ self.check_missing_doc_attrs(cx, Some(it.id), it.attrs.as_slice(),
+ it.span, desc);
+ }
+
+ fn check_fn(&mut self, cx: &Context,
+ fk: &visit::FnKind, _: &ast::FnDecl,
+ _: &ast::Block, _: Span, _: ast::NodeId) {
+ match *fk {
+ visit::FkMethod(_, _, m) => {
+ // If the method is an impl for a trait, don't doc.
+ if method_context(cx, m) == TraitImpl { return; }
+
+ // Otherwise, doc according to privacy. This will also check
+ // doc for default methods defined on traits.
+ self.check_missing_doc_attrs(cx, Some(m.id), m.attrs.as_slice(),
+ m.span, "a method");
+ }
+ _ => {}
+ }
+ }
+
+ fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
+ self.check_missing_doc_attrs(cx, Some(tm.id), tm.attrs.as_slice(),
+ tm.span, "a type method");
+ }
+
+ fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
+ match sf.node.kind {
+ ast::NamedField(_, vis) if vis == ast::Public => {
+ let cur_struct_def = *self.struct_def_stack.last()
+ .expect("empty struct_def_stack");
+ self.check_missing_doc_attrs(cx, Some(cur_struct_def),
+ sf.node.attrs.as_slice(), sf.span,
+ "a struct field")
+ }
+ _ => {}
+ }
+ }
+
+ fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
+ self.check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs.as_slice(),
+ v.span, "a variant");
+ }
+}
+
+declare_lint!(DEPRECATED, Warn,
+ "detects use of #[deprecated] items")
+
+// FIXME #6875: Change to Warn after std library stabilization is complete
+declare_lint!(EXPERIMENTAL, Allow,
+ "detects use of #[experimental] items")
+
+declare_lint!(UNSTABLE, Allow,
+ "detects use of #[unstable] items (incl. items with no stability attribute)")
+
+/// Checks for use of items with `#[deprecated]`, `#[experimental]` and
+/// `#[unstable]` attributes, or no stability attribute.
+pub struct Stability;
+
+impl LintPass for Stability {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE)
+ }
+
+ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
+ let id = match e.node {
+ ast::ExprPath(..) | ast::ExprStruct(..) => {
+ match cx.tcx.def_map.borrow().find(&e.id) {
+ Some(&def) => def.def_id(),
+ None => return
+ }
+ }
+ ast::ExprMethodCall(..) => {
+ let method_call = typeck::MethodCall::expr(e.id);
+ match cx.tcx.method_map.borrow().find(&method_call) {
+ Some(method) => {
+ match method.origin {
+ typeck::MethodStatic(def_id) => {
+ // If this implements a trait method, get def_id
+ // of the method inside trait definition.
+ // Otherwise, use the current def_id (which refers
+ // to the method inside impl).
+ ty::trait_method_of_method(cx.tcx, def_id).unwrap_or(def_id)
+ }
+ typeck::MethodParam(typeck::MethodParam {
+ trait_id: trait_id,
+ method_num: index,
+ ..
+ })
+ | typeck::MethodObject(typeck::MethodObject {
+ trait_id: trait_id,
+ method_num: index,
+ ..
+ }) => ty::trait_method(cx.tcx, trait_id, index).def_id
+ }
+ }
+ None => return
+ }
+ }
+ _ => return
+ };
+
+ // stability attributes are promises made across crates; do not
+ // check anything for crate-local usage.
+ if ast_util::is_local(id) { return }
+
+ let stability = cx.tcx.stability.borrow_mut().lookup(&cx.tcx.sess.cstore, id);
+
+ let (lint, label) = match stability {
+ // no stability attributes == Unstable
+ None => (UNSTABLE, "unmarked"),
+ Some(attr::Stability { level: attr::Unstable, .. }) =>
+ (UNSTABLE, "unstable"),
+ Some(attr::Stability { level: attr::Experimental, .. }) =>
+ (EXPERIMENTAL, "experimental"),
+ Some(attr::Stability { level: attr::Deprecated, .. }) =>
+ (DEPRECATED, "deprecated"),
+ _ => return
+ };
+
+ let msg = match stability {
+ Some(attr::Stability { text: Some(ref s), .. }) => {
+ format!("use of {} item: {}", label, *s)
+ }
+ _ => format!("use of {} item", label)
+ };
+
+ cx.span_lint(lint, e.span, msg.as_slice());
+ }
+}
+
+declare_lint!(pub UNUSED_IMPORTS, Warn,
+ "imports that are never used")
+
+declare_lint!(pub UNNECESSARY_QUALIFICATION, Allow,
+ "detects unnecessarily qualified names")
+
+declare_lint!(pub UNRECOGNIZED_LINT, Warn,
+ "unrecognized lint attribute")
+
+declare_lint!(pub UNUSED_VARIABLE, Warn,
+ "detect variables which are not used in any way")
+
+declare_lint!(pub DEAD_ASSIGNMENT, Warn,
+ "detect assignments that will never be read")
+
+declare_lint!(pub DEAD_CODE, Warn,
+ "detect piece of code that will never be used")
+
+declare_lint!(pub VISIBLE_PRIVATE_TYPES, Warn,
+ "detect use of private types in exported type signatures")
+
+declare_lint!(pub UNREACHABLE_CODE, Warn,
+ "detects unreachable code")
+
+declare_lint!(pub WARNINGS, Warn,
+ "mass-change the level for lints which produce warnings")
+
+declare_lint!(pub UNKNOWN_FEATURES, Deny,
+ "unknown features found in crate-level #[feature] directives")
+
+declare_lint!(pub UNKNOWN_CRATE_TYPE, Deny,
+ "unknown crate type found in #[crate_type] directive")
+
+declare_lint!(pub VARIANT_SIZE_DIFFERENCE, Allow,
+ "detects enums with widely varying variant sizes")
+
+/// Does nothing as a lint pass, but registers some `Lint`s
+/// which are used by other parts of the compiler.
+pub struct HardwiredLints;
+
+impl LintPass for HardwiredLints {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(
+ UNUSED_IMPORTS,
+ UNNECESSARY_QUALIFICATION,
+ UNRECOGNIZED_LINT,
+ UNUSED_VARIABLE,
+ DEAD_ASSIGNMENT,
+ DEAD_CODE,
+ VISIBLE_PRIVATE_TYPES,
+ UNREACHABLE_CODE,
+ WARNINGS,
+ UNKNOWN_FEATURES,
+ UNKNOWN_CRATE_TYPE,
+ VARIANT_SIZE_DIFFERENCE
+ )
+ }
+}
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Implementation of lint checking.
+//!
+//! The lint checking is mostly consolidated into one pass which runs just
+//! before translation to LLVM bytecode. Throughout compilation, lint warnings
+//! can be added via the `add_lint` method on the Session structure. This
+//! requires a span and an id of the node that the lint is being added to. The
+//! lint isn't actually emitted at that time because it is unknown what the
+//! actual lint level at that location is.
+//!
+//! To actually emit lint warnings/errors, a separate pass is used just before
+//! translation. A context keeps track of the current state of all lint levels.
+//! Upon entering a node of the ast which can modify the lint settings, the
+//! previous lint state is pushed onto a stack and the ast is then recursed
+//! upon. As the ast is traversed, this keeps track of the current lint level
+//! for all lint attributes.
+
+use middle::privacy::ExportedItems;
+use middle::ty;
+use middle::typeck::astconv::AstConv;
+use middle::typeck::infer;
+use driver::session::Session;
+use driver::early_error;
+use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject};
+use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
+use lint::builtin;
+
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::cell::RefCell;
+use std::tuple::Tuple2;
+use std::mem;
+use syntax::ast_util::IdVisitingOperation;
+use syntax::attr::AttrMetaMethods;
+use syntax::attr;
+use syntax::codemap::Span;
+use syntax::visit::{Visitor, FnKind};
+use syntax::parse::token::InternedString;
+use syntax::{ast, ast_util, visit};
+
+/// Information about the registered lints.
+///
+/// This is basically the subset of `Context` that we can
+/// build early in the compile pipeline.
+pub struct LintStore {
+ /// Registered lints. The bool is true if the lint was
+ /// added by a plugin.
+ lints: Vec<(&'static Lint, bool)>,
+
+ /// Trait objects for each lint pass.
+ /// This is only `None` while iterating over the objects. See the definition
+ /// of run_lints.
+ passes: Option<Vec<LintPassObject>>,
+
+ /// Lints indexed by name.
+ by_name: HashMap<String, LintId>,
+
+ /// Current levels of each lint, and where they were set.
+ levels: HashMap<LintId, LevelSource>,
+}
+
+impl LintStore {
+ fn get_level_source(&self, lint: LintId) -> LevelSource {
+ match self.levels.find(&lint) {
+ Some(&s) => s,
+ None => (Allow, Default),
+ }
+ }
+
+ fn set_level(&mut self, lint: LintId, lvlsrc: LevelSource) {
+ if lvlsrc.val0() == Allow {
+ self.levels.remove(&lint);
+ } else {
+ self.levels.insert(lint, lvlsrc);
+ }
+ }
+
+ pub fn new() -> LintStore {
+ LintStore {
+ lints: vec!(),
+ passes: Some(vec!()),
+ by_name: HashMap::new(),
+ levels: HashMap::new(),
+ }
+ }
+
+ pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
+ self.lints.as_slice()
+ }
+
+ pub fn register_pass(&mut self, sess: Option<&Session>,
+ from_plugin: bool, pass: LintPassObject) {
+ for &lint in pass.get_lints().iter() {
+ self.lints.push((lint, from_plugin));
+
+ let id = LintId::of(lint);
+ if !self.by_name.insert(lint.name_lower(), id) {
+ let msg = format!("duplicate specification of lint {}", lint.name_lower());
+ match (sess, from_plugin) {
+ // We load builtin lints first, so a duplicate is a compiler bug.
+ // Use early_error when handling -W help with no crate.
+ (None, _) => early_error(msg.as_slice()),
+ (Some(sess), false) => sess.bug(msg.as_slice()),
+
+ // A duplicate name from a plugin is a user error.
+ (Some(sess), true) => sess.err(msg.as_slice()),
+ }
+ }
+
+ if lint.default_level != Allow {
+ self.levels.insert(id, (lint.default_level, Default));
+ }
+ }
+ self.passes.get_mut_ref().push(pass);
+ }
+
+ pub fn register_builtin(&mut self, sess: Option<&Session>) {
+ macro_rules! add_builtin ( ( $sess:ident, $($name:ident),*, ) => (
+ {$(
+ self.register_pass($sess, false, box builtin::$name as LintPassObject);
+ )*}
+ ))
+
+ macro_rules! add_builtin_with_new ( ( $sess:ident, $($name:ident),*, ) => (
+ {$(
+ self.register_pass($sess, false, box builtin::$name::new() as LintPassObject);
+ )*}
+ ))
+
+ add_builtin!(sess,
+ HardwiredLints,
+ WhileTrue,
+ UnusedCasts,
+ CTypes,
+ HeapMemory,
+ UnusedAttribute,
+ PathStatement,
+ UnusedResult,
+ NonCamelCaseTypes,
+ NonSnakeCaseFunctions,
+ NonUppercaseStatics,
+ NonUppercasePatternStatics,
+ UppercaseVariables,
+ UnnecessaryParens,
+ UnusedUnsafe,
+ UnsafeBlock,
+ UnusedMut,
+ UnnecessaryAllocation,
+ Stability,
+ )
+
+ add_builtin_with_new!(sess,
+ TypeLimits,
+ RawPointerDeriving,
+ MissingDoc,
+ )
+
+ // We have one lint pass defined in this module.
+ self.register_pass(sess, false, box GatherNodeLevels as LintPassObject);
+ }
+
+ pub fn process_command_line(&mut self, sess: &Session) {
+ for &(ref lint_name, level) in sess.opts.lint_opts.iter() {
+ match self.by_name.find_equiv(&lint_name.as_slice()) {
+ Some(&lint_id) => self.set_level(lint_id, (level, CommandLine)),
+ None => sess.err(format!("unknown {} flag: {}",
+ level.as_str(), lint_name).as_slice()),
+ }
+ }
+ }
+}
+
+/// Context for lint checking.
+pub struct Context<'a> {
+ /// Type context we're checking in.
+ pub tcx: &'a ty::ctxt,
+
+ /// The crate being checked.
+ pub krate: &'a ast::Crate,
+
+ /// Items exported from the crate being checked.
+ pub exported_items: &'a ExportedItems,
+
+ /// The store of registered lints.
+ lints: LintStore,
+
+ /// When recursing into an attributed node of the ast which modifies lint
+ /// levels, this stack keeps track of the previous lint levels of whatever
+ /// was modified.
+ level_stack: Vec<(LintId, LevelSource)>,
+
+ /// Level of lints for certain NodeIds, stored here because the body of
+ /// the lint needs to run in trans.
+ node_levels: RefCell<HashMap<(ast::NodeId, LintId), LevelSource>>,
+}
+
+/// Convenience macro for calling a `LintPass` method on every pass in the context.
+macro_rules! run_lints ( ($cx:expr, $f:ident, $($args:expr),*) => ({
+ // Move the vector of passes out of `$cx` so that we can
+ // iterate over it mutably while passing `$cx` to the methods.
+ let mut passes = $cx.lints.passes.take_unwrap();
+ for obj in passes.mut_iter() {
+ obj.$f($cx, $($args),*);
+ }
+ $cx.lints.passes = Some(passes);
+}))
+
+/// Parse the lint attributes into a vector, with `Err`s for malformed lint
+/// attributes. Writing this as an iterator is an enormous mess.
+pub fn gather_attrs(attrs: &[ast::Attribute])
+ -> Vec<Result<(InternedString, Level, Span), Span>> {
+ let mut out = vec!();
+ for attr in attrs.iter() {
+ let level = match Level::from_str(attr.name().get()) {
+ None => continue,
+ Some(lvl) => lvl,
+ };
+
+ attr::mark_used(attr);
+
+ let meta = attr.node.value;
+ let metas = match meta.node {
+ ast::MetaList(_, ref metas) => metas,
+ _ => {
+ out.push(Err(meta.span));
+ continue;
+ }
+ };
+
+ for meta in metas.iter() {
+ out.push(match meta.node {
+ ast::MetaWord(ref lint_name) => Ok((lint_name.clone(), level, meta.span)),
+ _ => Err(meta.span),
+ });
+ }
+ }
+ out
+}
+
+/// Emit a lint as a warning or an error (or not at all)
+/// according to `level`.
+///
+/// This lives outside of `Context` so it can be used by checks
+/// in trans that run after the main lint pass is finished. Most
+/// lints elsewhere in the compiler should call
+/// `Session::add_lint()` instead.
+pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
+ lvlsrc: LevelSource, span: Option<Span>, msg: &str) {
+ let (mut level, source) = lvlsrc;
+ if level == Allow { return }
+
+ let name = lint.name_lower();
+ let mut note = None;
+ let msg = match source {
+ Default => {
+ format!("{}, #[{}({})] on by default", msg,
+ level.as_str(), name)
+ },
+ CommandLine => {
+ format!("{} [-{} {}]", msg,
+ match level {
+ Warn => 'W', Deny => 'D', Forbid => 'F',
+ Allow => fail!()
+ }, name.replace("_", "-"))
+ },
+ Node(src) => {
+ note = Some(src);
+ msg.to_string()
+ }
+ };
+
+ // For purposes of printing, we can treat forbid as deny.
+ if level == Forbid { level = Deny; }
+
+ match (level, span) {
+ (Warn, Some(sp)) => sess.span_warn(sp, msg.as_slice()),
+ (Warn, None) => sess.warn(msg.as_slice()),
+ (Deny, Some(sp)) => sess.span_err(sp, msg.as_slice()),
+ (Deny, None) => sess.err(msg.as_slice()),
+ _ => sess.bug("impossible level in raw_emit_lint"),
+ }
+
+ for span in note.move_iter() {
+ sess.span_note(span, "lint level defined here");
+ }
+}
+
+impl<'a> Context<'a> {
+ fn new(tcx: &'a ty::ctxt,
+ krate: &'a ast::Crate,
+ exported_items: &'a ExportedItems) -> Context<'a> {
+ // We want to own the lint store, so move it out of the session.
+ let lint_store = mem::replace(&mut *tcx.sess.lint_store.borrow_mut(),
+ LintStore::new());
+
+ Context {
+ tcx: tcx,
+ krate: krate,
+ exported_items: exported_items,
+ lints: lint_store,
+ level_stack: vec!(),
+ node_levels: RefCell::new(HashMap::new()),
+ }
+ }
+
+ /// Get the overall compiler `Session` object.
+ pub fn sess(&'a self) -> &'a Session {
+ &self.tcx.sess
+ }
+
+ fn lookup_and_emit(&self, lint: &'static Lint, span: Option<Span>, msg: &str) {
+ let (level, src) = match self.lints.levels.find(&LintId::of(lint)) {
+ None => return,
+ Some(&(Warn, src)) => {
+ let lint_id = LintId::of(builtin::WARNINGS);
+ (self.lints.get_level_source(lint_id).val0(), src)
+ }
+ Some(&pair) => pair,
+ };
+
+ raw_emit_lint(&self.tcx.sess, lint, (level, src), span, msg);
+ }
+
+ /// Emit a lint at the appropriate level, with no associated span.
+ pub fn lint(&self, lint: &'static Lint, msg: &str) {
+ self.lookup_and_emit(lint, None, msg);
+ }
+
+ /// Emit a lint at the appropriate level, for a particular span.
+ pub fn span_lint(&self, lint: &'static Lint, span: Span, msg: &str) {
+ self.lookup_and_emit(lint, Some(span), msg);
+ }
+
+ /**
+ * Merge the lints specified by any lint attributes into the
+ * current lint context, call the provided function, then reset the
+ * lints in effect to their previous state.
+ */
+ fn with_lint_attrs(&mut self,
+ attrs: &[ast::Attribute],
+ f: |&mut Context|) {
+ // Parse all of the lint attributes, and then add them all to the
+ // current dictionary of lint information. Along the way, keep a history
+ // of what we changed so we can roll everything back after invoking the
+ // specified closure
+ let mut pushed = 0u;
+
+ for result in gather_attrs(attrs).move_iter() {
+ let (lint_id, level, span) = match result {
+ Err(span) => {
+ self.tcx.sess.span_err(span, "malformed lint attribute");
+ continue;
+ }
+ Ok((lint_name, level, span)) => {
+ match self.lints.by_name.find_equiv(&lint_name.get()) {
+ Some(&lint_id) => (lint_id, level, span),
+ None => {
+ self.span_lint(builtin::UNRECOGNIZED_LINT, span,
+ format!("unknown `{}` attribute: `{}`",
+ level.as_str(), lint_name).as_slice());
+ continue;
+ }
+ }
+ }
+ };
+
+ let now = self.lints.get_level_source(lint_id).val0();
+ if now == Forbid && level != Forbid {
+ let lint_name = lint_id.as_str();
+ self.tcx.sess.span_err(span,
+ format!("{}({}) overruled by outer forbid({})",
+ level.as_str(), lint_name, lint_name).as_slice());
+ } else if now != level {
+ let src = self.lints.get_level_source(lint_id).val1();
+ self.level_stack.push((lint_id, (now, src)));
+ pushed += 1;
+ self.lints.set_level(lint_id, (level, Node(span)));
+ }
+ }
+
+ run_lints!(self, enter_lint_attrs, attrs);
+ f(self);
+ run_lints!(self, exit_lint_attrs, attrs);
+
+ // rollback
+ for _ in range(0, pushed) {
+ let (lint, lvlsrc) = self.level_stack.pop().unwrap();
+ self.lints.set_level(lint, lvlsrc);
+ }
+ }
+
+ fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
+ let mut v = ast_util::IdVisitor {
+ operation: self,
+ pass_through_items: false,
+ visited_outermost: false,
+ };
+ f(&mut v);
+ }
+}
+
+impl<'a> AstConv for Context<'a>{
+ fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
+
+ fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype {
+ ty::lookup_item_type(self.tcx, id)
+ }
+
+ fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
+ ty::lookup_trait_def(self.tcx, id)
+ }
+
+ fn ty_infer(&self, _span: Span) -> ty::t {
+ infer::new_infer_ctxt(self.tcx).next_ty_var()
+ }
+}
+
+impl<'a> Visitor<()> for Context<'a> {
+ fn visit_item(&mut self, it: &ast::Item, _: ()) {
+ self.with_lint_attrs(it.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_item, it);
+ cx.visit_ids(|v| v.visit_item(it, ()));
+ visit::walk_item(cx, it, ());
+ })
+ }
+
+ fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
+ self.with_lint_attrs(it.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_foreign_item, it);
+ visit::walk_foreign_item(cx, it, ());
+ })
+ }
+
+ fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
+ self.with_lint_attrs(i.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_view_item, i);
+ cx.visit_ids(|v| v.visit_view_item(i, ()));
+ visit::walk_view_item(cx, i, ());
+ })
+ }
+
+ fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
+ run_lints!(self, check_pat, p);
+ visit::walk_pat(self, p, ());
+ }
+
+ fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
+ run_lints!(self, check_expr, e);
+ visit::walk_expr(self, e, ());
+ }
+
+ fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
+ run_lints!(self, check_stmt, s);
+ visit::walk_stmt(self, s, ());
+ }
+
+ fn visit_fn(&mut self, fk: &FnKind, decl: &ast::FnDecl,
+ body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
+ match *fk {
+ visit::FkMethod(_, _, m) => {
+ self.with_lint_attrs(m.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_fn, fk, decl, body, span, id);
+ cx.visit_ids(|v| {
+ v.visit_fn(fk, decl, body, span, id, ());
+ });
+ visit::walk_fn(cx, fk, decl, body, span, ());
+ })
+ },
+ _ => {
+ run_lints!(self, check_fn, fk, decl, body, span, id);
+ visit::walk_fn(self, fk, decl, body, span, ());
+ }
+ }
+ }
+
+ fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
+ self.with_lint_attrs(t.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_ty_method, t);
+ visit::walk_ty_method(cx, t, ());
+ })
+ }
+
+ fn visit_struct_def(&mut self,
+ s: &ast::StructDef,
+ ident: ast::Ident,
+ g: &ast::Generics,
+ id: ast::NodeId,
+ _: ()) {
+ run_lints!(self, check_struct_def, s, ident, g, id);
+ visit::walk_struct_def(self, s, ());
+ run_lints!(self, check_struct_def_post, s, ident, g, id);
+ }
+
+ fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
+ self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_struct_field, s);
+ visit::walk_struct_field(cx, s, ());
+ })
+ }
+
+ fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
+ self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
+ run_lints!(cx, check_variant, v, g);
+ visit::walk_variant(cx, v, g, ());
+ })
+ }
+
+ // FIXME(#10894) should continue recursing
+ fn visit_ty(&mut self, t: &ast::Ty, _: ()) {
+ run_lints!(self, check_ty, t);
+ }
+
+ fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) {
+ run_lints!(self, check_ident, sp, id);
+ }
+
+ fn visit_mod(&mut self, m: &ast::Mod, s: Span, n: ast::NodeId, _: ()) {
+ run_lints!(self, check_mod, m, s, n);
+ visit::walk_mod(self, m, ());
+ }
+
+ fn visit_local(&mut self, l: &ast::Local, _: ()) {
+ run_lints!(self, check_local, l);
+ visit::walk_local(self, l, ());
+ }
+
+ fn visit_block(&mut self, b: &ast::Block, _: ()) {
+ run_lints!(self, check_block, b);
+ visit::walk_block(self, b, ());
+ }
+
+ fn visit_arm(&mut self, a: &ast::Arm, _: ()) {
+ run_lints!(self, check_arm, a);
+ visit::walk_arm(self, a, ());
+ }
+
+ fn visit_decl(&mut self, d: &ast::Decl, _: ()) {
+ run_lints!(self, check_decl, d);
+ visit::walk_decl(self, d, ());
+ }
+
+ fn visit_expr_post(&mut self, e: &ast::Expr, _: ()) {
+ run_lints!(self, check_expr_post, e);
+ }
+
+ fn visit_generics(&mut self, g: &ast::Generics, _: ()) {
+ run_lints!(self, check_generics, g);
+ visit::walk_generics(self, g, ());
+ }
+
+ fn visit_trait_method(&mut self, m: &ast::TraitMethod, _: ()) {
+ run_lints!(self, check_trait_method, m);
+ visit::walk_trait_method(self, m, ());
+ }
+
+ fn visit_opt_lifetime_ref(&mut self, sp: Span, lt: &Option<ast::Lifetime>, _: ()) {
+ run_lints!(self, check_opt_lifetime_ref, sp, lt);
+ }
+
+ fn visit_lifetime_ref(&mut self, lt: &ast::Lifetime, _: ()) {
+ run_lints!(self, check_lifetime_ref, lt);
+ }
+
+ fn visit_lifetime_decl(&mut self, lt: &ast::Lifetime, _: ()) {
+ run_lints!(self, check_lifetime_decl, lt);
+ }
+
+ fn visit_explicit_self(&mut self, es: &ast::ExplicitSelf, _: ()) {
+ run_lints!(self, check_explicit_self, es);
+ visit::walk_explicit_self(self, es, ());
+ }
+
+ fn visit_mac(&mut self, mac: &ast::Mac, _: ()) {
+ run_lints!(self, check_mac, mac);
+ visit::walk_mac(self, mac, ());
+ }
+
+ fn visit_path(&mut self, p: &ast::Path, id: ast::NodeId, _: ()) {
+ run_lints!(self, check_path, p, id);
+ visit::walk_path(self, p, ());
+ }
+
+ fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
+ run_lints!(self, check_attribute, attr);
+ }
+}
+
+// Output any lints that were previously added to the session.
+impl<'a> IdVisitingOperation for Context<'a> {
+ fn visit_id(&self, id: ast::NodeId) {
+ match self.tcx.sess.lints.borrow_mut().pop(&id) {
+ None => {}
+ Some(lints) => {
+ for (lint_id, span, msg) in lints.move_iter() {
+ self.span_lint(lint_id.lint, span, msg.as_slice())
+ }
+ }
+ }
+ }
+}
+
+// This lint pass is defined here because it touches parts of the `Context`
+// that we don't want to expose. It records the lint level at certain AST
+// nodes, so that the variant size difference check in trans can call
+// `raw_emit_lint`.
+
+struct GatherNodeLevels;
+
+impl LintPass for GatherNodeLevels {
+ fn get_lints(&self) -> LintArray {
+ lint_array!()
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ match it.node {
+ ast::ItemEnum(..) => {
+ let lint_id = LintId::of(builtin::VARIANT_SIZE_DIFFERENCE);
+ match cx.lints.get_level_source(lint_id) {
+ lvlsrc @ (lvl, _) if lvl != Allow => {
+ cx.node_levels.borrow_mut()
+ .insert((it.id, lint_id), lvlsrc);
+ },
+ _ => { }
+ }
+ },
+ _ => { }
+ }
+ }
+}
+
+/// Perform lint checking on a crate.
+///
+/// Consumes the `lint_store` field of the `Session`.
+pub fn check_crate(tcx: &ty::ctxt,
+ krate: &ast::Crate,
+ exported_items: &ExportedItems) {
+ let mut cx = Context::new(tcx, krate, exported_items);
+
+ // Visit the whole crate.
+ cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
+ cx.visit_id(ast::CRATE_NODE_ID);
+ cx.visit_ids(|v| {
+ v.visited_outermost = true;
+ visit::walk_crate(v, krate, ());
+ });
+
+ // since the root module isn't visited as an item (because it isn't an
+ // item), warn for it here.
+ run_lints!(cx, check_crate, krate);
+
+ visit::walk_crate(cx, krate, ());
+ });
+
+ // If we missed any lints added to the session, then there's a bug somewhere
+ // in the iteration code.
+ for (id, v) in tcx.sess.lints.borrow().iter() {
+ for &(lint, span, ref msg) in v.iter() {
+ tcx.sess.span_bug(span,
+ format!("unprocessed lint {} at {}: {}",
+ lint.as_str(), tcx.map.node_to_str(*id), *msg).as_slice())
+ }
+ }
+
+ tcx.sess.abort_if_errors();
+ *tcx.node_lint_levels.borrow_mut() = cx.node_levels.unwrap();
+}
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Lints, aka compiler warnings.
+//!
+//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
+//! want to enforce, but might reasonably want to permit as well, on a
+//! module-by-module basis. They contrast with static constraints enforced by
+//! other phases of the compiler, which are generally required to hold in order
+//! to compile the program at all.
+//!
+//! Most lints can be written as `LintPass` instances. These run just before
+//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
+//! within `builtin.rs`, which has further comments on how to add such a lint.
+//! rustc can also load user-defined lint plugins via the plugin mechanism.
+//!
+//! Some of rustc's lints are defined elsewhere in the compiler and work by
+//! calling `add_lint()` on the overall `Session` object. This works when
+//! it happens before the main lint pass, which emits the lints stored by
+//! `add_lint()`. To emit lints after the main lint pass (from trans, for
+//! example) requires more effort. See `emit_lint` and `GatherNodeLevels`
+//! in `context.rs`.
+
+#![macro_escape]
+
+use std::hash;
+use std::ascii::StrAsciiExt;
+use syntax::codemap::Span;
+use syntax::visit::FnKind;
+use syntax::ast;
+
+pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
+
+/// Specification of a single lint.
+pub struct Lint {
+ /// A string identifier for the lint.
+ ///
+ /// This identifies the lint in attributes and in command-line arguments.
+ /// In those contexts it is always lowercase, but this field is compared
+ /// in a way which is case-insensitive for ASCII characters. This allows
+ /// `declare_lint!()` invocations to follow the convention of upper-case
+ /// statics without repeating the name.
+ ///
+ /// The name is written with underscores, e.g. "unused_imports".
+ /// On the command line, underscores become dashes.
+ pub name: &'static str,
+
+ /// Default level for the lint.
+ pub default_level: Level,
+
+ /// Description of the lint or the issue it detects.
+ ///
+ /// e.g. "imports that are never used"
+ pub desc: &'static str,
+}
+
+impl Lint {
+ /// Get the lint's name, with ASCII letters converted to lowercase.
+ pub fn name_lower(&self) -> String {
+ self.name.to_ascii_lower()
+ }
+}
+
+/// Build a `Lint` initializer.
+#[macro_export]
+macro_rules! lint_initializer (
+ ($name:ident, $level:ident, $desc:expr) => (
+ ::rustc::lint::Lint {
+ name: stringify!($name),
+ default_level: ::rustc::lint::$level,
+ desc: $desc,
+ }
+ )
+)
+
+/// Declare a static item of type `&'static Lint`.
+#[macro_export]
+macro_rules! declare_lint (
+ // FIXME(#14660): deduplicate
+ (pub $name:ident, $level:ident, $desc:expr) => (
+ pub static $name: &'static ::rustc::lint::Lint
+ = &lint_initializer!($name, $level, $desc);
+ );
+ ($name:ident, $level:ident, $desc:expr) => (
+ static $name: &'static ::rustc::lint::Lint
+ = &lint_initializer!($name, $level, $desc);
+ );
+)
+
+/// Declare a static `LintArray` and return it as an expression.
+#[macro_export]
+macro_rules! lint_array ( ($( $lint:expr ),*) => (
+ {
+ static array: LintArray = &[ $( $lint ),* ];
+ array
+ }
+))
+
+pub type LintArray = &'static [&'static Lint];
+
+/// Trait for types providing lint checks.
+///
+/// Each `check` method checks a single syntax node, and should not
+/// invoke methods recursively (unlike `Visitor`). By default they
+/// do nothing.
+//
+// FIXME: eliminate the duplication with `Visitor`. But this also
+// contains a few lint-specific methods with no equivalent in `Visitor`.
+pub trait LintPass {
+ /// Get descriptions of the lints this `LintPass` object can emit.
+ ///
+ /// NB: there is no enforcement that the object only emits lints it registered.
+ /// And some `rustc` internal `LintPass`es register lints to be emitted by other
+ /// parts of the compiler. If you want enforced access restrictions for your
+ /// `Lint`, make it a private `static` item in its own module.
+ fn get_lints(&self) -> LintArray;
+
+ fn check_crate(&mut self, _: &Context, _: &ast::Crate) { }
+ fn check_ident(&mut self, _: &Context, _: Span, _: ast::Ident) { }
+ fn check_mod(&mut self, _: &Context, _: &ast::Mod, _: Span, _: ast::NodeId) { }
+ fn check_view_item(&mut self, _: &Context, _: &ast::ViewItem) { }
+ fn check_foreign_item(&mut self, _: &Context, _: &ast::ForeignItem) { }
+ fn check_item(&mut self, _: &Context, _: &ast::Item) { }
+ fn check_local(&mut self, _: &Context, _: &ast::Local) { }
+ fn check_block(&mut self, _: &Context, _: &ast::Block) { }
+ fn check_stmt(&mut self, _: &Context, _: &ast::Stmt) { }
+ fn check_arm(&mut self, _: &Context, _: &ast::Arm) { }
+ fn check_pat(&mut self, _: &Context, _: &ast::Pat) { }
+ fn check_decl(&mut self, _: &Context, _: &ast::Decl) { }
+ fn check_expr(&mut self, _: &Context, _: &ast::Expr) { }
+ fn check_expr_post(&mut self, _: &Context, _: &ast::Expr) { }
+ fn check_ty(&mut self, _: &Context, _: &ast::Ty) { }
+ fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
+ fn check_fn(&mut self, _: &Context,
+ _: &FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
+ fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
+ fn check_trait_method(&mut self, _: &Context, _: &ast::TraitMethod) { }
+ fn check_struct_def(&mut self, _: &Context,
+ _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
+ fn check_struct_def_post(&mut self, _: &Context,
+ _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
+ fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
+ fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
+ fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: &Option<ast::Lifetime>) { }
+ fn check_lifetime_ref(&mut self, _: &Context, _: &ast::Lifetime) { }
+ fn check_lifetime_decl(&mut self, _: &Context, _: &ast::Lifetime) { }
+ fn check_explicit_self(&mut self, _: &Context, _: &ast::ExplicitSelf) { }
+ fn check_mac(&mut self, _: &Context, _: &ast::Mac) { }
+ fn check_path(&mut self, _: &Context, _: &ast::Path, _: ast::NodeId) { }
+ fn check_attribute(&mut self, _: &Context, _: &ast::Attribute) { }
+
+ /// Called when entering a syntax node that can have lint attributes such
+ /// as `#[allow(...)]`. Called with *all* the attributes of that node.
+ fn enter_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
+
+ /// Counterpart to `enter_lint_attrs`.
+ fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) { }
+}
+
+/// A lint pass boxed up as a trait object.
+pub type LintPassObject = Box<LintPass + 'static>;
+
+/// Identifies a lint known to the compiler.
+#[deriving(Clone)]
+pub struct LintId {
+ // Identity is based on pointer equality of this field.
+ lint: &'static Lint,
+}
+
+impl PartialEq for LintId {
+ fn eq(&self, other: &LintId) -> bool {
+ (self.lint as *Lint) == (other.lint as *Lint)
+ }
+}
+
+impl Eq for LintId { }
+
+impl<S: hash::Writer> hash::Hash<S> for LintId {
+ fn hash(&self, state: &mut S) {
+ let ptr = self.lint as *Lint;
+ ptr.hash(state);
+ }
+}
+
+impl LintId {
+ /// Get the `LintId` for a `Lint`.
+ pub fn of(lint: &'static Lint) -> LintId {
+ LintId {
+ lint: lint,
+ }
+ }
+
+ /// Get the name of the lint.
+ pub fn as_str(&self) -> String {
+ self.lint.name_lower()
+ }
+}
+
+/// Setting for how to handle a lint.
+#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
+pub enum Level {
+ Allow, Warn, Deny, Forbid
+}
+
+impl Level {
+ /// Convert a level to a lower-case string.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Allow => "allow",
+ Warn => "warn",
+ Deny => "deny",
+ Forbid => "forbid",
+ }
+ }
+
+ /// Convert a lower-case string to a level.
+ pub fn from_str(x: &str) -> Option<Level> {
+ match x {
+ "allow" => Some(Allow),
+ "warn" => Some(Warn),
+ "deny" => Some(Deny),
+ "forbid" => Some(Forbid),
+ _ => None,
+ }
+ }
+}
+
+/// How a lint level was set.
+#[deriving(Clone, PartialEq, Eq)]
+pub enum LintSource {
+ /// Lint is at the default level as declared
+ /// in rustc or a plugin.
+ Default,
+
+ /// Lint level was set by an attribute.
+ Node(Span),
+
+ /// Lint level was set by a command-line flag.
+ CommandLine,
+}
+
+pub type LevelSource = (Level, LintSource);
+
+pub mod builtin;
+
+mod context;
macros: macros.move_iter().map(|x| x.to_string()).collect(),
registrar_symbol: registrar,
};
- if should_link {
+ if should_link && existing_match(&self.env, &info.crate_id, None).is_none() {
// register crate now to avoid double-reading metadata
register_crate(&mut self.env, &None, info.ident.as_slice(),
&info.crate_id, krate.span, library);
fn extract_one(&mut self, m: HashSet<Path>, flavor: &str,
slot: &mut Option<MetadataBlob>) -> Option<Path> {
let mut ret = None::<Path>;
- let mut error = 0;
+ let mut error = 0u;
if slot.is_some() {
// FIXME(#10786): for an optimization, we only read one of the
#![allow(non_camel_case_types)]
-use middle::const_eval::{compare_const_vals, const_bool, const_float, const_val};
+use middle::const_eval::{compare_const_vals, const_bool, const_float, const_nil, const_val};
use middle::const_eval::{eval_const_expr, lookup_const_by_id};
use middle::def::*;
use middle::pat_util::*;
fn const_val_to_expr(value: &const_val) -> Gc<Expr> {
let node = match value {
&const_bool(b) => LitBool(b),
+ &const_nil => LitNil,
_ => unreachable!()
};
box(GC) Expr {
ty::ty_bool =>
[true, false].iter().map(|b| val(const_bool(*b))).collect(),
+ ty::ty_nil =>
+ vec!(val(const_nil)),
+
ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
ty::ty_vec(_, None) => vec_constructors(m),
_ => vec!(single)
ty::ty_vec(_, Some(n)) =>
vec!(vec(n)),
- ty::ty_nil if !m.iter().all(|r| is_wild(cx, *r.get(0))) =>
- vec!(),
-
_ =>
vec!(single)
}
},
None => ()
}
+ check_legality_of_move_bindings(cx, false, [input.pat]);
}
}
const_uint(u64),
const_str(InternedString),
const_binary(Rc<Vec<u8> >),
- const_bool(bool)
+ const_bool(bool),
+ const_nil
}
pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
BiAnd | BiBitAnd => Ok(const_int(a & b)),
BiOr | BiBitOr => Ok(const_int(a | b)),
BiBitXor => Ok(const_int(a ^ b)),
- BiShl => Ok(const_int(a << b)),
- BiShr => Ok(const_int(a >> b)),
+ BiShl => Ok(const_int(a << b as uint)),
+ BiShr => Ok(const_int(a >> b as uint)),
BiEq => fromb(a == b),
BiLt => fromb(a < b),
BiLe => fromb(a <= b),
BiAnd | BiBitAnd => Ok(const_uint(a & b)),
BiOr | BiBitOr => Ok(const_uint(a | b)),
BiBitXor => Ok(const_uint(a ^ b)),
- BiShl => Ok(const_uint(a << b)),
- BiShr => Ok(const_uint(a >> b)),
+ BiShl => Ok(const_uint(a << b as uint)),
+ BiShr => Ok(const_uint(a >> b as uint)),
BiEq => fromb(a == b),
BiLt => fromb(a < b),
BiLe => fromb(a <= b),
// shifts can have any integral type as their rhs
(Ok(const_int(a)), Ok(const_uint(b))) => {
match op {
- BiShl => Ok(const_int(a << b)),
- BiShr => Ok(const_int(a >> b)),
+ BiShl => Ok(const_int(a << b as uint)),
+ BiShr => Ok(const_int(a >> b as uint)),
_ => Err("can't do this op on an int and uint".to_string())
}
}
(Ok(const_uint(a)), Ok(const_int(b))) => {
match op {
- BiShl => Ok(const_uint(a << b)),
- BiShr => Ok(const_uint(a >> b)),
+ BiShl => Ok(const_uint(a << b as uint)),
+ BiShr => Ok(const_uint(a >> b as uint)),
_ => Err("can't do this op on a uint and int".to_string())
}
}
LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
const_float(from_str::<f64>(n.get()).unwrap() as f64)
}
- LitNil => const_int(0i64),
+ LitNil => const_nil,
LitBool(b) => const_bool(b)
}
}
(&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
(&const_bool(a), &const_bool(b)) => compare_vals(a, b),
(&const_binary(ref a), &const_binary(ref b)) => compare_vals(a, b),
+ (&const_nil, &const_nil) => compare_vals((), ()),
_ => None
}
}
fn bit_str(bit: uint) -> String {
let byte = bit >> 8;
- let lobits = 1 << (bit & 0xFF);
+ let lobits = 1u << (bit & 0xFF);
format!("[{}:{}-{:02x}]", bit, byte, lobits)
}
// from live codes are live, and everything else is dead.
use middle::def;
-use middle::lint::{Allow, contains_lint, DeadCode};
+use lint;
use middle::privacy;
use middle::ty;
use middle::typeck;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_util::{local_def, is_local};
+use syntax::attr::AttrMetaMethods;
use syntax::attr;
use syntax::codemap;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
-pub static DEAD_CODE_LINT_STR: &'static str = "dead_code";
-
// Any local node that may call something in its body block should be
// explored. For example, if it's a live NodeItem that is a
// function, then we should explore its block to check for codes that
}
fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
- contains_lint(attrs, Allow, DEAD_CODE_LINT_STR)
- || attr::contains_name(attrs.as_slice(), "lang")
+ if attr::contains_name(attrs.as_slice(), "lang") {
+ return true;
+ }
+
+ let dead_code = lint::builtin::DEAD_CODE.name_lower();
+ for attr in lint::gather_attrs(attrs).move_iter() {
+ match attr {
+ Ok((ref name, lint::Allow, _))
+ if name.get() == dead_code.as_slice() => return true,
+ _ => (),
+ }
+ }
+ false
}
// This visitor seeds items that
ident: ast::Ident) {
self.tcx
.sess
- .add_lint(DeadCode,
+ .add_lint(lint::builtin::DEAD_CODE,
id,
span,
format!("code is never used: `{}`",
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! A 'lint' check is a kind of miscellaneous constraint that a user _might_
-//! want to enforce, but might reasonably want to permit as well, on a
-//! module-by-module basis. They contrast with static constraints enforced by
-//! other phases of the compiler, which are generally required to hold in order
-//! to compile the program at all.
-//!
-//! The lint checking is all consolidated into one pass which runs just before
-//! translation to LLVM bytecode. Throughout compilation, lint warnings can be
-//! added via the `add_lint` method on the Session structure. This requires a
-//! span and an id of the node that the lint is being added to. The lint isn't
-//! actually emitted at that time because it is unknown what the actual lint
-//! level at that location is.
-//!
-//! To actually emit lint warnings/errors, a separate pass is used just before
-//! translation. A context keeps track of the current state of all lint levels.
-//! Upon entering a node of the ast which can modify the lint settings, the
-//! previous lint state is pushed onto a stack and the ast is then recursed
-//! upon. As the ast is traversed, this keeps track of the current lint level
-//! for all lint attributes.
-//!
-//! To add a new lint warning, all you need to do is to either invoke `add_lint`
-//! on the session at the appropriate time, or write a few linting functions and
-//! modify the Context visitor appropriately. If you're adding lints from the
-//! Context itself, span_lint should be used instead of add_lint.
-
-#![allow(non_camel_case_types)]
-
-use driver::session;
-use metadata::csearch;
-use middle::dead::DEAD_CODE_LINT_STR;
-use middle::def;
-use middle::def::*;
-use middle::pat_util;
-use middle::privacy;
-use middle::trans::adt; // for `adt::is_ffi_safe`
-use middle::ty;
-use middle::typeck::astconv::{ast_ty_to_ty, AstConv};
-use middle::typeck::infer;
-use middle::typeck;
-use util::ppaux::{ty_to_str};
-use util::nodemap::NodeSet;
-
-use std::cmp;
-use std::collections::HashMap;
-use std::i16;
-use std::i32;
-use std::i64;
-use std::i8;
-use std::rc::Rc;
-use std::gc::Gc;
-use std::to_str::ToStr;
-use std::u16;
-use std::u32;
-use std::u64;
-use std::u8;
-use std::collections::SmallIntMap;
-use syntax::abi;
-use syntax::ast_map;
-use syntax::ast_util::IdVisitingOperation;
-use syntax::attr::AttrMetaMethods;
-use syntax::attr;
-use syntax::codemap::Span;
-use syntax::parse::token::InternedString;
-use syntax::parse::token;
-use syntax::visit::Visitor;
-use syntax::{ast, ast_util, visit};
-
-#[deriving(Clone, Show, PartialEq, PartialOrd, Eq, Ord, Hash)]
-pub enum Lint {
- CTypes,
- UnusedImports,
- UnnecessaryQualification,
- WhileTrue,
- PathStatement,
- UnrecognizedLint,
- NonCamelCaseTypes,
- NonUppercaseStatics,
- NonUppercasePatternStatics,
- NonSnakeCaseFunctions,
- UppercaseVariables,
- UnnecessaryParens,
- TypeLimits,
- TypeOverflow,
- UnusedUnsafe,
- UnsafeBlock,
- UnusedAttribute,
- UnknownFeatures,
- UnknownCrateType,
- UnsignedNegate,
- VariantSizeDifference,
-
- ManagedHeapMemory,
- OwnedHeapMemory,
- HeapMemory,
-
- UnusedVariable,
- DeadAssignment,
- UnusedMut,
- UnnecessaryAllocation,
- DeadCode,
- VisiblePrivateTypes,
- UnnecessaryTypecast,
-
- MissingDoc,
- UnreachableCode,
-
- Deprecated,
- Experimental,
- Unstable,
-
- UnusedMustUse,
- UnusedResult,
-
- Warnings,
-
- RawPointerDeriving,
-}
-
-pub fn level_to_str(lv: Level) -> &'static str {
- match lv {
- Allow => "allow",
- Warn => "warn",
- Deny => "deny",
- Forbid => "forbid"
- }
-}
-
-#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
-pub enum Level {
- Allow, Warn, Deny, Forbid
-}
-
-#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)]
-pub struct LintSpec {
- pub default: Level,
- pub lint: Lint,
- pub desc: &'static str,
-}
-
-pub type LintDict = HashMap<&'static str, LintSpec>;
-
-// this is public for the lints that run in trans
-#[deriving(PartialEq)]
-pub enum LintSource {
- Node(Span),
- Default,
- CommandLine
-}
-
-static lint_table: &'static [(&'static str, LintSpec)] = &[
- ("ctypes",
- LintSpec {
- lint: CTypes,
- desc: "proper use of libc types in foreign modules",
- default: Warn
- }),
-
- ("unused_imports",
- LintSpec {
- lint: UnusedImports,
- desc: "imports that are never used",
- default: Warn
- }),
-
- ("unnecessary_qualification",
- LintSpec {
- lint: UnnecessaryQualification,
- desc: "detects unnecessarily qualified names",
- default: Allow
- }),
-
- ("while_true",
- LintSpec {
- lint: WhileTrue,
- desc: "suggest using `loop { }` instead of `while true { }`",
- default: Warn
- }),
-
- ("path_statement",
- LintSpec {
- lint: PathStatement,
- desc: "path statements with no effect",
- default: Warn
- }),
-
- ("unrecognized_lint",
- LintSpec {
- lint: UnrecognizedLint,
- desc: "unrecognized lint attribute",
- default: Warn
- }),
-
- ("non_camel_case_types",
- LintSpec {
- lint: NonCamelCaseTypes,
- desc: "types, variants and traits should have camel case names",
- default: Warn
- }),
-
- ("non_uppercase_statics",
- LintSpec {
- lint: NonUppercaseStatics,
- desc: "static constants should have uppercase identifiers",
- default: Allow
- }),
-
- ("non_uppercase_pattern_statics",
- LintSpec {
- lint: NonUppercasePatternStatics,
- desc: "static constants in match patterns should be all caps",
- default: Warn
- }),
-
- ("non_snake_case_functions",
- LintSpec {
- lint: NonSnakeCaseFunctions,
- desc: "methods and functions should have snake case names",
- default: Warn
- }),
-
- ("uppercase_variables",
- LintSpec {
- lint: UppercaseVariables,
- desc: "variable and structure field names should start with a lowercase character",
- default: Warn
- }),
-
- ("unnecessary_parens",
- LintSpec {
- lint: UnnecessaryParens,
- desc: "`if`, `match`, `while` and `return` do not need parentheses",
- default: Warn
- }),
-
- ("managed_heap_memory",
- LintSpec {
- lint: ManagedHeapMemory,
- desc: "use of managed (@ type) heap memory",
- default: Allow
- }),
-
- ("owned_heap_memory",
- LintSpec {
- lint: OwnedHeapMemory,
- desc: "use of owned (Box type) heap memory",
- default: Allow
- }),
-
- ("heap_memory",
- LintSpec {
- lint: HeapMemory,
- desc: "use of any (Box type or @ type) heap memory",
- default: Allow
- }),
-
- ("type_limits",
- LintSpec {
- lint: TypeLimits,
- desc: "comparisons made useless by limits of the types involved",
- default: Warn
- }),
-
- ("type_overflow",
- LintSpec {
- lint: TypeOverflow,
- desc: "literal out of range for its type",
- default: Warn
- }),
-
-
- ("unused_unsafe",
- LintSpec {
- lint: UnusedUnsafe,
- desc: "unnecessary use of an `unsafe` block",
- default: Warn
- }),
-
- ("unsafe_block",
- LintSpec {
- lint: UnsafeBlock,
- desc: "usage of an `unsafe` block",
- default: Allow
- }),
-
- ("unused_attribute",
- LintSpec {
- lint: UnusedAttribute,
- desc: "detects attributes that were not used by the compiler",
- default: Warn
- }),
-
- ("unused_variable",
- LintSpec {
- lint: UnusedVariable,
- desc: "detect variables which are not used in any way",
- default: Warn
- }),
-
- ("dead_assignment",
- LintSpec {
- lint: DeadAssignment,
- desc: "detect assignments that will never be read",
- default: Warn
- }),
-
- ("unnecessary_typecast",
- LintSpec {
- lint: UnnecessaryTypecast,
- desc: "detects unnecessary type casts, that can be removed",
- default: Allow,
- }),
-
- ("unused_mut",
- LintSpec {
- lint: UnusedMut,
- desc: "detect mut variables which don't need to be mutable",
- default: Warn
- }),
-
- ("unnecessary_allocation",
- LintSpec {
- lint: UnnecessaryAllocation,
- desc: "detects unnecessary allocations that can be eliminated",
- default: Warn
- }),
-
- (DEAD_CODE_LINT_STR,
- LintSpec {
- lint: DeadCode,
- desc: "detect piece of code that will never be used",
- default: Warn
- }),
- ("visible_private_types",
- LintSpec {
- lint: VisiblePrivateTypes,
- desc: "detect use of private types in exported type signatures",
- default: Warn
- }),
-
- ("missing_doc",
- LintSpec {
- lint: MissingDoc,
- desc: "detects missing documentation for public members",
- default: Allow
- }),
-
- ("unreachable_code",
- LintSpec {
- lint: UnreachableCode,
- desc: "detects unreachable code",
- default: Warn
- }),
-
- ("deprecated",
- LintSpec {
- lint: Deprecated,
- desc: "detects use of #[deprecated] items",
- default: Warn
- }),
-
- ("experimental",
- LintSpec {
- lint: Experimental,
- desc: "detects use of #[experimental] items",
- // FIXME #6875: Change to Warn after std library stabilization is complete
- default: Allow
- }),
-
- ("unstable",
- LintSpec {
- lint: Unstable,
- desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
- default: Allow
- }),
-
- ("warnings",
- LintSpec {
- lint: Warnings,
- desc: "mass-change the level for lints which produce warnings",
- default: Warn
- }),
-
- ("unknown_features",
- LintSpec {
- lint: UnknownFeatures,
- desc: "unknown features found in crate-level #[feature] directives",
- default: Deny,
- }),
-
- ("unknown_crate_type",
- LintSpec {
- lint: UnknownCrateType,
- desc: "unknown crate type found in #[crate_type] directive",
- default: Deny,
- }),
-
- ("unsigned_negate",
- LintSpec {
- lint: UnsignedNegate,
- desc: "using an unary minus operator on unsigned type",
- default: Warn
- }),
-
- ("variant_size_difference",
- LintSpec {
- lint: VariantSizeDifference,
- desc: "detects enums with widely varying variant sizes",
- default: Allow,
- }),
-
- ("unused_must_use",
- LintSpec {
- lint: UnusedMustUse,
- desc: "unused result of a type flagged as #[must_use]",
- default: Warn,
- }),
-
- ("unused_result",
- LintSpec {
- lint: UnusedResult,
- desc: "unused result of an expression in a statement",
- default: Allow,
- }),
-
- ("raw_pointer_deriving",
- LintSpec {
- lint: RawPointerDeriving,
- desc: "uses of #[deriving] with raw pointers are rarely correct",
- default: Warn,
- }),
-];
-
-/*
- Pass names should not contain a '-', as the compiler normalizes
- '-' to '_' in command-line flags
- */
-pub fn get_lint_dict() -> LintDict {
- lint_table.iter().map(|&(k, v)| (k, v)).collect()
-}
-
-struct Context<'a> {
- /// All known lint modes (string versions)
- dict: LintDict,
- /// Current levels of each lint warning
- cur: SmallIntMap<(Level, LintSource)>,
- /// Context we're checking in (used to access fields like sess)
- tcx: &'a ty::ctxt,
- /// Items exported by the crate; used by the missing_doc lint.
- exported_items: &'a privacy::ExportedItems,
- /// The id of the current `ast::StructDef` being walked.
- cur_struct_def_id: ast::NodeId,
- /// Whether some ancestor of the current node was marked
- /// #[doc(hidden)].
- is_doc_hidden: bool,
-
- /// When recursing into an attributed node of the ast which modifies lint
- /// levels, this stack keeps track of the previous lint levels of whatever
- /// was modified.
- lint_stack: Vec<(Lint, Level, LintSource)>,
-
- /// Id of the last visited negated expression
- negated_expr_id: ast::NodeId,
-
- /// Ids of structs/enums which have been checked for raw_pointer_deriving
- checked_raw_pointers: NodeSet,
-
- /// Level of lints for certain NodeIds, stored here because the body of
- /// the lint needs to run in trans.
- node_levels: HashMap<(ast::NodeId, Lint), (Level, LintSource)>,
-}
-
-pub fn emit_lint(level: Level, src: LintSource, msg: &str, span: Span,
- lint_str: &str, tcx: &ty::ctxt) {
- if level == Allow { return }
-
- let mut note = None;
- let msg = match src {
- Default => {
- format!("{}, #[{}({})] on by default", msg,
- level_to_str(level), lint_str)
- },
- CommandLine => {
- format!("{} [-{} {}]", msg,
- match level {
- Warn => 'W', Deny => 'D', Forbid => 'F',
- Allow => fail!()
- }, lint_str.replace("_", "-"))
- },
- Node(src) => {
- note = Some(src);
- msg.to_str()
- }
- };
-
- match level {
- Warn => { tcx.sess.span_warn(span, msg.as_slice()); }
- Deny | Forbid => { tcx.sess.span_err(span, msg.as_slice()); }
- Allow => fail!(),
- }
-
- for &span in note.iter() {
- tcx.sess.span_note(span, "lint level defined here");
- }
-}
-
-pub fn lint_to_str(lint: Lint) -> &'static str {
- for &(name, lspec) in lint_table.iter() {
- if lspec.lint == lint {
- return name;
- }
- }
-
- fail!("unrecognized lint: {}", lint);
-}
-
-impl<'a> Context<'a> {
- fn get_level(&self, lint: Lint) -> Level {
- match self.cur.find(&(lint as uint)) {
- Some(&(lvl, _)) => lvl,
- None => Allow
- }
- }
-
- fn get_source(&self, lint: Lint) -> LintSource {
- match self.cur.find(&(lint as uint)) {
- Some(&(_, src)) => src,
- None => Default
- }
- }
-
- fn set_level(&mut self, lint: Lint, level: Level, src: LintSource) {
- if level == Allow {
- self.cur.remove(&(lint as uint));
- } else {
- self.cur.insert(lint as uint, (level, src));
- }
- }
-
- fn lint_to_str(&self, lint: Lint) -> &'static str {
- for (k, v) in self.dict.iter() {
- if v.lint == lint {
- return *k;
- }
- }
- fail!("unregistered lint {}", lint);
- }
-
- fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
- let (level, src) = match self.cur.find(&(lint as uint)) {
- None => { return }
- Some(&(Warn, src)) => (self.get_level(Warnings), src),
- Some(&pair) => pair,
- };
-
- emit_lint(level, src, msg, span, self.lint_to_str(lint), self.tcx);
- }
-
- /**
- * Merge the lints specified by any lint attributes into the
- * current lint context, call the provided function, then reset the
- * lints in effect to their previous state.
- */
- fn with_lint_attrs(&mut self,
- attrs: &[ast::Attribute],
- f: |&mut Context|) {
- // Parse all of the lint attributes, and then add them all to the
- // current dictionary of lint information. Along the way, keep a history
- // of what we changed so we can roll everything back after invoking the
- // specified closure
- let mut pushed = 0u;
- each_lint(&self.tcx.sess, attrs, |meta, level, lintname| {
- match self.dict.find_equiv(&lintname) {
- None => {
- self.span_lint(
- UnrecognizedLint,
- meta.span,
- format!("unknown `{}` attribute: `{}`",
- level_to_str(level), lintname).as_slice());
- }
- Some(lint) => {
- let lint = lint.lint;
- let now = self.get_level(lint);
- if now == Forbid && level != Forbid {
- self.tcx.sess.span_err(meta.span,
- format!("{}({}) overruled by outer forbid({})",
- level_to_str(level),
- lintname,
- lintname).as_slice());
- } else if now != level {
- let src = self.get_source(lint);
- self.lint_stack.push((lint, now, src));
- pushed += 1;
- self.set_level(lint, level, Node(meta.span));
- }
- }
- }
- true
- });
-
- let old_is_doc_hidden = self.is_doc_hidden;
- self.is_doc_hidden =
- self.is_doc_hidden ||
- attrs.iter()
- .any(|attr| {
- attr.name().equiv(&("doc")) &&
- match attr.meta_item_list() {
- None => false,
- Some(l) => {
- attr::contains_name(l.as_slice(), "hidden")
- }
- }
- });
-
- f(self);
-
- // rollback
- self.is_doc_hidden = old_is_doc_hidden;
- for _ in range(0, pushed) {
- let (lint, lvl, src) = self.lint_stack.pop().unwrap();
- self.set_level(lint, lvl, src);
- }
- }
-
- fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
- let mut v = ast_util::IdVisitor {
- operation: self,
- pass_through_items: false,
- visited_outermost: false,
- };
- f(&mut v);
- }
-}
-
-/// Check that every lint from the list of attributes satisfies `f`.
-/// Return true if that's the case. Otherwise return false.
-pub fn each_lint(sess: &session::Session,
- attrs: &[ast::Attribute],
- f: |Gc<ast::MetaItem>, Level, InternedString| -> bool)
- -> bool {
- let xs = [Allow, Warn, Deny, Forbid];
- for &level in xs.iter() {
- let level_name = level_to_str(level);
- for attr in attrs.iter().filter(|m| m.check_name(level_name)) {
- let meta = attr.node.value;
- let metas = match meta.node {
- ast::MetaList(_, ref metas) => metas,
- _ => {
- sess.span_err(meta.span, "malformed lint attribute");
- continue;
- }
- };
- for meta in metas.iter() {
- match meta.node {
- ast::MetaWord(ref lintname) => {
- if !f(*meta, level, (*lintname).clone()) {
- return false;
- }
- }
- _ => {
- sess.span_err(meta.span, "malformed lint attribute");
- }
- }
- }
- }
- }
- true
-}
-
-/// Check from a list of attributes if it contains the appropriate
-/// `#[level(lintname)]` attribute (e.g. `#[allow(dead_code)]).
-pub fn contains_lint(attrs: &[ast::Attribute],
- level: Level,
- lintname: &'static str)
- -> bool {
- let level_name = level_to_str(level);
- for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
- if attr.meta_item_list().is_none() {
- continue
- }
- let list = attr.meta_item_list().unwrap();
- for meta_item in list.iter() {
- if meta_item.name().equiv(&lintname) {
- return true;
- }
- }
- }
- false
-}
-
-fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
- match e.node {
- ast::ExprWhile(cond, _) => {
- match cond.node {
- ast::ExprLit(lit) => {
- match lit.node {
- ast::LitBool(true) => {
- cx.span_lint(WhileTrue,
- e.span,
- "denote infinite loops with loop \
- { ... }");
- }
- _ => {}
- }
- }
- _ => ()
- }
- }
- _ => ()
- }
-}
-impl<'a> AstConv for Context<'a>{
- fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
-
- fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype {
- ty::lookup_item_type(self.tcx, id)
- }
-
- fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef> {
- ty::lookup_trait_def(self.tcx, id)
- }
-
- fn ty_infer(&self, _span: Span) -> ty::t {
- infer::new_infer_ctxt(self.tcx).next_ty_var()
- }
-}
-
-
-fn check_unused_casts(cx: &Context, e: &ast::Expr) {
- return match e.node {
- ast::ExprCast(expr, ty) => {
- let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), &*ty);
- if ty::get(ty::expr_ty(cx.tcx, &*expr)).sty == ty::get(t_t).sty {
- cx.span_lint(UnnecessaryTypecast, ty.span,
- "unnecessary type cast");
- }
- }
- _ => ()
- };
-}
-
-fn check_type_limits(cx: &Context, e: &ast::Expr) {
- return match e.node {
- ast::ExprUnary(ast::UnNeg, ex) => {
- match ex.node {
- ast::ExprLit(lit) => {
- match lit.node {
- ast::LitUint(..) => {
- cx.span_lint(UnsignedNegate, e.span,
- "negation of unsigned int literal may be unintentional");
- },
- _ => ()
- }
- },
- _ => {
- let t = ty::expr_ty(cx.tcx, &*ex);
- match ty::get(t).sty {
- ty::ty_uint(_) => {
- cx.span_lint(UnsignedNegate, e.span,
- "negation of unsigned int variable may be unintentional");
- },
- _ => ()
- }
- }
- }
- },
- ast::ExprBinary(binop, l, r) => {
- if is_comparison(binop) && !check_limits(cx.tcx, binop, &*l, &*r) {
- cx.span_lint(TypeLimits, e.span,
- "comparison is useless due to type limits");
- }
- },
- ast::ExprLit(lit) => {
- match ty::get(ty::expr_ty(cx.tcx, e)).sty {
- ty::ty_int(t) => {
- let int_type = if t == ast::TyI {
- cx.tcx.sess.targ_cfg.int_type
- } else { t };
- let (min, max) = int_ty_range(int_type);
- let mut lit_val: i64 = match lit.node {
- ast::LitInt(v, _) => v,
- ast::LitUint(v, _) => v as i64,
- ast::LitIntUnsuffixed(v) => v,
- _ => fail!()
- };
- if cx.negated_expr_id == e.id {
- lit_val *= -1;
- }
- if lit_val < min || lit_val > max {
- cx.span_lint(TypeOverflow, e.span,
- "literal out of range for its type");
- }
- },
- ty::ty_uint(t) => {
- let uint_type = if t == ast::TyU {
- cx.tcx.sess.targ_cfg.uint_type
- } else { t };
- let (min, max) = uint_ty_range(uint_type);
- let lit_val: u64 = match lit.node {
- ast::LitByte(_v) => return, // _v is u8, within range by definition
- ast::LitInt(v, _) => v as u64,
- ast::LitUint(v, _) => v,
- ast::LitIntUnsuffixed(v) => v as u64,
- _ => fail!()
- };
- if lit_val < min || lit_val > max {
- cx.span_lint(TypeOverflow, e.span,
- "literal out of range for its type");
- }
- },
-
- _ => ()
- };
- },
- _ => ()
- };
-
- fn is_valid<T:cmp::PartialOrd>(binop: ast::BinOp, v: T,
- min: T, max: T) -> bool {
- match binop {
- ast::BiLt => v > min && v <= max,
- ast::BiLe => v >= min && v < max,
- ast::BiGt => v >= min && v < max,
- ast::BiGe => v > min && v <= max,
- ast::BiEq | ast::BiNe => v >= min && v <= max,
- _ => fail!()
- }
- }
-
- fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
- match binop {
- ast::BiLt => ast::BiGt,
- ast::BiLe => ast::BiGe,
- ast::BiGt => ast::BiLt,
- ast::BiGe => ast::BiLe,
- _ => binop
- }
- }
-
- // for int & uint, be conservative with the warnings, so that the
- // warnings are consistent between 32- and 64-bit platforms
- fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
- match int_ty {
- ast::TyI => (i64::MIN, i64::MAX),
- ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
- ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
- ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
- ast::TyI64 => (i64::MIN, i64::MAX)
- }
- }
-
- fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
- match uint_ty {
- ast::TyU => (u64::MIN, u64::MAX),
- ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
- ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
- ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
- ast::TyU64 => (u64::MIN, u64::MAX)
- }
- }
-
- fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
- l: &ast::Expr, r: &ast::Expr) -> bool {
- let (lit, expr, swap) = match (&l.node, &r.node) {
- (&ast::ExprLit(_), _) => (l, r, true),
- (_, &ast::ExprLit(_)) => (r, l, false),
- _ => return true
- };
- // Normalize the binop so that the literal is always on the RHS in
- // the comparison
- let norm_binop = if swap { rev_binop(binop) } else { binop };
- match ty::get(ty::expr_ty(tcx, expr)).sty {
- ty::ty_int(int_ty) => {
- let (min, max) = int_ty_range(int_ty);
- let lit_val: i64 = match lit.node {
- ast::ExprLit(li) => match li.node {
- ast::LitInt(v, _) => v,
- ast::LitUint(v, _) => v as i64,
- ast::LitIntUnsuffixed(v) => v,
- _ => return true
- },
- _ => fail!()
- };
- is_valid(norm_binop, lit_val, min, max)
- }
- ty::ty_uint(uint_ty) => {
- let (min, max): (u64, u64) = uint_ty_range(uint_ty);
- let lit_val: u64 = match lit.node {
- ast::ExprLit(li) => match li.node {
- ast::LitInt(v, _) => v as u64,
- ast::LitUint(v, _) => v,
- ast::LitIntUnsuffixed(v) => v as u64,
- _ => return true
- },
- _ => fail!()
- };
- is_valid(norm_binop, lit_val, min, max)
- }
- _ => true
- }
- }
-
- fn is_comparison(binop: ast::BinOp) -> bool {
- match binop {
- ast::BiEq | ast::BiLt | ast::BiLe |
- ast::BiNe | ast::BiGe | ast::BiGt => true,
- _ => false
- }
- }
-}
-
-fn check_item_ctypes(cx: &Context, it: &ast::Item) {
- fn check_ty(cx: &Context, ty: &ast::Ty) {
- match ty.node {
- ast::TyPath(_, _, id) => {
- match cx.tcx.def_map.borrow().get_copy(&id) {
- def::DefPrimTy(ast::TyInt(ast::TyI)) => {
- cx.span_lint(CTypes, ty.span,
- "found rust type `int` in foreign module, while \
- libc::c_int or libc::c_long should be used");
- }
- def::DefPrimTy(ast::TyUint(ast::TyU)) => {
- cx.span_lint(CTypes, ty.span,
- "found rust type `uint` in foreign module, while \
- libc::c_uint or libc::c_ulong should be used");
- }
- def::DefTy(def_id) => {
- if !adt::is_ffi_safe(cx.tcx, def_id) {
- cx.span_lint(CTypes, ty.span,
- "found enum type without foreign-function-safe \
- representation annotation in foreign module");
- // hmm... this message could be more helpful
- }
- }
- _ => ()
- }
- }
- ast::TyPtr(ref mt) => { check_ty(cx, &*mt.ty) }
- _ => {}
- }
- }
-
- fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
- for input in decl.inputs.iter() {
- check_ty(cx, &*input.ty);
- }
- check_ty(cx, &*decl.output)
- }
-
- match it.node {
- ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
- for ni in nmod.items.iter() {
- match ni.node {
- ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, &*decl),
- ast::ForeignItemStatic(t, _) => check_ty(cx, &*t)
- }
- }
- }
- _ => {/* nothing to do */ }
- }
-}
-
-fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
- let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
- for &lint in xs.iter() {
- if cx.get_level(lint) == Allow { continue }
-
- let mut n_box = 0;
- let mut n_uniq = 0;
- ty::fold_ty(cx.tcx, ty, |t| {
- match ty::get(t).sty {
- ty::ty_box(_) => {
- n_box += 1;
- }
- ty::ty_uniq(_) |
- ty::ty_closure(box ty::ClosureTy {
- store: ty::UniqTraitStore,
- ..
- }) => {
- n_uniq += 1;
- }
-
- _ => ()
- };
- t
- });
-
- if n_uniq > 0 && lint != ManagedHeapMemory {
- let s = ty_to_str(cx.tcx, ty);
- let m = format!("type uses owned (Box type) pointers: {}", s);
- cx.span_lint(lint, span, m.as_slice());
- }
-
- if n_box > 0 && lint != OwnedHeapMemory {
- let s = ty_to_str(cx.tcx, ty);
- let m = format!("type uses managed (@ type) pointers: {}", s);
- cx.span_lint(lint, span, m.as_slice());
- }
- }
-}
-
-fn check_heap_item(cx: &Context, it: &ast::Item) {
- match it.node {
- ast::ItemFn(..) |
- ast::ItemTy(..) |
- ast::ItemEnum(..) |
- ast::ItemStruct(..) => check_heap_type(cx, it.span,
- ty::node_id_to_type(cx.tcx,
- it.id)),
- _ => ()
- }
-
- // If it's a struct, we also have to check the fields' types
- match it.node {
- ast::ItemStruct(struct_def, _) => {
- for struct_field in struct_def.fields.iter() {
- check_heap_type(cx, struct_field.span,
- ty::node_id_to_type(cx.tcx,
- struct_field.node.id));
- }
- }
- _ => ()
- }
-}
-
-struct RawPtrDerivingVisitor<'a> {
- cx: &'a Context<'a>
-}
-
-impl<'a> Visitor<()> for RawPtrDerivingVisitor<'a> {
- fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
- static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
- match ty.node {
- ast::TyPtr(..) => self.cx.span_lint(RawPointerDeriving, ty.span, MSG),
- _ => {}
- }
- visit::walk_ty(self, ty, ());
- }
- // explicit override to a no-op to reduce code bloat
- fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
- fn visit_block(&mut self, _: &ast::Block, _: ()) {}
-}
-
-fn check_raw_ptr_deriving(cx: &mut Context, item: &ast::Item) {
- if !attr::contains_name(item.attrs.as_slice(), "automatically_derived") {
- return
- }
- let did = match item.node {
- ast::ItemImpl(..) => {
- match ty::get(ty::node_id_to_type(cx.tcx, item.id)).sty {
- ty::ty_enum(did, _) => did,
- ty::ty_struct(did, _) => did,
- _ => return,
- }
- }
- _ => return,
- };
- if !ast_util::is_local(did) { return }
- let item = match cx.tcx.map.find(did.node) {
- Some(ast_map::NodeItem(item)) => item,
- _ => return,
- };
- if !cx.checked_raw_pointers.insert(item.id) { return }
- match item.node {
- ast::ItemStruct(..) | ast::ItemEnum(..) => {
- let mut visitor = RawPtrDerivingVisitor { cx: cx };
- visit::walk_item(&mut visitor, &*item, ());
- }
- _ => {}
- }
-}
-
-fn check_unused_attribute(cx: &Context, attr: &ast::Attribute) {
- static ATTRIBUTE_WHITELIST: &'static [&'static str] = &'static [
- // FIXME: #14408 whitelist docs since rustdoc looks at them
- "doc",
-
- // FIXME: #14406 these are processed in trans, which happens after the
- // lint pass
- "cold",
- "inline",
- "link",
- "link_name",
- "link_section",
- "no_builtins",
- "no_mangle",
- "no_split_stack",
- "packed",
- "static_assert",
- "thread_local",
-
- // not used anywhere (!?) but apparently we want to keep them around
- "comment",
- "desc",
- "license",
-
- // FIXME: #14407 these are only looked at on-demand so we can't
- // guarantee they'll have already been checked
- "deprecated",
- "experimental",
- "frozen",
- "locked",
- "must_use",
- "stable",
- "unstable",
- ];
-
- static CRATE_ATTRS: &'static [&'static str] = &'static [
- "crate_type",
- "feature",
- "no_start",
- "no_main",
- "no_std",
- "crate_id",
- "desc",
- "comment",
- "license",
- "copyright",
- "no_builtins",
- ];
-
- for &name in ATTRIBUTE_WHITELIST.iter() {
- if attr.check_name(name) {
- break;
- }
- }
-
- if !attr::is_used(attr) {
- cx.span_lint(UnusedAttribute, attr.span, "unused attribute");
- if CRATE_ATTRS.contains(&attr.name().get()) {
- let msg = match attr.node.style {
- ast::AttrOuter => "crate-level attribute should be an inner \
- attribute: add an exclamation mark: #![foo]",
- ast::AttrInner => "crate-level attribute should be in the \
- root module",
- };
- cx.span_lint(UnusedAttribute, attr.span, msg);
- }
- }
-}
-
-fn check_heap_expr(cx: &Context, e: &ast::Expr) {
- let ty = ty::expr_ty(cx.tcx, e);
- check_heap_type(cx, e.span, ty);
-}
-
-fn check_path_statement(cx: &Context, s: &ast::Stmt) {
- match s.node {
- ast::StmtSemi(expr, _) => {
- match expr.node {
- ast::ExprPath(_) => {
- cx.span_lint(PathStatement,
- s.span,
- "path statement with no effect");
- }
- _ => {}
- }
- }
- _ => ()
- }
-}
-
-fn check_unused_result(cx: &Context, s: &ast::Stmt) {
- let expr = match s.node {
- ast::StmtSemi(expr, _) => expr,
- _ => return
- };
- let t = ty::expr_ty(cx.tcx, &*expr);
- match ty::get(t).sty {
- ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
- _ => {}
- }
- match expr.node {
- ast::ExprRet(..) => return,
- _ => {}
- }
-
- let t = ty::expr_ty(cx.tcx, &*expr);
- let mut warned = false;
- match ty::get(t).sty {
- ty::ty_struct(did, _) |
- ty::ty_enum(did, _) => {
- if ast_util::is_local(did) {
- match cx.tcx.map.get(did.node) {
- ast_map::NodeItem(it) => {
- if attr::contains_name(it.attrs.as_slice(),
- "must_use") {
- cx.span_lint(UnusedMustUse, s.span,
- "unused result which must be used");
- warned = true;
- }
- }
- _ => {}
- }
- } else {
- csearch::get_item_attrs(&cx.tcx.sess.cstore, did, |attrs| {
- if attr::contains_name(attrs.as_slice(), "must_use") {
- cx.span_lint(UnusedMustUse, s.span,
- "unused result which must be used");
- warned = true;
- }
- });
- }
- }
- _ => {}
- }
- if !warned {
- cx.span_lint(UnusedResult, s.span, "unused result");
- }
-}
-
-fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
- fn is_camel_case(ident: ast::Ident) -> bool {
- let ident = token::get_ident(ident);
- assert!(!ident.get().is_empty());
- let ident = ident.get().trim_chars('_');
-
- // start with a non-lowercase letter rather than non-uppercase
- // ones (some scripts don't have a concept of upper/lowercase)
- !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
- }
-
- fn to_camel_case(s: &str) -> String {
- s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
- if i == 0 { c.to_uppercase() }
- else { c }
- )).collect()
- }
-
- fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
- let s = token::get_ident(ident);
-
- if !is_camel_case(ident) {
- cx.span_lint(
- NonCamelCaseTypes, span,
- format!("{} `{}` should have a camel case name such as `{}`",
- sort, s, to_camel_case(s.get())).as_slice());
- }
- }
-
- match it.node {
- ast::ItemTy(..) | ast::ItemStruct(..) => {
- check_case(cx, "type", it.ident, it.span)
- }
- ast::ItemTrait(..) => {
- check_case(cx, "trait", it.ident, it.span)
- }
- ast::ItemEnum(ref enum_definition, _) => {
- check_case(cx, "type", it.ident, it.span);
- for variant in enum_definition.variants.iter() {
- check_case(cx, "variant", variant.node.name, variant.span);
- }
- }
- _ => ()
- }
-}
-
-fn check_snake_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
- fn is_snake_case(ident: ast::Ident) -> bool {
- let ident = token::get_ident(ident);
- assert!(!ident.get().is_empty());
- let ident = ident.get().trim_chars('_');
-
- let mut allow_underscore = true;
- ident.chars().all(|c| {
- allow_underscore = match c {
- c if c.is_lowercase() || c.is_digit() => true,
- '_' if allow_underscore => false,
- _ => return false,
- };
- true
- })
- }
-
- fn to_snake_case(str: &str) -> String {
- let mut words = vec![];
- for s in str.split('_') {
- let mut buf = String::new();
- if s.is_empty() { continue; }
- for ch in s.chars() {
- if !buf.is_empty() && ch.is_uppercase() {
- words.push(buf);
- buf = String::new();
- }
- buf.push_char(ch.to_lowercase());
- }
- words.push(buf);
- }
- words.connect("_")
- }
-
- let s = token::get_ident(ident);
-
- if !is_snake_case(ident) {
- cx.span_lint(NonSnakeCaseFunctions, span,
- format!("{} `{}` should have a snake case name such as `{}`",
- sort, s, to_snake_case(s.get())).as_slice());
- }
-}
-
-fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
- match it.node {
- // only check static constants
- ast::ItemStatic(_, ast::MutImmutable, _) => {
- let s = token::get_ident(it.ident);
- // check for lowercase letters rather than non-uppercase
- // ones (some scripts don't have a concept of
- // upper/lowercase)
- if s.get().chars().any(|c| c.is_lowercase()) {
- cx.span_lint(NonUppercaseStatics, it.span,
- format!("static constant `{}` should have an uppercase name \
- such as `{}`", s.get(),
- s.get().chars().map(|c| c.to_uppercase())
- .collect::<String>().as_slice()).as_slice());
- }
- }
- _ => {}
- }
-}
-
-fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
- // Lint for constants that look like binding identifiers (#7526)
- match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
- (&ast::PatIdent(_, ref path, _), Some(&def::DefStatic(_, false))) => {
- // last identifier alone is right choice for this lint.
- let ident = path.segments.last().unwrap().identifier;
- let s = token::get_ident(ident);
- if s.get().chars().any(|c| c.is_lowercase()) {
- cx.span_lint(NonUppercasePatternStatics, path.span,
- format!("static constant in pattern `{}` should have an uppercase \
- name such as `{}`", s.get(),
- s.get().chars().map(|c| c.to_uppercase())
- .collect::<String>().as_slice()).as_slice());
- }
- }
- _ => {}
- }
-}
-
-fn check_pat_uppercase_variable(cx: &Context, p: &ast::Pat) {
- match &p.node {
- &ast::PatIdent(_, ref path, _) => {
- match cx.tcx.def_map.borrow().find(&p.id) {
- Some(&def::DefLocal(_, _)) | Some(&def::DefBinding(_, _)) |
- Some(&def::DefArg(_, _)) => {
- // last identifier alone is right choice for this lint.
- let ident = path.segments.last().unwrap().identifier;
- let s = token::get_ident(ident);
- if s.get().len() > 0 && s.get().char_at(0).is_uppercase() {
- cx.span_lint(
- UppercaseVariables,
- path.span,
- "variable names should start with a lowercase character");
- }
- }
- _ => {}
- }
- }
- _ => {}
- }
-}
-
-fn check_struct_uppercase_variable(cx: &Context, s: &ast::StructDef) {
- for sf in s.fields.iter() {
- match sf.node {
- ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
- let s = token::get_ident(ident);
- if s.get().char_at(0).is_uppercase() {
- cx.span_lint(
- UppercaseVariables,
- sf.span,
- "structure field names should start with a lowercase character");
- }
- }
- _ => {}
- }
- }
-}
-
-fn check_unnecessary_parens_core(cx: &Context, value: &ast::Expr, msg: &str) {
- match value.node {
- ast::ExprParen(_) => {
- cx.span_lint(UnnecessaryParens, value.span,
- format!("unnecessary parentheses around {}",
- msg).as_slice())
- }
- _ => {}
- }
-}
-
-fn check_unnecessary_parens_expr(cx: &Context, e: &ast::Expr) {
- let (value, msg) = match e.node {
- ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
- ast::ExprWhile(cond, _) => (cond, "`while` condition"),
- ast::ExprMatch(head, _) => (head, "`match` head expression"),
- ast::ExprRet(Some(value)) => (value, "`return` value"),
- ast::ExprAssign(_, value) => (value, "assigned value"),
- ast::ExprAssignOp(_, _, value) => (value, "assigned value"),
- _ => return
- };
- check_unnecessary_parens_core(cx, &*value, msg);
-}
-
-fn check_unnecessary_parens_stmt(cx: &Context, s: &ast::Stmt) {
- let (value, msg) = match s.node {
- ast::StmtDecl(decl, _) => match decl.node {
- ast::DeclLocal(local) => match local.init {
- Some(value) => (value, "assigned value"),
- None => return
- },
- _ => return
- },
- _ => return
- };
- check_unnecessary_parens_core(cx, &*value, msg);
-}
-
-fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
- match e.node {
- // Don't warn about generated blocks, that'll just pollute the output.
- ast::ExprBlock(ref blk) => {
- if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
- !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
- cx.span_lint(UnusedUnsafe, blk.span,
- "unnecessary `unsafe` block");
- }
- }
- _ => ()
- }
-}
-
-fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
- match e.node {
- // Don't warn about generated blocks, that'll just pollute the output.
- ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
- cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
- }
- _ => ()
- }
-}
-
-fn check_unused_mut_pat(cx: &Context, pats: &[Gc<ast::Pat>]) {
- // collect all mutable pattern and group their NodeIDs by their Identifier to
- // avoid false warnings in match arms with multiple patterns
- let mut mutables = HashMap::new();
- for &p in pats.iter() {
- pat_util::pat_bindings(&cx.tcx.def_map, &*p, |mode, id, _, path| {
- match mode {
- ast::BindByValue(ast::MutMutable) => {
- if path.segments.len() != 1 {
- cx.tcx.sess.span_bug(p.span,
- "mutable binding that doesn't consist \
- of exactly one segment");
- }
- let ident = path.segments.get(0).identifier;
- if !token::get_ident(ident).get().starts_with("_") {
- mutables.insert_or_update_with(ident.name as uint, vec!(id), |_, old| {
- old.push(id);
- });
- }
- }
- _ => {
- }
- }
- });
- }
-
- let used_mutables = cx.tcx.used_mut_nodes.borrow();
- for (_, v) in mutables.iter() {
- if !v.iter().any(|e| used_mutables.contains(e)) {
- cx.span_lint(UnusedMut, cx.tcx.map.span(*v.get(0)),
- "variable does not need to be mutable");
- }
- }
-}
-
-enum Allocation {
- VectorAllocation,
- BoxAllocation
-}
-
-fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
- // Warn if string and vector literals with sigils, or boxing expressions,
- // are immediately borrowed.
- let allocation = match e.node {
- ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
- match e2.node {
- ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
- VectorAllocation
- }
- ast::ExprVec(..) => VectorAllocation,
- _ => return
- }
- }
- ast::ExprUnary(ast::UnUniq, _) |
- ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
-
- _ => return
- };
-
- let report = |msg| {
- cx.span_lint(UnnecessaryAllocation, e.span, msg);
- };
-
- match cx.tcx.adjustments.borrow().find(&e.id) {
- Some(adjustment) => {
- match *adjustment {
- ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
- match (allocation, autoref) {
- (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
- report("unnecessary allocation, the sigil can be \
- removed");
- }
- (BoxAllocation,
- Some(ty::AutoPtr(_, ast::MutImmutable))) => {
- report("unnecessary allocation, use & instead");
- }
- (BoxAllocation,
- Some(ty::AutoPtr(_, ast::MutMutable))) => {
- report("unnecessary allocation, use &mut \
- instead");
- }
- _ => ()
- }
- }
- _ => {}
- }
- }
-
- _ => ()
- }
-}
-
-fn check_missing_doc_attrs(cx: &Context,
- id: Option<ast::NodeId>,
- attrs: &[ast::Attribute],
- sp: Span,
- desc: &'static str) {
- // If we're building a test harness, then warning about
- // documentation is probably not really relevant right now.
- if cx.tcx.sess.opts.test { return }
-
- // `#[doc(hidden)]` disables missing_doc check.
- if cx.is_doc_hidden { return }
-
- // Only check publicly-visible items, using the result from the privacy pass. It's an option so
- // the crate root can also use this function (it doesn't have a NodeId).
- match id {
- Some(ref id) if !cx.exported_items.contains(id) => return,
- _ => ()
- }
-
- let has_doc = attrs.iter().any(|a| {
- match a.node.value.node {
- ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
- _ => false
- }
- });
- if !has_doc {
- cx.span_lint(MissingDoc,
- sp,
- format!("missing documentation for {}",
- desc).as_slice());
- }
-}
-
-fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
- let desc = match it.node {
- ast::ItemFn(..) => "a function",
- ast::ItemMod(..) => "a module",
- ast::ItemEnum(..) => "an enum",
- ast::ItemStruct(..) => "a struct",
- ast::ItemTrait(..) => "a trait",
- _ => return
- };
- check_missing_doc_attrs(cx,
- Some(it.id),
- it.attrs.as_slice(),
- it.span,
- desc);
-}
-
-#[deriving(PartialEq)]
-enum MethodContext {
- TraitDefaultImpl,
- TraitImpl,
- PlainImpl
-}
-
-fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
- // If the method is an impl for a trait, don't doc.
- if method_context(cx, m) == TraitImpl { return; }
-
- // Otherwise, doc according to privacy. This will also check
- // doc for default methods defined on traits.
- check_missing_doc_attrs(cx,
- Some(m.id),
- m.attrs.as_slice(),
- m.span,
- "a method");
-}
-
-fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
- let did = ast::DefId {
- krate: ast::LOCAL_CRATE,
- node: m.id
- };
-
- match cx.tcx.methods.borrow().find_copy(&did) {
- None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
- Some(md) => {
- match md.container {
- ty::TraitContainer(..) => TraitDefaultImpl,
- ty::ImplContainer(cid) => {
- match ty::impl_trait_ref(cx.tcx, cid) {
- Some(..) => TraitImpl,
- None => PlainImpl
- }
- }
- }
- }
- }
-}
-
-fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
- check_missing_doc_attrs(cx,
- Some(tm.id),
- tm.attrs.as_slice(),
- tm.span,
- "a type method");
-}
-
-fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
- match sf.node.kind {
- ast::NamedField(_, vis) if vis == ast::Public =>
- check_missing_doc_attrs(cx,
- Some(cx.cur_struct_def_id),
- sf.node.attrs.as_slice(),
- sf.span,
- "a struct field"),
- _ => {}
- }
-}
-
-fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
- check_missing_doc_attrs(cx,
- Some(v.node.id),
- v.node.attrs.as_slice(),
- v.span,
- "a variant");
-}
-
-/// Checks for use of items with #[deprecated], #[experimental] and
-/// #[unstable] (or none of them) attributes.
-fn check_stability(cx: &Context, e: &ast::Expr) {
- let tcx = cx.tcx;
-
- let id = match e.node {
- ast::ExprPath(..) | ast::ExprStruct(..) => {
- match cx.tcx.def_map.borrow().find(&e.id) {
- Some(&def) => def.def_id(),
- None => return
- }
- }
- ast::ExprMethodCall(..) => {
- let method_call = typeck::MethodCall::expr(e.id);
- match tcx.method_map.borrow().find(&method_call) {
- Some(method) => {
- match method.origin {
- typeck::MethodStatic(def_id) => {
- // If this implements a trait method, get def_id
- // of the method inside trait definition.
- // Otherwise, use the current def_id (which refers
- // to the method inside impl).
- ty::trait_method_of_method(cx.tcx, def_id)
- .unwrap_or(def_id)
- }
- typeck::MethodParam(typeck::MethodParam {
- trait_id: trait_id,
- method_num: index,
- ..
- })
- | typeck::MethodObject(typeck::MethodObject {
- trait_id: trait_id,
- method_num: index,
- ..
- }) => ty::trait_method(cx.tcx, trait_id, index).def_id
- }
- }
- None => return
- }
- }
- _ => return
- };
-
- // stability attributes are promises made across crates; do not
- // check anything for crate-local usage.
- if ast_util::is_local(id) { return }
-
- let stability = tcx.stability.borrow_mut().lookup(&tcx.sess.cstore, id);
-
- let (lint, label) = match stability {
- // no stability attributes == Unstable
- None => (Unstable, "unmarked"),
- Some(attr::Stability { level: attr::Unstable, .. }) =>
- (Unstable, "unstable"),
- Some(attr::Stability { level: attr::Experimental, .. }) =>
- (Experimental, "experimental"),
- Some(attr::Stability { level: attr::Deprecated, .. }) =>
- (Deprecated, "deprecated"),
- _ => return
- };
-
- let msg = match stability {
- Some(attr::Stability { text: Some(ref s), .. }) => {
- format!("use of {} item: {}", label, *s)
- }
- _ => format!("use of {} item", label)
- };
-
- cx.span_lint(lint, e.span, msg.as_slice());
-}
-
-fn check_enum_variant_sizes(cx: &mut Context, it: &ast::Item) {
- match it.node {
- ast::ItemEnum(..) => {
- match cx.cur.find(&(VariantSizeDifference as uint)) {
- Some(&(lvl, src)) if lvl != Allow => {
- cx.node_levels.insert((it.id, VariantSizeDifference), (lvl, src));
- },
- _ => { }
- }
- },
- _ => { }
- }
-}
-
-impl<'a> Visitor<()> for Context<'a> {
- fn visit_item(&mut self, it: &ast::Item, _: ()) {
- self.with_lint_attrs(it.attrs.as_slice(), |cx| {
- check_enum_variant_sizes(cx, it);
- check_item_ctypes(cx, it);
- check_item_non_camel_case_types(cx, it);
- check_item_non_uppercase_statics(cx, it);
- check_heap_item(cx, it);
- check_missing_doc_item(cx, it);
- check_raw_ptr_deriving(cx, it);
-
- cx.visit_ids(|v| v.visit_item(it, ()));
-
- visit::walk_item(cx, it, ());
- })
- }
-
- fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
- self.with_lint_attrs(it.attrs.as_slice(), |cx| {
- visit::walk_foreign_item(cx, it, ());
- })
- }
-
- fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
- self.with_lint_attrs(i.attrs.as_slice(), |cx| {
- cx.visit_ids(|v| v.visit_view_item(i, ()));
-
- visit::walk_view_item(cx, i, ());
- })
- }
-
- fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
- check_pat_non_uppercase_statics(self, p);
- check_pat_uppercase_variable(self, p);
-
- visit::walk_pat(self, p, ());
- }
-
- fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
- match e.node {
- ast::ExprUnary(ast::UnNeg, expr) => {
- // propagate negation, if the negation itself isn't negated
- if self.negated_expr_id != e.id {
- self.negated_expr_id = expr.id;
- }
- },
- ast::ExprParen(expr) => if self.negated_expr_id == e.id {
- self.negated_expr_id = expr.id
- },
- ast::ExprMatch(_, ref arms) => {
- for a in arms.iter() {
- check_unused_mut_pat(self, a.pats.as_slice());
- }
- },
- _ => ()
- };
-
- check_while_true_expr(self, e);
- check_stability(self, e);
- check_unnecessary_parens_expr(self, e);
- check_unused_unsafe(self, e);
- check_unsafe_block(self, e);
- check_unnecessary_allocation(self, e);
- check_heap_expr(self, e);
-
- check_type_limits(self, e);
- check_unused_casts(self, e);
-
- visit::walk_expr(self, e, ());
- }
-
- fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
- check_path_statement(self, s);
- check_unused_result(self, s);
- check_unnecessary_parens_stmt(self, s);
-
- match s.node {
- ast::StmtDecl(d, _) => {
- match d.node {
- ast::DeclLocal(l) => {
- check_unused_mut_pat(self, &[l.pat]);
- },
- _ => {}
- }
- },
- _ => {}
- }
-
- visit::walk_stmt(self, s, ());
- }
-
- fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
- body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
- let recurse = |this: &mut Context| {
- visit::walk_fn(this, fk, decl, body, span, ());
- };
-
- for a in decl.inputs.iter(){
- check_unused_mut_pat(self, &[a.pat]);
- }
-
- match *fk {
- visit::FkMethod(ident, _, m) => {
- self.with_lint_attrs(m.attrs.as_slice(), |cx| {
- check_missing_doc_method(cx, m);
-
- match method_context(cx, m) {
- PlainImpl => check_snake_case(cx, "method", ident, span),
- TraitDefaultImpl => check_snake_case(cx, "trait method", ident, span),
- _ => (),
- }
-
- cx.visit_ids(|v| {
- v.visit_fn(fk, decl, body, span, id, ());
- });
- recurse(cx);
- })
- },
- visit::FkItemFn(ident, _, _, _) => {
- check_snake_case(self, "function", ident, span);
- recurse(self);
- }
- _ => recurse(self),
- }
- }
-
- fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
- self.with_lint_attrs(t.attrs.as_slice(), |cx| {
- check_missing_doc_ty_method(cx, t);
- check_snake_case(cx, "trait method", t.ident, t.span);
-
- visit::walk_ty_method(cx, t, ());
- })
- }
-
- fn visit_struct_def(&mut self,
- s: &ast::StructDef,
- _: ast::Ident,
- _: &ast::Generics,
- id: ast::NodeId,
- _: ()) {
- check_struct_uppercase_variable(self, s);
-
- let old_id = self.cur_struct_def_id;
- self.cur_struct_def_id = id;
- visit::walk_struct_def(self, s, ());
- self.cur_struct_def_id = old_id;
- }
-
- fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
- self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
- check_missing_doc_struct_field(cx, s);
-
- visit::walk_struct_field(cx, s, ());
- })
- }
-
- fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
- self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
- check_missing_doc_variant(cx, v);
-
- visit::walk_variant(cx, v, g, ());
- })
- }
-
- // FIXME(#10894) should continue recursing
- fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
-
- fn visit_attribute(&mut self, attr: &ast::Attribute, _: ()) {
- check_unused_attribute(self, attr);
- }
-}
-
-impl<'a> IdVisitingOperation for Context<'a> {
- fn visit_id(&self, id: ast::NodeId) {
- match self.tcx.sess.lints.borrow_mut().pop(&id) {
- None => {}
- Some(l) => {
- for (lint, span, msg) in l.move_iter() {
- self.span_lint(lint, span, msg.as_slice())
- }
- }
- }
- }
-}
-
-pub fn check_crate(tcx: &ty::ctxt,
- exported_items: &privacy::ExportedItems,
- krate: &ast::Crate) {
- let mut cx = Context {
- dict: get_lint_dict(),
- cur: SmallIntMap::new(),
- tcx: tcx,
- exported_items: exported_items,
- cur_struct_def_id: -1,
- is_doc_hidden: false,
- lint_stack: Vec::new(),
- negated_expr_id: -1,
- checked_raw_pointers: NodeSet::new(),
- node_levels: HashMap::new(),
- };
-
- // Install default lint levels, followed by the command line levels, and
- // then actually visit the whole crate.
- for (_, spec) in cx.dict.iter() {
- if spec.default != Allow {
- cx.cur.insert(spec.lint as uint, (spec.default, Default));
- }
- }
- for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
- cx.set_level(lint, level, CommandLine);
- }
- cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
- cx.visit_id(ast::CRATE_NODE_ID);
- cx.visit_ids(|v| {
- v.visited_outermost = true;
- visit::walk_crate(v, krate, ());
- });
-
- // since the root module isn't visited as an item (because it isn't an item), warn for it
- // here.
- check_missing_doc_attrs(cx,
- None,
- krate.attrs.as_slice(),
- krate.span,
- "crate");
-
- visit::walk_crate(cx, krate, ());
- });
-
- // If we missed any lints added to the session, then there's a bug somewhere
- // in the iteration code.
- for (id, v) in tcx.sess.lints.borrow().iter() {
- for &(lint, span, ref msg) in v.iter() {
- tcx.sess.span_bug(span, format!("unprocessed lint {} at {}: {}",
- lint, tcx.map.node_to_str(*id), *msg).as_slice())
- }
- }
-
- tcx.sess.abort_if_errors();
- *tcx.node_lint_levels.borrow_mut() = cx.node_levels;
-}
use middle::def::*;
use middle::freevars;
-use middle::lint::{UnusedVariable, DeadAssignment};
use middle::mem_categorization::Typer;
use middle::pat_util;
use middle::ty;
+use lint;
use util::nodemap::NodeMap;
use std::fmt;
};
if is_assigned {
- self.ir.tcx.sess.add_lint(UnusedVariable, id, sp,
+ self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
format!("variable `{}` is assigned to, but never used",
*name));
} else {
- self.ir.tcx.sess.add_lint(UnusedVariable, id, sp,
+ self.ir.tcx.sess.add_lint(lint::builtin::UNUSED_VARIABLE, id, sp,
format!("unused variable: `{}`", *name));
}
}
if self.live_on_exit(ln, var).is_none() {
let r = self.should_warn(var);
for name in r.iter() {
- self.ir.tcx.sess.add_lint(DeadAssignment, id, sp,
+ self.ir.tcx.sess.add_lint(lint::builtin::DEAD_ASSIGNMENT, id, sp,
format!("value assigned to `{}` is never read", *name));
}
}
use metadata::csearch;
use middle::def;
-use middle::lint;
+use lint;
use middle::resolve;
use middle::ty;
use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam};
ast::TyPath(ref p, _, path_id) => {
if self.path_is_private_type(path_id) {
self.tcx.sess.add_lint(
- lint::VisiblePrivateTypes,
+ lint::builtin::VISIBLE_PRIVATE_TYPES,
path_id, p.span,
"private type in exported type \
signature".to_string());
use metadata::decoder::{DefLike, DlDef, DlField, DlImpl};
use middle::def::*;
use middle::lang_items::LanguageItems;
-use middle::lint::{UnnecessaryQualification, UnusedImports};
use middle::pat_util::pat_bindings;
use middle::subst::{ParamSpace, FnSpace, TypeSpace};
+use lint;
use util::nodemap::{NodeMap, DefIdSet, FnvHashMap};
use syntax::ast::*;
/// Resolves all imports for the crate. This method performs the fixed-
/// point iteration.
fn resolve_imports(&mut self) {
- let mut i = 0;
+ let mut i = 0u;
let mut prev_unresolved_imports = 0;
loop {
debug!("(resolving imports) iteration {}, {} imports left",
match (def, unqualified_def) {
(Some((d, _)), Some((ud, _))) if d == ud => {
self.session
- .add_lint(UnnecessaryQualification,
+ .add_lint(lint::builtin::UNNECESSARY_QUALIFICATION,
id,
path.span,
"unnecessary qualification".to_string());
if !self.used_imports.contains(&(id, TypeNS)) &&
!self.used_imports.contains(&(id, ValueNS)) {
self.session
- .add_lint(UnusedImports,
+ .add_lint(lint::builtin::UNUSED_IMPORTS,
id,
p.span,
"unused import".to_string());
if !self.used_imports.contains(&(id, TypeNS)) &&
!self.used_imports.contains(&(id, ValueNS)) {
- self.session.add_lint(UnusedImports,
+ self.session.add_lint(lint::builtin::UNUSED_IMPORTS,
id,
span,
"unused import".to_string());
self.check_and_record(Variable,
span,
sub_span,
- svec!(id, name, qualname, value, typ, 0));
+ svec!(id, name, qualname, value, typ, 0u));
}
// formal parameters
self.check_and_record(Variable,
span,
sub_span,
- svec!(id, name, qualname, "", typ, 0));
+ svec!(id, name, qualname, "", typ, 0u));
}
// value is the initialising expression of the static if it is not mut, otherwise "".
self.check_and_record(Inheritance,
span,
sub_span,
- svec!(base_id.node, base_id.krate, deriv_id, 0));
+ svec!(base_id.node,
+ base_id.krate,
+ deriv_id,
+ 0u));
}
pub fn fn_call_str(&mut self,
self.record_with_span(ModRef,
span,
sub_span,
- svec!(0, 0, qualname, parent));
+ svec!(0u, 0u, qualname, parent));
}
pub fn typedef_str(&mut self,
self.record_with_span(TypeRef,
span,
sub_span,
- svec!(0, 0, qualname, 0));
+ svec!(0u, 0u, qualname, 0u));
}
// A slightly generic function for a reference to an item of any kind.
assert_eq!(val_ty(ptr), llty.ptr_to());
let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
assert!(bits <= 64);
+ let bits = bits as uint;
let mask = (-1u64 >> (64 - bits)) as Disr;
if (max + 1) & mask == min & mask {
// i.e., if the range is everything. The lo==hi case would be
use lib::llvm::{llvm, Vector};
use lib;
use metadata::{csearch, encoder, loader};
-use middle::lint;
+use lint;
use middle::astencode;
use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
use middle::weak_lang_items;
fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
- let (lvl, src) = ccx.tcx.node_lint_levels.borrow()
- .find(&(id, lint::VariantSizeDifference))
- .map_or((lint::Allow, lint::Default), |&(lvl,src)| (lvl, src));
-
- if lvl != lint::Allow {
- let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
- match *avar {
- adt::General(_, ref variants) => {
- for var in variants.iter() {
- let mut size = 0;
- for field in var.fields.iter().skip(1) {
- // skip the discriminant
- size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
- }
- sizes.push(size);
- }
- },
- _ => { /* its size is either constant or unimportant */ }
- }
+ let levels = ccx.tcx.node_lint_levels.borrow();
+ let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
+ let lvlsrc = match levels.find(&(id, lint_id)) {
+ None | Some(&(lint::Allow, _)) => return,
+ Some(&lvlsrc) => lvlsrc,
+ };
- let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
- |(l, s, li), (idx, &size)|
- if size > l {
- (size, l, idx)
- } else if size > s {
- (l, size, li)
- } else {
- (l, s, li)
+ let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
+ match *avar {
+ adt::General(_, ref variants) => {
+ for var in variants.iter() {
+ let mut size = 0;
+ for field in var.fields.iter().skip(1) {
+ // skip the discriminant
+ size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
}
- );
+ sizes.push(size);
+ }
+ },
+ _ => { /* its size is either constant or unimportant */ }
+ }
- // we only warn if the largest variant is at least thrice as large as
- // the second-largest.
- if largest > slargest * 3 && slargest > 0 {
- lint::emit_lint(lvl, src,
+ let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
+ |(l, s, li), (idx, &size)|
+ if size > l {
+ (size, l, idx)
+ } else if size > s {
+ (l, size, li)
+ } else {
+ (l, s, li)
+ }
+ );
+
+ // we only warn if the largest variant is at least thrice as large as
+ // the second-largest.
+ if largest > slargest * 3 && slargest > 0 {
+ // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
+ // pass for the latter already ran.
+ lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
+ lvlsrc, Some(sp),
format!("enum variant is more than three times larger \
- ({} bytes) than the next largest (ignoring padding)",
- largest).as_slice(),
- sp, lint::lint_to_str(lint::VariantSizeDifference), ccx.tcx());
+ ({} bytes) than the next largest (ignoring padding)",
+ largest).as_slice());
- ccx.sess().span_note(enum_def.variants.get(largest_index).span,
- "this variant is the largest");
- }
+ ccx.sess().span_note(enum_def.variants.get(largest_index).span,
+ "this variant is the largest");
}
}
let null_variant_index = (1 - non_null_variant_index) as uint;
let null_variant_ident = self.variants.get(null_variant_index).name;
let null_variant_name = token::get_ident(null_variant_ident);
- let union_member_name = format!("RUST$ENCODED$ENUM${}${}", 0, null_variant_name);
+ let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
+ 0u,
+ null_variant_name);
// Finally create the (singleton) list of descriptions of union
// members.
match debug_location {
KnownLocation { scope, line, .. } => {
- let col = 0; // Always set the column to zero like Clang and GCC
+ let col = 0u; // Always set the column to zero like Clang and GCC
debug!("setting debug location to {} {}", line, col);
let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32), scope, ptr::null()];
unsafe {
controlflow::trans_loop(bcx, expr.id, &**body)
}
ast::ExprAssign(ref dst, ref src) => {
- let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
//
// We could avoid this intermediary with some analysis
// to determine whether `dst` may possibly own `src`.
+ let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
let src_datum = unpack_datum!(
bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
bcx = glue::drop_ty(bcx, dst_datum.val, dst_datum.ty);
src_datum.store_to(bcx, dst_datum.val)
} else {
- src_datum.store_to(bcx, dst_datum.val)
+ trans_into(bcx, &**src, SaveIn(dst_datum.to_llref()))
}
}
ast::ExprAssignOp(op, ref dst, ref src) => {
use driver::session::Session;
use metadata::csearch;
use mc = middle::mem_categorization;
-use middle::lint;
+use lint;
use middle::const_eval;
use middle::def;
use middle::dependency_format;
pub dependency_formats: RefCell<dependency_format::Dependencies>,
- pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::Lint),
- (lint::Level, lint::LintSource)>>,
+ pub node_lint_levels: RefCell<HashMap<(ast::NodeId, lint::LintId),
+ lint::LevelSource>>,
/// The types that must be asserted to be the same size for `transmute`
/// to be valid. We gather up these restrictions in the intrinsicck pass
repeat count but found binary array");
return 0;
}
+ const_eval::const_nil => {
+ tcx.ty_ctxt().sess.span_err(count_expr.span,
+ "expected positive integer for \
+ repeat count but found ()");
+ return 0;
+ }
},
Err(..) => {
tcx.ty_ctxt().sess.span_err(count_expr.span,
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) {
- resolve_type(fcx.infcx(), expected,
+ resolve_type(fcx.infcx(),
+ None,
+ expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {
use middle::const_eval;
use middle::def;
-use middle::lint::UnreachableCode;
use middle::pat_util::pat_id_map;
use middle::pat_util;
use middle::subst;
use middle::typeck::{MethodCall, MethodMap};
use middle::typeck::{TypeAndSubsts};
use middle::lang_items::TypeIdLangItem;
+use lint;
use util::common::{block_query, indenter, loop_query};
use util::ppaux;
use util::ppaux::{UserString, Repr};
upvar_borrow_map: RefCell<ty::UpvarBorrowMap>,
}
+/// When type-checking an expression, we propagate downward
+/// whatever type hint we are able in the form of an `Expectation`.
+enum Expectation {
+ /// We know nothing about what type this expression should have.
+ NoExpectation,
+
+ /// This expression should have the type given (or some subtype)
+ ExpectHasType(ty::t),
+
+ /// This expression will be cast to the `ty::t`
+ ExpectCastableToType(ty::t),
+}
+
#[deriving(Clone)]
pub struct FnStyleState {
pub def: ast::NodeId,
visit.visit_block(body, ());
}
- check_block_with_expected(&fcx, body, Some(ret_ty));
+ check_block_with_expected(&fcx, body, ExpectHasType(ret_ty));
// We unify the tail expr's type with the
// function result type, if there is a tail expr.
}
// AST fragment checking
-pub fn check_lit(fcx: &FnCtxt, lit: &ast::Lit) -> ty::t {
+fn check_lit(fcx: &FnCtxt,
+ lit: &ast::Lit,
+ expected: Expectation)
+ -> ty::t
+{
let tcx = fcx.ccx.tcx;
match lit.node {
ast::LitInt(_, t) => ty::mk_mach_int(t),
ast::LitUint(_, t) => ty::mk_mach_uint(t),
ast::LitIntUnsuffixed(_) => {
- // An unsuffixed integer literal could have any integral type,
- // so we create an integral type variable for it.
- ty::mk_int_var(tcx, fcx.infcx().next_int_var_id())
+ let opt_ty = expected.map_to_option(fcx, |sty| {
+ match *sty {
+ ty::ty_int(i) => Some(ty::mk_mach_int(i)),
+ ty::ty_uint(i) => Some(ty::mk_mach_uint(i)),
+ ty::ty_char => Some(ty::mk_mach_uint(ast::TyU8)),
+ ty::ty_ptr(..) => Some(ty::mk_mach_uint(ast::TyU)),
+ ty::ty_bare_fn(..) => Some(ty::mk_mach_uint(ast::TyU)),
+ _ => None
+ }
+ });
+ opt_ty.unwrap_or_else(
+ || ty::mk_int_var(tcx, fcx.infcx().next_int_var_id()))
}
ast::LitFloat(_, t) => ty::mk_mach_float(t),
ast::LitFloatUnsuffixed(_) => {
- // An unsuffixed floating point literal could have any floating point
- // type, so we create a floating point type variable for it.
- ty::mk_float_var(tcx, fcx.infcx().next_float_var_id())
+ let opt_ty = expected.map_to_option(fcx, |sty| {
+ match *sty {
+ ty::ty_float(i) => Some(ty::mk_mach_float(i)),
+ _ => None
+ }
+ });
+ opt_ty.unwrap_or_else(
+ || ty::mk_float_var(tcx, fcx.infcx().next_float_var_id()))
}
ast::LitNil => ty::mk_nil(),
ast::LitBool(_) => ty::mk_bool()
}
}
-pub fn check_expr_has_type(
- fcx: &FnCtxt, expr: &ast::Expr,
- expected: ty::t) {
- check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || {
- demand::suptype(fcx, expr.span, expected, fcx.expr_ty(expr));
- });
+pub fn check_expr_has_type(fcx: &FnCtxt,
+ expr: &ast::Expr,
+ expected: ty::t) {
+ check_expr_with_unifier(
+ fcx, expr, ExpectHasType(expected), NoPreference,
+ || demand::suptype(fcx, expr.span, expected, fcx.expr_ty(expr)));
}
-fn check_expr_coercable_to_type(fcx: &FnCtxt, expr: &ast::Expr, expected: ty::t) {
- check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || {
- demand::coerce(fcx, expr.span, expected, expr)
- });
+fn check_expr_coercable_to_type(fcx: &FnCtxt,
+ expr: &ast::Expr,
+ expected: ty::t) {
+ check_expr_with_unifier(
+ fcx, expr, ExpectHasType(expected), NoPreference,
+ || demand::coerce(fcx, expr.span, expected, expr));
}
fn check_expr_with_hint(fcx: &FnCtxt, expr: &ast::Expr, expected: ty::t) {
- check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || ())
+ check_expr_with_unifier(
+ fcx, expr, ExpectHasType(expected), NoPreference,
+ || ())
}
-fn check_expr_with_opt_hint(fcx: &FnCtxt, expr: &ast::Expr,
- expected: Option<ty::t>) {
- check_expr_with_unifier(fcx, expr, expected, NoPreference, || ())
+fn check_expr_with_expectation(fcx: &FnCtxt,
+ expr: &ast::Expr,
+ expected: Expectation) {
+ check_expr_with_unifier(
+ fcx, expr, expected, NoPreference,
+ || ())
}
-fn check_expr_with_opt_hint_and_lvalue_pref(fcx: &FnCtxt,
+fn check_expr_with_expectation_and_lvalue_pref(fcx: &FnCtxt,
expr: &ast::Expr,
- expected: Option<ty::t>,
- lvalue_pref: LvaluePreference) {
+ expected: Expectation,
+ lvalue_pref: LvaluePreference)
+{
check_expr_with_unifier(fcx, expr, expected, lvalue_pref, || ())
}
fn check_expr(fcx: &FnCtxt, expr: &ast::Expr) {
- check_expr_with_unifier(fcx, expr, None, NoPreference, || ())
+ check_expr_with_unifier(fcx, expr, NoExpectation, NoPreference, || ())
}
fn check_expr_with_lvalue_pref(fcx: &FnCtxt, expr: &ast::Expr,
lvalue_pref: LvaluePreference) {
- check_expr_with_unifier(fcx, expr, None, lvalue_pref, || ())
+ check_expr_with_unifier(fcx, expr, NoExpectation, lvalue_pref, || ())
}
/// `ty_bot`, so avoid that when err and bot need to be handled differently.
fn check_expr_with_unifier(fcx: &FnCtxt,
expr: &ast::Expr,
- expected: Option<ty::t>,
+ expected: Expectation,
lvalue_pref: LvaluePreference,
- unifier: ||) {
+ unifier: ||)
+{
debug!(">> typechecking");
// A generic function for doing all of the checking for call expressions
opt_else_expr: Option<Gc<ast::Expr>>,
id: ast::NodeId,
sp: Span,
- expected: Option<ty::t>) {
+ expected: Expectation) {
check_expr_has_type(fcx, cond_expr, ty::mk_bool());
let branches_ty = match opt_else_expr {
Some(ref else_expr) => {
+ // Disregard "castable to" expectations because they
+ // can lead us astray. Consider for example `if cond
+ // {22} else {c} as u8` -- if we propagate the
+ // "castable to u8" constraint to 22, it will pick the
+ // type 22u8, which is overly constrained (c might not
+ // be a u8). In effect, the problem is that the
+ // "castable to" expectation is not the tightest thing
+ // we can say, so we want to drop it in this case.
+ // The tightest thing we can say is "must unify with
+ // else branch". Note that in the case of a "has type"
+ // constraint, this limitation does not hold.
+ let expected = expected.only_has_type();
+
check_block_with_expected(fcx, then_blk, expected);
let then_ty = fcx.node_ty(then_blk.id);
- check_expr_with_opt_hint(fcx, &**else_expr, expected);
+ check_expr_with_expectation(fcx, &**else_expr, expected);
let else_ty = fcx.expr_ty(&**else_expr);
infer::common_supertype(fcx.infcx(),
infer::IfExpression(sp),
fcx.expr_ty(&*lhs));
if ty::type_is_integral(lhs_t) && ast_util::is_shift_binop(op) {
- // Shift is a special case: rhs can be any integral type
- check_expr(fcx, &*rhs);
- let rhs_t = fcx.expr_ty(&*rhs);
- require_integral(fcx, rhs.span, rhs_t);
+ // Shift is a special case: rhs must be uint, no matter what lhs is
+ check_expr_has_type(fcx, rhs, ty::mk_uint());
fcx.write_ty(expr.id, lhs_t);
return;
}
})
}
- // Resolves `expected` by a single level if it is a variable and passes it
- // through the `unpack` function. It there is no expected type or
- // resolution is not possible (e.g., no constraints yet present), just
- // returns `none`.
- fn unpack_expected<O>(
- fcx: &FnCtxt,
- expected: Option<ty::t>,
- unpack: |&ty::sty| -> Option<O>)
- -> Option<O> {
- match expected {
- Some(t) => {
- match resolve_type(fcx.infcx(), t, force_tvar) {
- Ok(t) => unpack(&ty::get(t).sty),
- _ => None
- }
- }
- _ => None
- }
- }
-
fn check_expr_fn(fcx: &FnCtxt,
expr: &ast::Expr,
store: ty::TraitStore,
decl: &ast::FnDecl,
body: ast::P<ast::Block>,
- expected: Option<ty::t>) {
+ expected: Expectation) {
let tcx = fcx.ccx.tcx;
// Find the expected input/output types (if any). Substitute
// fresh bound regions for any bound regions we find in the
// expected types so as to avoid capture.
- let expected_sty = unpack_expected(fcx,
- expected,
- |x| Some((*x).clone()));
+ let expected_sty = expected.map_to_option(fcx, |x| Some((*x).clone()));
let (expected_sig,
expected_onceness,
expected_bounds) = {
}
}
- ast::ExprLit(ref lit) => {
- let typ = check_lit(fcx, &**lit);
+ ast::ExprLit(lit) => {
+ let typ = check_lit(fcx, lit, expected);
fcx.write_ty(id, typ);
}
ast::ExprBinary(op, ref lhs, ref rhs) => {
}
}
ast::ExprUnary(unop, ref oprnd) => {
- let exp_inner = unpack_expected(fcx, expected, |sty| {
+ let expected = expected.only_has_type();
+ let expected_inner = expected.map(fcx, |sty| {
match unop {
ast::UnBox | ast::UnUniq => match *sty {
- ty::ty_box(ty) | ty::ty_uniq(ty) => Some(ty),
- _ => None
+ ty::ty_box(ty) | ty::ty_uniq(ty) => {
+ ExpectHasType(ty)
+ }
+ _ => {
+ NoExpectation
+ }
},
- ast::UnNot | ast::UnNeg => expected,
- ast::UnDeref => None
+ ast::UnNot | ast::UnNeg => {
+ expected
+ }
+ ast::UnDeref => {
+ NoExpectation
+ }
}
});
let lvalue_pref = match unop {
ast::UnDeref => lvalue_pref,
_ => NoPreference
};
- check_expr_with_opt_hint_and_lvalue_pref(fcx, &**oprnd, exp_inner, lvalue_pref);
+ check_expr_with_expectation_and_lvalue_pref(
+ fcx, &**oprnd, expected_inner, lvalue_pref);
let mut oprnd_t = fcx.expr_ty(&**oprnd);
if !ty::type_is_error(oprnd_t) && !ty::type_is_bot(oprnd_t) {
match unop {
fcx.write_ty(id, oprnd_t);
}
ast::ExprAddrOf(mutbl, ref oprnd) => {
- let hint = unpack_expected(
- fcx, expected,
- |sty| match *sty { ty::ty_rptr(_, ref mt) => Some(mt.ty),
- _ => None });
+ let expected = expected.only_has_type();
+ let hint = expected.map(fcx, |sty| {
+ match *sty { ty::ty_rptr(_, ref mt) => ExpectHasType(mt.ty),
+ _ => NoExpectation }
+ });
let lvalue_pref = match mutbl {
ast::MutMutable => PreferMutLvalue,
ast::MutImmutable => NoPreference
};
- check_expr_with_opt_hint_and_lvalue_pref(fcx, &**oprnd, hint, lvalue_pref);
+ check_expr_with_expectation_and_lvalue_pref(fcx,
+ &**oprnd,
+ hint,
+ lvalue_pref);
// Note: at this point, we cannot say what the best lifetime
// is to use for resulting pointer. We want to use the
}
fcx.write_bot(id);
}
- ast::ExprParen(ref a) => {
- check_expr_with_opt_hint_and_lvalue_pref(fcx, &**a, expected, lvalue_pref);
- fcx.write_ty(id, fcx.expr_ty(&**a));
+ ast::ExprParen(a) => {
+ check_expr_with_expectation_and_lvalue_pref(fcx, a, expected, lvalue_pref);
+ fcx.write_ty(id, fcx.expr_ty(a));
}
ast::ExprAssign(ref lhs, ref rhs) => {
check_expr_with_lvalue_pref(fcx, &**lhs, PreferMutLvalue);
fcx.write_bot(id);
}
}
- ast::ExprCast(ref e, ref t) => {
- check_expr(fcx, &**e);
- let t_1 = fcx.to_ty(&**t);
- let t_e = fcx.expr_ty(&**e);
-
- debug!("t_1={}", fcx.infcx().ty_to_str(t_1));
- debug!("t_e={}", fcx.infcx().ty_to_str(t_e));
-
- if ty::type_is_error(t_e) {
- fcx.write_error(id);
- }
- else if ty::type_is_bot(t_e) {
- fcx.write_bot(id);
- }
- else {
- match ty::get(t_1).sty {
- // This will be looked up later on
- _ if ty::type_is_trait(t_1) => {},
-
- _ => {
- let t_1 = structurally_resolved_type(fcx, e.span, t_1);
- let t_e = structurally_resolved_type(fcx, e.span, t_e);
-
- if ty::type_is_nil(t_e) {
- fcx.type_error_message(expr.span, |actual| {
- format!("cast from nil: `{}` as `{}`",
- actual,
- fcx.infcx().ty_to_str(t_1))
- }, t_e, None);
- } else if ty::type_is_nil(t_1) {
- fcx.type_error_message(expr.span, |actual| {
- format!("cast to nil: `{}` as `{}`",
- actual,
- fcx.infcx().ty_to_str(t_1))
- }, t_e, None);
- }
-
- let t_1_is_scalar = ty::type_is_scalar(t_1);
- let t_1_is_char = ty::type_is_char(t_1);
- let t_1_is_bare_fn = ty::type_is_bare_fn(t_1);
- let t_1_is_float = ty::type_is_floating_point(t_1);
-
- // casts to scalars other than `char` and `bare fn` are trivial
- let t_1_is_trivial = t_1_is_scalar && !t_1_is_char && !t_1_is_bare_fn;
- if ty::type_is_c_like_enum(fcx.tcx(), t_e) && t_1_is_trivial {
- if t_1_is_float {
- fcx.type_error_message(expr.span, |actual| {
- format!("illegal cast; cast through an \
- integer first: `{}` as `{}`",
- actual,
- fcx.infcx().ty_to_str(t_1))
- }, t_e, None);
- }
- // casts from C-like enums are allowed
- } else if t_1_is_char {
- let t_e = fcx.infcx().resolve_type_vars_if_possible(t_e);
- if ty::get(t_e).sty != ty::ty_uint(ast::TyU8) {
- fcx.type_error_message(expr.span, |actual| {
- format!("only `u8` can be cast as \
- `char`, not `{}`", actual)
- }, t_e, None);
- }
- } else if ty::get(t_1).sty == ty::ty_bool {
- fcx.tcx()
- .sess
- .span_err(expr.span,
- "cannot cast as `bool`, compare with \
- zero instead");
- } else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) {
- fn is_vec(t: ty::t) -> bool {
- match ty::get(t).sty {
- ty::ty_vec(..) => true,
- ty::ty_ptr(ty::mt{ty: t, ..}) | ty::ty_rptr(_, ty::mt{ty: t, ..}) |
- ty::ty_box(t) | ty::ty_uniq(t) => match ty::get(t).sty {
- ty::ty_vec(_, None) => true,
- _ => false,
- },
- _ => false
- }
- }
- fn types_compatible(fcx: &FnCtxt, sp: Span,
- t1: ty::t, t2: ty::t) -> bool {
- if !is_vec(t1) {
- false
- } else {
- let el = ty::sequence_element_type(fcx.tcx(),
- t1);
- infer::mk_eqty(fcx.infcx(), false,
- infer::Misc(sp), el, t2).is_ok()
- }
- }
-
- // Due to the limitations of LLVM global constants,
- // region pointers end up pointing at copies of
- // vector elements instead of the original values.
- // To allow unsafe pointers to work correctly, we
- // need to special-case obtaining an unsafe pointer
- // from a region pointer to a vector.
-
- /* this cast is only allowed from &[T] to *T or
- &T to *T. */
- match (&ty::get(t_e).sty, &ty::get(t_1).sty) {
- (&ty::ty_rptr(_, ty::mt { ty: mt1, mutbl: ast::MutImmutable }),
- &ty::ty_ptr(ty::mt { ty: mt2, mutbl: ast::MutImmutable }))
- if types_compatible(fcx, e.span, mt1, mt2) => {
- /* this case is allowed */
- }
- _ => {
- demand::coerce(fcx, e.span, t_1, &**e);
- }
- }
- } else if !(ty::type_is_scalar(t_e) && t_1_is_trivial) {
- /*
- If more type combinations should be supported than are
- supported here, then file an enhancement issue and
- record the issue number in this comment.
- */
- fcx.type_error_message(expr.span, |actual| {
- format!("non-scalar cast: `{}` as `{}`",
- actual,
- fcx.infcx().ty_to_str(t_1))
- }, t_e, None);
- }
- }
- }
- fcx.write_ty(id, t_1);
- }
+ ast::ExprCast(expr_from, t) => {
+ let ty_to = fcx.to_ty(t);
+ debug!("ExprCast ty_to={}", fcx.infcx().ty_to_str(ty_to));
+ check_cast(fcx, expr_from, ty_to);
+ fcx.write_ty(id, ty_to);
}
ast::ExprVec(ref args) => {
let t: ty::t = fcx.infcx().next_ty_var();
fcx.write_ty(id, typ);
}
ast::ExprRepeat(ref element, ref count_expr) => {
- check_expr_with_hint(fcx, &**count_expr, ty::mk_uint());
+ check_expr_has_type(fcx, &**count_expr, ty::mk_uint());
let count = ty::eval_repeat_count(fcx, &**count_expr);
let t: ty::t = fcx.infcx().next_ty_var();
check_expr_has_type(fcx, &**element, t);
}
}
ast::ExprTup(ref elts) => {
- let flds = unpack_expected(fcx, expected, |sty| {
+ let expected = expected.only_has_type();
+ let flds = expected.map_to_option(fcx, |sty| {
match *sty {
ty::ty_tup(ref flds) => Some((*flds).clone()),
_ => None
let elt_ts = elts.iter().enumerate().map(|(i, e)| {
let opt_hint = match flds {
- Some(ref fs) if i < fs.len() => Some(*fs.get(i)),
- _ => None
+ Some(ref fs) if i < fs.len() => ExpectHasType(*fs.get(i)),
+ _ => NoExpectation
};
- check_expr_with_opt_hint(fcx, &**e, opt_hint);
- let t = fcx.expr_ty(&**e);
+ check_expr_with_expectation(fcx, *e, opt_hint);
+ let t = fcx.expr_ty(*e);
err_field = err_field || ty::type_is_error(t);
bot_field = bot_field || ty::type_is_bot(t);
t
syntax::print::pprust::expr_to_str(expr));
debug!("... {}, expected is {}",
ppaux::ty_to_str(tcx, fcx.expr_ty(expr)),
- match expected {
- Some(t) => ppaux::ty_to_str(tcx, t),
- _ => "empty".to_string()
- });
+ expected.repr(tcx))
unifier();
}
+impl Expectation {
+ fn only_has_type(self) -> Expectation {
+ match self {
+ NoExpectation | ExpectCastableToType(..) => NoExpectation,
+ ExpectHasType(t) => ExpectHasType(t)
+ }
+ }
+
+ // Resolves `expected` by a single level if it is a variable. If
+ // there is no expected type or resolution is not possible (e.g.,
+ // no constraints yet present), just returns `None`.
+ fn resolve(self, fcx: &FnCtxt) -> Expectation {
+ match self {
+ NoExpectation => {
+ NoExpectation
+ }
+ ExpectCastableToType(t) => {
+ ExpectCastableToType(
+ fcx.infcx().resolve_type_vars_if_possible(t))
+ }
+ ExpectHasType(t) => {
+ ExpectHasType(
+ fcx.infcx().resolve_type_vars_if_possible(t))
+ }
+ }
+ }
+
+ fn map(self, fcx: &FnCtxt, unpack: |&ty::sty| -> Expectation) -> Expectation {
+ match self.resolve(fcx) {
+ NoExpectation => NoExpectation,
+ ExpectCastableToType(t) | ExpectHasType(t) => unpack(&ty::get(t).sty),
+ }
+ }
+
+ fn map_to_option<O>(self,
+ fcx: &FnCtxt,
+ unpack: |&ty::sty| -> Option<O>)
+ -> Option<O>
+ {
+ match self.resolve(fcx) {
+ NoExpectation => None,
+ ExpectCastableToType(t) | ExpectHasType(t) => unpack(&ty::get(t).sty),
+ }
+ }
+}
+
+impl Repr for Expectation {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
+ match *self {
+ NoExpectation => format!("NoExpectation"),
+ ExpectHasType(t) => format!("ExpectHasType({})",
+ t.repr(tcx)),
+ ExpectCastableToType(t) => format!("ExpectCastableToType({})",
+ t.repr(tcx)),
+ }
+ }
+}
+
+fn check_cast(fcx: &FnCtxt, expr_from: Gc<ast::Expr>, ty_to: ty::t) {
+ // Find the type of `expr_from`. Supply hints based on the type
+ // we are casting to, if appropriate.
+ let ty_to = structurally_resolved_type(fcx, expr_from.span, ty_to);
+ if ty::type_is_scalar(ty_to) {
+ // Supply the type as a hint so as to influence integer
+ // literals and other things that might care.
+ check_expr_with_hint(fcx, expr_from, ty_to)
+ } else {
+ check_expr(fcx, expr_from)
+ }
+ let ty_from = fcx.expr_ty(expr_from);
+
+ // Object creation is checked during the vtable phase.
+ if ty::type_is_trait(ty_to) {
+ check_expr(fcx, expr_from);
+ return;
+ }
+
+ let ty_from = fcx.infcx().resolve_type_vars_if_possible(ty_from);
+
+ if ty::type_is_nil(ty_from) {
+ fcx.type_error_message(expr_from.span, |actual| {
+ format!("cast from nil: `{}` as `{}`", actual,
+ fcx.infcx().ty_to_str(ty_to))
+ }, ty_from, None);
+ return;
+ }
+
+ if ty::type_is_nil(ty_to) {
+ fcx.type_error_message(expr_from.span, |actual| {
+ format!("cast to nil: `{}` as `{}`", actual,
+ fcx.infcx().ty_to_str(ty_to))
+ }, ty_from, None);
+ return;
+ }
+
+ let t_e = structurally_resolved_type(fcx, expr_from.span, ty_from);
+ let t_1 = structurally_resolved_type(fcx, expr_from.span, ty_to);
+
+ let to_is_scalar = ty::type_is_scalar(t_1);
+ let to_is_float = ty::type_is_floating_point(t_1);
+ let to_is_char = ty::type_is_char(t_1);
+ let to_is_bare_fn = ty::type_is_bare_fn(t_1);
+
+ // casts to scalars other than `char` and `bare fn` are trivial
+ let to_is_trivial = to_is_scalar &&
+ !to_is_char && !to_is_bare_fn;
+
+ if ty::type_is_c_like_enum(fcx.tcx(), t_e) && to_is_trivial {
+ if to_is_float {
+ fcx.type_error_message(expr_from.span, |actual| {
+ format!("illegal cast; cast through an integer first: `{}` \
+ as `{}`",
+ actual,
+ fcx.infcx().ty_to_str(t_1))
+ }, ty_from, None);
+ }
+ // casts from C-like enums are allowed
+ } else if to_is_char {
+ if ty::get(ty_from).sty != ty::ty_uint(ast::TyU8) {
+ fcx.type_error_message(expr_from.span, |actual| {
+ format!("only `u8` can be cast as `char`, not `{}`", actual)
+ }, ty_from, None);
+ }
+ } else if ty::type_is_bool(t_1) {
+ fcx.tcx().sess.span_err(expr_from.span,
+ "cannot cast as `bool`, compare with zero instead");
+ } else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) {
+ fn is_vec(t: ty::t) -> bool {
+ match ty::get(t).sty {
+ ty::ty_vec(..) => true,
+ ty::ty_ptr(ty::mt{ty: t, ..}) |
+ ty::ty_rptr(_, ty::mt{ty: t, ..}) |
+ ty::ty_box(t) |
+ ty::ty_uniq(t) => match ty::get(t).sty {
+ ty::ty_vec(_, None) => true,
+ _ => false,
+ },
+ _ => false
+ }
+ }
+ fn types_compatible(fcx: &FnCtxt, sp: Span,
+ t1: ty::t, t2: ty::t) -> bool {
+ if !is_vec(t1) {
+ false
+ } else {
+ let el = ty::sequence_element_type(fcx.tcx(),
+ t1);
+ infer::mk_eqty(fcx.infcx(), false,
+ infer::Misc(sp), el, t2).is_ok()
+ }
+ }
+
+ // Due to the limitations of LLVM global constants,
+ // region pointers end up pointing at copies of
+ // vector elements instead of the original values.
+ // To allow unsafe pointers to work correctly, we
+ // need to special-case obtaining an unsafe pointer
+ // from a region pointer to a vector.
+
+ /* this cast is only allowed from &[T] to *T or
+ &T to *T. */
+ match (&ty::get(t_e).sty, &ty::get(t_1).sty) {
+ (&ty::ty_rptr(_, ty::mt { ty: mt1, mutbl: ast::MutImmutable }),
+ &ty::ty_ptr(ty::mt { ty: mt2, mutbl: ast::MutImmutable }))
+ if types_compatible(fcx, expr_from.span, mt1, mt2) => {
+ /* this case is allowed */
+ }
+ _ => {
+ demand::coerce(fcx, expr_from.span, ty_to, expr_from);
+ }
+ }
+ } else if !(ty::type_is_scalar(t_e) && to_is_trivial) {
+ // If more type combinations should be supported than are
+ // supported here, then file an enhancement issue and
+ // record the issue number in this comment.
+ fcx.type_error_message(expr_from.span, |actual| {
+ format!("non-scalar cast: `{}` as `{}`", actual,
+ fcx.infcx().ty_to_str(ty_to))
+ }, ty_from, None);
+ }
+}
+
pub fn require_uint(fcx: &FnCtxt, sp: Span, t: ty::t) {
if !type_is_uint(fcx, sp, t) {
fcx.type_error_message(sp, |actual| {
}
pub fn check_block_no_value(fcx: &FnCtxt, blk: &ast::Block) {
- check_block_with_expected(fcx, blk, Some(ty::mk_nil()));
+ check_block_with_expected(fcx, blk, ExpectHasType(ty::mk_nil()));
let blkty = fcx.node_ty(blk.id);
if ty::type_is_error(blkty) {
fcx.write_error(blk.id);
}
}
-pub fn check_block_with_expected(fcx: &FnCtxt,
- blk: &ast::Block,
- expected: Option<ty::t>) {
+fn check_block_with_expected(fcx: &FnCtxt,
+ blk: &ast::Block,
+ expected: Expectation) {
let prev = {
let mut fcx_ps = fcx.ps.borrow_mut();
let fn_style_state = fcx_ps.recurse(blk);
fcx.ccx
.tcx
.sess
- .add_lint(UnreachableCode,
+ .add_lint(lint::builtin::UNREACHABLE_CODE,
s_id,
s.span,
"unreachable statement".to_string());
fcx.ccx
.tcx
.sess
- .add_lint(UnreachableCode,
+ .add_lint(lint::builtin::UNREACHABLE_CODE,
e.id,
e.span,
"unreachable expression".to_string());
}
- check_expr_with_opt_hint(fcx, &*e, expected);
- let ety = fcx.expr_ty(&*e);
+ check_expr_with_expectation(fcx, e, expected);
+ let ety = fcx.expr_ty(e);
fcx.write_ty(blk.id, ety);
if any_err {
fcx.write_error(blk.id);
// Resolves `typ` by a single level if `typ` is a type variable. If no
// resolution is possible, then an error is reported.
pub fn structurally_resolved_type(fcx: &FnCtxt, sp: Span, tp: ty::t) -> ty::t {
- match infer::resolve_type(fcx.infcx(), tp, force_tvar) {
+ match infer::resolve_type(fcx.infcx(), Some(sp), tp, force_tvar) {
Ok(t_s) if !ty::type_is_ty_var(t_s) => t_s,
_ => {
fcx.type_error_message(sp, |_actual| {
* bigger than the let and the `*b` expression, so we will
* effectively resolve `<R0>` to be the block B.
*/
- match resolve_type(self.fcx.infcx(), unresolved_ty,
+ match resolve_type(self.fcx.infcx(), None, unresolved_ty,
resolve_and_force_all_but_regions) {
Ok(t) => t,
Err(_) => ty::mk_err()
is_early: bool)
-> Option<ty::t> {
let tcx = vcx.tcx();
- match resolve_type(vcx.infcx, ty, resolve_and_force_all_but_regions) {
+ match resolve_type(vcx.infcx, Some(span), ty, resolve_and_force_all_but_regions) {
Ok(new_type) => Some(new_type),
Err(e) if !is_early => {
tcx.sess.span_fatal(span,
return t;
}
- match resolve_type(self.infcx, t, resolve_all | force_all) {
+ match resolve_type(self.infcx, None, t, resolve_all | force_all) {
Ok(t) => t,
Err(e) => {
self.report_error(e);
-> Option<t> {
let resolved_type;
match resolve_type(inference_context,
+ Some(span),
original_type,
resolve_ivar) {
Ok(resulting_type) if !type_is_ty_var(resulting_type) => {
pub fn unpack_actual_value(&self, a: ty::t, f: |&ty::sty| -> CoerceResult)
-> CoerceResult {
- match resolve_type(self.get_ref().infcx, a, try_resolve_tvar_shallow) {
+ match resolve_type(self.get_ref().infcx, None,
+ a, try_resolve_tvar_shallow) {
Ok(t) => {
f(&ty::get(t).sty)
}
pub enum fixup_err {
unresolved_int_ty(IntVid),
+ unresolved_float_ty(FloatVid),
unresolved_ty(TyVid),
cyclic_ty(TyVid),
unresolved_region(RegionVid),
pub fn fixup_err_to_str(f: fixup_err) -> String {
match f {
unresolved_int_ty(_) => "unconstrained integral type".to_string(),
+ unresolved_float_ty(_) => {
+ "unconstrained floating point type".to_string()
+ }
unresolved_ty(_) => "unconstrained type".to_string(),
cyclic_ty(_) => "cyclic type of infinite size".to_string(),
unresolved_region(_) => "unconstrained region".to_string(),
// See comment on the type `resolve_state` below
pub fn resolve_type(cx: &InferCtxt,
+ span: Option<Span>,
a: ty::t,
modes: uint)
- -> fres<ty::t>
-{
- let mut resolver = resolver(cx, modes);
+ -> fres<ty::t> {
+ let mut resolver = resolver(cx, modes, span);
cx.commit_unconditionally(|| resolver.resolve_type_chk(a))
}
pub fn resolve_region(cx: &InferCtxt, r: ty::Region, modes: uint)
- -> fres<ty::Region>
-{
- let mut resolver = resolver(cx, modes);
+ -> fres<ty::Region> {
+ let mut resolver = resolver(cx, modes, None);
resolver.resolve_region_chk(r)
}
}
pub fn resolve_type_vars_if_possible(&self, typ: ty::t) -> ty::t {
- match resolve_type(self, typ, resolve_nested_tvar | resolve_ivar) {
- Ok(new_type) => new_type,
- Err(_) => typ
+ match resolve_type(self,
+ None,
+ typ, resolve_nested_tvar | resolve_ivar) {
+ Ok(new_type) => new_type,
+ Err(_) => typ
}
}
fn iterate_until_fixed_point(&self,
tag: &str,
body: |constraint: &Constraint| -> bool) {
- let mut iteration = 0;
+ let mut iteration = 0u;
let mut changed = true;
while changed {
changed = false;
use middle::typeck::infer::{Bounds, cyclic_ty, fixup_err, fres, InferCtxt};
use middle::typeck::infer::unresolved_ty;
use middle::typeck::infer::unify::Root;
-use util::common::{indent};
-use util::ppaux::{ty_to_str, Repr};
+use syntax::codemap::Span;
+use util::common::indent;
+use util::ppaux::{Repr, ty_to_str};
use syntax::ast;
modes: uint,
err: Option<fixup_err>,
v_seen: Vec<TyVid> ,
- type_depth: uint
+ type_depth: uint,
+ span: Option<Span>,
}
-pub fn resolver<'a>(infcx: &'a InferCtxt, modes: uint) -> ResolveState<'a> {
+pub fn resolver<'a>(infcx: &'a InferCtxt,
+ modes: uint,
+ span: Option<Span>)
+ -> ResolveState<'a>
+{
ResolveState {
infcx: infcx,
modes: modes,
err: None,
v_seen: Vec::new(),
- type_depth: 0
+ type_depth: 0,
+ span: span
}
}
(self.modes & mode) == mode
}
- pub fn resolve_type_chk(&mut self, typ: ty::t) -> fres<ty::t> {
+ pub fn resolve_type_chk(&mut self,
+ typ: ty::t)
+ -> fres<ty::t> {
self.err = None;
debug!("Resolving {} (modes={:x})",
}
}
- pub fn resolve_region_chk(&mut self, orig: ty::Region)
+ pub fn resolve_region_chk(&mut self,
+ orig: ty::Region)
-> fres<ty::Region> {
self.err = None;
let resolved = indent(|| self.resolve_region(orig) );
Some(UintType(t)) => ty::mk_mach_uint(t),
None => {
if self.should(force_ivar) {
- // As a last resort, default to int.
+ // As a last resort, default to int and emit an error.
let ty = ty::mk_int();
table.borrow_mut().set(
tcx, node.key, Root(Some(IntType(ast::TyI)), node.rank));
+
+ match self.span {
+ Some(sp) => {
+ self.infcx.tcx.sess.span_err(
+ sp,
+ "cannot determine the type of this integer; add \
+ a suffix to specify the type explicitly");
+ }
+ None => { }
+ }
ty
} else {
ty::mk_int_var(self.infcx.tcx, vid)
Some(t) => ty::mk_mach_float(t),
None => {
if self.should(force_fvar) {
- // As a last resort, default to f64.
+ // As a last resort, default to f64 and emit an error.
let ty = ty::mk_f64();
table.borrow_mut().set(
tcx, node.key, Root(Some(ast::TyF64), node.rank));
+
+ match self.span {
+ Some(sp) => {
+ self.infcx.tcx.sess.span_err(
+ sp,
+ "cannot determine the type of this number; add \
+ a suffix to specify the type explicitly");
+ }
+ None => { }
+ }
ty
} else {
ty::mk_float_var(self.infcx.tcx, vid)
name: "test".to_owned(),
version: None };
let (krate, ast_map) =
- driver::phase_2_configure_and_expand(&sess, krate, &krate_id);
+ driver::phase_2_configure_and_expand(&sess, krate, &krate_id)
+ .expect("phase 2 aborted");
// run just enough stuff to build a tcx:
let lang_items = lang_items::collect_language_items(&krate, &sess);
//! Used by plugin crates to tell `rustc` about the plugins they provide.
+use lint::LintPassObject;
+
use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT};
use syntax::ext::base::{IdentTT, ItemDecorator, ItemModifier, BasicMacroExpander};
use syntax::ext::base::{MacroExpanderFn};
#[doc(hidden)]
pub syntax_exts: Vec<NamedSyntaxExtension>,
+
+ #[doc(hidden)]
+ pub lint_passes: Vec<LintPassObject>,
}
impl Registry {
Registry {
krate_span: krate.span,
syntax_exts: vec!(),
+ lint_passes: vec!(),
}
}
span: None,
}, None));
}
+
+ /// Register a compiler lint pass.
+ pub fn register_lint_pass(&mut self, lint_pass: LintPassObject) {
+ self.lint_passes.push(lint_pass);
+ }
}
ty_bot => "!".to_string(),
ty_bool => "bool".to_string(),
ty_char => "char".to_string(),
- ty_int(t) => ast_util::int_ty_to_str(t, None,
- ast_util::AutoSuffix).to_string(),
- ty_uint(t) => ast_util::uint_ty_to_str(t, None,
- ast_util::AutoSuffix).to_string(),
+ ty_int(t) => ast_util::int_ty_to_str(t, None).to_string(),
+ ty_uint(t) => ast_util::uint_ty_to_str(t, None).to_string(),
ty_float(t) => ast_util::float_ty_to_str(t).to_string(),
ty_box(typ) => format!("Gc<{}>", ty_to_str(cx, typ)),
ty_uniq(typ) => format!("Box<{}>", ty_to_str(cx, typ)),
use rustc;
use rustc::{driver, middle};
use rustc::middle::privacy;
-use rustc::middle::lint;
+use rustc::lint;
use syntax::ast;
use syntax::parse::token;
let input = FileInput(cpath.clone());
+ let warning_lint = lint::builtin::WARNINGS.name_lower();
+
let sessopts = driver::config::Options {
maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
addl_lib_search_paths: RefCell::new(libs),
crate_types: vec!(driver::config::CrateTypeRlib),
- lint_opts: vec!((lint::Warnings, lint::Allow)),
+ lint_opts: vec!((warning_lint, lint::Allow)),
..rustc::driver::config::basic_options().clone()
};
}
let krate = phase_1_parse_input(&sess, cfg, &input);
- let (krate, ast_map) = phase_2_configure_and_expand(&sess, krate,
- &from_str("rustdoc").unwrap());
+ let (krate, ast_map)
+ = phase_2_configure_and_expand(&sess, krate, &from_str("rustdoc").unwrap())
+ .expect("phase_2_configure_and_expand aborted in rustdoc!");
+
let driver::driver::CrateAnalysis {
exported_items, public_items, ty_cx, ..
} = phase_3_run_analysis_passes(sess, &krate, ast_map);
use getopts::*;
vec!(
optflag("h", "help", "show this help message"),
- optflag("", "version", "print rustdoc's version"),
+ optflagopt("", "version", "print rustdoc's version", "verbose"),
optopt("r", "input-format", "the input type of the specified file",
"[rust|json]"),
optopt("w", "output-format", "the output type to write",
usage(args[0].as_slice());
return 0;
} else if matches.opt_present("version") {
- rustc::driver::version("rustdoc");
- return 0;
+ match rustc::driver::version("rustdoc", &matches) {
+ Some(err) => {
+ println!("{}", err);
+ return 1
+ },
+ None => return 0
+ }
}
if matches.free.len() == 0 {
}));
let krate = driver::phase_1_parse_input(&sess, cfg, &input);
let (krate, _) = driver::phase_2_configure_and_expand(&sess, krate,
- &from_str("rustdoc-test").unwrap());
+ &from_str("rustdoc-test").unwrap())
+ .expect("phase_2_configure_and_expand aborted in rustdoc!");
let ctx = box(GC) core::DocContext {
krate: krate,
}
/// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
- /// Any ownership of the buffer by the `CString` wrapper is forgotten.
+ ///
+ /// The original object is destructed after this method is called, and if
+ /// the underlying pointer was previously allocated, care must be taken to
+ /// ensure that it is deallocated properly.
pub unsafe fn unwrap(self) -> *libc::c_char {
let mut c_str = self;
c_str.owns_buffer_ = false;
pub type _Unwind_Word = libc::uintptr_t;
#[cfg(target_arch = "x86")]
-pub static unwinder_private_data_size: int = 5;
+pub static unwinder_private_data_size: uint = 5;
#[cfg(target_arch = "x86_64")]
-pub static unwinder_private_data_size: int = 2;
+pub static unwinder_private_data_size: uint = 2;
#[cfg(target_arch = "arm", not(target_os = "ios"))]
-pub static unwinder_private_data_size: int = 20;
+pub static unwinder_private_data_size: uint = 20;
#[cfg(target_arch = "arm", target_os = "ios")]
-pub static unwinder_private_data_size: int = 5;
+pub static unwinder_private_data_size: uint = 5;
#[cfg(target_arch = "mips")]
#[cfg(target_arch = "mipsel")]
-pub static unwinder_private_data_size: int = 2;
+pub static unwinder_private_data_size: uint = 2;
pub struct _Unwind_Exception {
pub exception_class: _Unwind_Exception_Class,
fn smoke() { Thread::start(proc (){}).join(); }
#[test]
- fn data() { assert_eq!(Thread::start(proc () { 1 }).join(), 1); }
+ fn data() { assert_eq!(Thread::start(proc () { 1i }).join(), 1); }
#[test]
fn detached() { Thread::spawn(proc () {}) }
#[test]
fn small_stacks() {
- assert_eq!(42, Thread::start_stack(0, proc () 42).join());
- assert_eq!(42, Thread::start_stack(1, proc () 42).join());
+ assert_eq!(42i, Thread::start_stack(0, proc () 42i).join());
+ assert_eq!(42i, Thread::start_stack(1, proc () 42i).join());
}
}
fn test_base64_random() {
use std::rand::{task_rng, random, Rng};
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let times = task_rng().gen_range(1u, 100);
let v = Vec::from_fn(times, |_| random::<u8>());
assert_eq!(v.as_slice()
// the most significant bit is set, the second most significant bit is set etc. we can
// replace up to three "and+branch" with a single table lookup which gives us a measured
// speedup of around 2x on x86_64.
- static SHIFT_MASK_TABLE: [(u32, u32), ..16] = [
+ static SHIFT_MASK_TABLE: [(uint, u32), ..16] = [
(0, 0x0), (0, 0x0fffffff),
(8, 0x1fffff), (8, 0x1fffff),
(16, 0x3fff), (16, 0x3fff), (16, 0x3fff), (16, 0x3fff),
#[test]
pub fn test_to_hex_all_bytes() {
- for i in range(0, 256) {
+ for i in range(0u, 256) {
assert_eq!([i as u8].to_hex(), format!("{:02x}", i as uint));
}
}
#[test]
pub fn test_from_hex_all_bytes() {
- for i in range(0, 256) {
+ for i in range(0u, 256) {
assert_eq!(format!("{:02x}", i as uint).as_slice()
.from_hex()
.unwrap()
assert_eq!(true.to_json(), Boolean(true));
assert_eq!(false.to_json(), Boolean(false));
assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
- assert_eq!((1, 2).to_json(), list2);
- assert_eq!((1, 2, 3).to_json(), list3);
- assert_eq!([1, 2].to_json(), list2);
- assert_eq!((&[1, 2, 3]).to_json(), list3);
- assert_eq!((vec![1, 2]).to_json(), list2);
- assert_eq!(vec!(1, 2, 3).to_json(), list3);
+ assert_eq!((1i, 2i).to_json(), list2);
+ assert_eq!((1i, 2i, 3i).to_json(), list3);
+ assert_eq!([1i, 2].to_json(), list2);
+ assert_eq!((&[1i, 2, 3]).to_json(), list3);
+ assert_eq!((vec![1i, 2]).to_json(), list2);
+ assert_eq!(vec!(1i, 2i, 3i).to_json(), list3);
let mut tree_map = TreeMap::new();
- tree_map.insert("a".to_string(), 1);
+ tree_map.insert("a".to_string(), 1i);
tree_map.insert("b".to_string(), 2);
assert_eq!(tree_map.to_json(), object);
let mut hash_map = HashMap::new();
- hash_map.insert("a".to_string(), 1);
+ hash_map.insert("a".to_string(), 1i);
hash_map.insert("b".to_string(), 2);
assert_eq!(hash_map.to_json(), object);
- assert_eq!(Some(15).to_json(), Number(15 as f64));
+ assert_eq!(Some(15i).to_json(), Number(15 as f64));
assert_eq!(None::<int>.to_json(), Null);
}
fn big_json() -> String {
let mut src = "[\n".to_string();
- for _ in range(0, 500) {
+ for _ in range(0i, 500) {
src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
[1,2,3]},"#);
}
fn test_create_capacity_zero() {
let mut m = HashMap::with_capacity(0);
- assert!(m.insert(1, 1));
+ assert!(m.insert(1i, 1i));
assert!(m.contains_key(&1));
assert!(!m.contains_key(&0));
fn test_insert() {
let mut m = HashMap::new();
assert_eq!(m.len(), 0);
- assert!(m.insert(1, 2));
+ assert!(m.insert(1i, 2i));
assert_eq!(m.len(), 1);
- assert!(m.insert(2, 4));
+ assert!(m.insert(2i, 4i));
assert_eq!(m.len(), 2);
assert_eq!(*m.find(&1).unwrap(), 2);
assert_eq!(*m.find(&2).unwrap(), 4);
#[test]
fn test_drops() {
- drop_vector.replace(Some(RefCell::new(Vec::from_elem(200, 0))));
+ drop_vector.replace(Some(RefCell::new(Vec::from_elem(200, 0i))));
{
let mut m = HashMap::new();
// Try this a few times to make sure we never screw up the hashmap's
// internal state.
- for _ in range(0, 10) {
+ for _ in range(0i, 10) {
assert!(m.is_empty());
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
assert!(m.insert(i, i));
for j in range_inclusive(1, i) {
}
}
- for i in range_inclusive(1001, 2000) {
+ for i in range_inclusive(1001i, 2000) {
assert!(!m.contains_key(&i));
}
// remove forwards
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
assert!(m.remove(&i));
for j in range_inclusive(1, i) {
}
}
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
assert!(!m.contains_key(&i));
}
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
assert!(m.insert(i, i));
}
// remove backwards
- for i in range_step_inclusive(1000, 1, -1) {
+ for i in range_step_inclusive(1000i, 1, -1) {
assert!(m.remove(&i));
for j in range_inclusive(i, 1000) {
#[test]
fn test_find_mut() {
let mut m = HashMap::new();
- assert!(m.insert(1, 12));
- assert!(m.insert(2, 8));
- assert!(m.insert(5, 14));
+ assert!(m.insert(1i, 12i));
+ assert!(m.insert(2i, 8i));
+ assert!(m.insert(5i, 14i));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
#[test]
fn test_insert_overwrite() {
let mut m = HashMap::new();
- assert!(m.insert(1, 2));
+ assert!(m.insert(1i, 2i));
assert_eq!(*m.find(&1).unwrap(), 2);
- assert!(!m.insert(1, 3));
+ assert!(!m.insert(1i, 3i));
assert_eq!(*m.find(&1).unwrap(), 3);
}
#[test]
fn test_insert_conflicts() {
let mut m = HashMap::with_capacity(4);
- assert!(m.insert(1, 2));
- assert!(m.insert(5, 3));
- assert!(m.insert(9, 4));
+ assert!(m.insert(1i, 2i));
+ assert!(m.insert(5i, 3i));
+ assert!(m.insert(9i, 4i));
assert_eq!(*m.find(&9).unwrap(), 4);
assert_eq!(*m.find(&5).unwrap(), 3);
assert_eq!(*m.find(&1).unwrap(), 2);
#[test]
fn test_conflict_remove() {
let mut m = HashMap::with_capacity(4);
- assert!(m.insert(1, 2));
+ assert!(m.insert(1i, 2i));
assert_eq!(*m.find(&1).unwrap(), 2);
assert!(m.insert(5, 3));
assert_eq!(*m.find(&1).unwrap(), 2);
#[test]
fn test_is_empty() {
let mut m = HashMap::with_capacity(4);
- assert!(m.insert(1, 2));
+ assert!(m.insert(1i, 2i));
assert!(!m.is_empty());
assert!(m.remove(&1));
assert!(m.is_empty());
#[test]
fn test_pop() {
let mut m = HashMap::new();
- m.insert(1, 2);
+ m.insert(1i, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
#[allow(experimental)]
fn test_pop_equiv() {
let mut m = HashMap::new();
- m.insert(1, 2);
+ m.insert(1i, 2i);
assert_eq!(m.pop_equiv(&KindaIntLike(1)), Some(2));
assert_eq!(m.pop_equiv(&KindaIntLike(1)), None);
}
#[test]
fn test_swap() {
let mut m = HashMap::new();
- assert_eq!(m.swap(1, 2), None);
- assert_eq!(m.swap(1, 3), Some(2));
- assert_eq!(m.swap(1, 4), Some(3));
+ assert_eq!(m.swap(1i, 2i), None);
+ assert_eq!(m.swap(1i, 3i), Some(2));
+ assert_eq!(m.swap(1i, 4i), Some(3));
}
#[test]
let hm = {
let mut hm = HashMap::new();
- hm.insert('a', 1);
- hm.insert('b', 2);
+ hm.insert('a', 1i);
+ hm.insert('b', 2i);
hm
};
#[test]
fn test_keys() {
- let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
+ let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
let map = vec.move_iter().collect::<HashMap<int, char>>();
let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
assert_eq!(keys.len(), 3);
#[test]
fn test_values() {
- let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
+ let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
let map = vec.move_iter().collect::<HashMap<int, char>>();
let values = map.values().map(|&v| v).collect::<Vec<char>>();
assert_eq!(values.len(), 3);
#[test]
fn test_find() {
let mut m = HashMap::new();
- assert!(m.find(&1).is_none());
- m.insert(1, 2);
+ assert!(m.find(&1i).is_none());
+ m.insert(1i, 2i);
match m.find(&1) {
None => fail!(),
Some(v) => assert_eq!(*v, 2)
#[test]
fn test_eq() {
let mut m1 = HashMap::new();
- m1.insert(1, 2);
- m1.insert(2, 3);
- m1.insert(3, 4);
+ m1.insert(1i, 2i);
+ m1.insert(2i, 3i);
+ m1.insert(3i, 4i);
let mut m2 = HashMap::new();
- m2.insert(1, 2);
- m2.insert(2, 3);
+ m2.insert(1i, 2i);
+ m2.insert(2i, 3i);
assert!(m1 != m2);
- m2.insert(3, 4);
+ m2.insert(3i, 4i);
assert_eq!(m1, m2);
}
let mut map: HashMap<int, int> = HashMap::new();
let empty: HashMap<int, int> = HashMap::new();
- map.insert(1, 2);
- map.insert(3, 4);
+ map.insert(1i, 2i);
+ map.insert(3i, 4i);
let map_str = format!("{}", map);
fn test_find_equiv() {
let mut m = HashMap::new();
- let (foo, bar, baz) = (1,2,3);
+ let (foo, bar, baz) = (1i,2i,3i);
m.insert("foo".to_string(), foo);
m.insert("bar".to_string(), bar);
m.insert("baz".to_string(), baz);
#[test]
fn test_from_iter() {
- let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
+ let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
#[test]
fn test_size_hint() {
- let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
+ let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
#[test]
fn test_mut_size_hint() {
- let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
+ let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
let mut ys = HashSet::new();
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
- assert!(xs.insert(5));
- assert!(ys.insert(11));
+ assert!(xs.insert(5i));
+ assert!(ys.insert(11i));
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(7));
#[test]
fn test_subset_and_superset() {
let mut a = HashSet::new();
- assert!(a.insert(0));
+ assert!(a.insert(0i));
assert!(a.insert(5));
assert!(a.insert(11));
assert!(a.insert(7));
let mut b = HashSet::new();
- assert!(b.insert(0));
+ assert!(b.insert(0i));
assert!(b.insert(7));
assert!(b.insert(19));
assert!(b.insert(250));
let mut a = HashSet::new();
let mut b = HashSet::new();
- assert!(a.insert(11));
+ assert!(a.insert(11i));
assert!(a.insert(1));
assert!(a.insert(3));
assert!(a.insert(77));
assert!(a.insert(5));
assert!(a.insert(-5));
- assert!(b.insert(2));
+ assert!(b.insert(2i));
assert!(b.insert(11));
assert!(b.insert(77));
assert!(b.insert(-9));
let mut a = HashSet::new();
let mut b = HashSet::new();
- assert!(a.insert(1));
+ assert!(a.insert(1i));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(11));
- assert!(b.insert(3));
+ assert!(b.insert(3i));
assert!(b.insert(9));
let mut i = 0;
let mut a = HashSet::new();
let mut b = HashSet::new();
- assert!(a.insert(1));
+ assert!(a.insert(1i));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(11));
- assert!(b.insert(-2));
+ assert!(b.insert(-2i));
assert!(b.insert(3));
assert!(b.insert(9));
assert!(b.insert(14));
let mut a = HashSet::new();
let mut b = HashSet::new();
- assert!(a.insert(1));
+ assert!(a.insert(1i));
assert!(a.insert(3));
assert!(a.insert(5));
assert!(a.insert(9));
assert!(a.insert(19));
assert!(a.insert(24));
- assert!(b.insert(-2));
+ assert!(b.insert(-2i));
assert!(b.insert(1));
assert!(b.insert(5));
assert!(b.insert(9));
#[test]
fn test_from_iter() {
- let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
+ let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
let set: HashSet<int> = xs.iter().map(|&x| x).collect();
// I'm keeping them around to prevent a regression.
let mut s1 = HashSet::new();
- s1.insert(1);
+ s1.insert(1i);
s1.insert(2);
s1.insert(3);
let mut s2 = HashSet::new();
- s2.insert(1);
+ s2.insert(1i);
s2.insert(2);
assert!(s1 != s2);
let mut set: HashSet<int> = HashSet::new();
let empty: HashSet<int> = HashSet::new();
- set.insert(1);
+ set.insert(1i);
set.insert(2);
let set_str = format!("{}", set);
b.iter(|| {
let mut m = HashMap::new();
- m.insert(0, 0);
+ m.insert(0i, 0i);
assert_eq!(m.len(), 1);
})
}
let mut m = HashMap::new();
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.insert(i, i);
}
let mut m = HashMap::new();
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.insert(i, i);
}
b.iter(|| {
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.contains_key(&i);
}
});
let mut m = HashMap::new();
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.insert(i, i);
}
b.iter(|| {
- for i in range_inclusive(1001, 2000) {
+ for i in range_inclusive(1001i, 2000) {
m.contains_key(&i);
}
});
let mut m = HashMap::new();
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.insert(i, i);
}
- let mut k = 1;
+ let mut k = 1i;
b.iter(|| {
m.pop(&k);
let mut m = HashMap::new();
- for i in range_inclusive(1, 1000) {
+ for i in range_inclusive(1i, 1000) {
m.insert(i, i);
}
- let mut k = 1;
+ let mut k = 1i;
b.iter(|| {
m.find(&(k + 400));
```rust
# extern crate debug;
# fn main() {
-format!("Hello"); // => "Hello"
-format!("Hello, {:s}!", "world"); // => "Hello, world!"
-format!("The number is {:d}", 1); // => "The number is 1"
-format!("{:?}", (3, 4)); // => "(3, 4)"
-format!("{value}", value=4); // => "4"
-format!("{} {}", 1, 2); // => "1 2"
+format!("Hello"); // => "Hello"
+format!("Hello, {:s}!", "world"); // => "Hello, world!"
+format!("The number is {:d}", 1i); // => "The number is 1"
+format!("{:?}", (3i, 4i)); // => "(3, 4)"
+format!("{value}", value=4i); // => "4"
+format!("{} {}", 1i, 2i); // => "1 2"
# }
```
iterator advances. This leads to behavior like this:
```rust
-format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
+format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
```
The internal iterator over the argument has not been advanced by the time the
```rust
# extern crate debug;
# fn main() {
-format!("{argument}", argument = "test"); // => "test"
-format!("{name} {}", 1, name = 2); // => "2 1"
-format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => "a 3 ()"
+format!("{argument}", argument = "test"); // => "test"
+format!("{name} {}", 1i, name = 2i); // => "2 1"
+format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3i); // => "a 3 ()"
# }
```
/// A trait to abstract the idea of creating a new instance of a type from a
/// string.
+#[experimental = "might need to return Result"]
pub trait FromStr {
/// Parses a string `s` to return an optional value of this type. If the
/// string is ill-formatted, the None is returned.
marker: marker::NoSend,
}
+#[unstable]
impl<T> Clone for Gc<T> {
/// Clone the pointer only
#[inline]
let mut n = n;
while i > 0u {
bytes.push((n & 255_u64) as u8);
- n >>= 8_u64;
+ n >>= 8;
i -= 1u;
}
f(bytes.as_slice())
let mut bytes = vec!();
let mut i = size;
while i > 0u {
- let shift = ((i - 1u) * 8u) as u64;
+ let shift = (i - 1u) * 8u;
bytes.push((n >> shift) as u8);
i -= 1u;
}
let dir = &tmpdir.join("di_readdir");
check!(mkdir(dir, io::UserRWX));
let prefix = "foo";
- for n in range(0,3) {
+ for n in range(0i,3) {
let f = dir.join(format!("{}.txt", n));
let mut w = check!(File::create(&f));
let msg_str = format!("{}{}", prefix, n.to_str());
fn bench_mem_writer(b: &mut Bencher) {
b.iter(|| {
let mut wr = MemWriter::new();
- for _i in range(0, 10) {
+ for _i in range(0u, 10) {
wr.write([5, .. 10]).unwrap();
}
assert_eq!(wr.unwrap().as_slice(), [5, .. 100].as_slice());
let buf = Vec::from_slice([5 as u8, ..100]);
{
let mut rdr = MemReader::new(buf);
- for _i in range(0, 10) {
+ for _i in range(0u, 10) {
let mut buf = [0 as u8, .. 10];
rdr.read(buf).unwrap();
assert_eq!(buf.as_slice(), [5, .. 10].as_slice());
let mut buf = [0 as u8, ..100];
{
let mut wr = BufWriter::new(buf);
- for _i in range(0, 10) {
+ for _i in range(0u, 10) {
wr.write([5, .. 10]).unwrap();
}
}
let buf = [5 as u8, ..100];
{
let mut rdr = BufReader::new(buf);
- for _i in range(0, 10) {
+ for _i in range(0u, 10) {
let mut buf = [0 as u8, .. 10];
rdr.read(buf).unwrap();
assert_eq!(buf.as_slice(), [5, .. 10].as_slice());
port).unwrap());
});
let _l = rx.recv();
- for i in range(0, 1001) {
+ for i in range(0i, 1001) {
match a.accept() {
Ok(..) => break,
Err(ref e) if e.kind == TimedOut => {}
assert_eq!(s.read([0]).err().unwrap().kind, TimedOut);
s.set_timeout(Some(20));
- for i in range(0, 1001) {
+ for i in range(0i, 1001) {
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
assert_eq!(s.read([0]).err().unwrap().kind, TimedOut);
tx.send(());
- for _ in range(0, 100) {
+ for _ in range(0i, 100) {
assert!(s.write([0, ..128 * 1024]).is_ok());
}
})
let mut s = a.accept().unwrap();
s.set_write_timeout(Some(20));
- for i in range(0, 1001) {
+ for i in range(0i, 1001) {
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
let _b = UdpSocket::bind(addr2).unwrap();
a.set_write_timeout(Some(1000));
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
match a.sendto([0, ..4*1024], addr2) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
};
spawn(proc() {
- for _ in range(0, times) {
+ for _ in range(0u, times) {
let mut stream = UnixStream::connect(&path2);
match stream.write([100]) {
Ok(..) => {}
tx.send(UnixStream::connect(&addr2).unwrap());
});
let l = rx.recv();
- for i in range(0, 1001) {
+ for i in range(0u, 1001) {
match a.accept() {
Ok(..) => break,
Err(ref e) if e.kind == TimedOut => {}
assert_eq!(s.read([0]).err().unwrap().kind, TimedOut);
s.set_timeout(Some(20));
- for i in range(0, 1001) {
+ for i in range(0u, 1001) {
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
assert_eq!(s.read([0]).err().unwrap().kind, TimedOut);
tx.send(());
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
assert!(s.write([0, ..128 * 1024]).is_ok());
}
})
let mut s = a.accept().unwrap();
s.set_write_timeout(Some(20));
- for i in range(0, 1001) {
+ for i in range(0u, 1001) {
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
iotest!(fn test_zero() {
let mut p = sleeper();
p.signal_kill().unwrap();
- for _ in range(0, 20) {
+ for _ in range(0i, 20) {
if p.signal(0).is_err() {
assert!(!p.wait().unwrap().success());
return
/// let mut timer = Timer::new().unwrap();
/// let ten_milliseconds = timer.oneshot(10);
///
- /// for _ in range(0, 100) { /* do work */ }
+ /// for _ in range(0u, 100) { /* do work */ }
///
/// // blocks until 10 ms after the `oneshot` call
/// ten_milliseconds.recv();
/// let mut timer = Timer::new().unwrap();
/// let ten_milliseconds = timer.periodic(10);
///
- /// for _ in range(0, 100) { /* do work */ }
+ /// for _ in range(0u, 100) { /* do work */ }
///
/// // blocks until 10 ms after the `periodic` call
/// ten_milliseconds.recv();
///
- /// for _ in range(0, 100) { /* do work */ }
+ /// for _ in range(0u, 100) { /* do work */ }
///
/// // blocks until 20 ms after the `periodic` call (*not* 10ms after the
/// // previous `recv`)
/// # #![allow(unreachable_code)]
/// fail!();
/// fail!("this is a terrible mistake!");
-/// fail!(4); // fail with the value of 4 to be collected elsewhere
+/// fail!(4i); // fail with the value of 4 to be collected elsewhere
/// fail!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
/// // assert with a custom message
/// # let x = true;
/// assert!(x, "x wasn't true!");
-/// # let a = 3; let b = 27;
+/// # let a = 3i; let b = 27i;
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
/// # Example
///
/// ```
-/// let a = 3;
-/// let b = 1 + 2;
+/// let a = 3i;
+/// let b = 1i + 2i;
/// assert_eq!(a, b);
/// ```
#[macro_export]
/// // assert with a custom message
/// # let x = true;
/// debug_assert!(x, "x wasn't true!");
-/// # let a = 3; let b = 27;
+/// # let a = 3i; let b = 27i;
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
/// # Example
///
/// ```
-/// let a = 3;
-/// let b = 1 + 2;
+/// let a = 3i;
+/// let b = 1i + 2i;
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
/// ```
/// format!("test");
/// format!("hello {}", "world!");
-/// format!("x = {}, y = {y}", 10, y = 30);
+/// format!("x = {}, y = {y}", 10i, y = 30i);
/// ```
#[macro_export]
macro_rules! format(
/// let (tx1, rx1) = channel();
/// let (tx2, rx2) = channel();
/// # fn long_running_task() {}
-/// # fn calculate_the_answer() -> int { 42 }
+/// # fn calculate_the_answer() -> int { 42i }
///
/// spawn(proc() { long_running_task(); tx1.send(()) });
/// spawn(proc() { tx2.send(calculate_the_answer()) });
/// # Example
///
/// ```
- /// let s = concat!("test", 10, 'b', true);
+ /// let s = concat!("test", 10i, 'b', true);
/// assert_eq!(s, "test10btrue");
/// ```
#[macro_export]
//! Operations and constants for signed 16-bits integers (`i16` type)
+#![unstable]
#![doc(primitive = "i16")]
use from_str::FromStr;
//! Operations and constants for signed 32-bits integers (`i32` type)
+#![unstable]
#![doc(primitive = "i32")]
use from_str::FromStr;
//! Operations and constants for signed 64-bits integers (`i64` type)
+#![unstable]
#![doc(primitive = "i64")]
use from_str::FromStr;
//! Operations and constants for signed 8-bits integers (`i8` type)
+#![unstable]
#![doc(primitive = "i8")]
use from_str::FromStr;
//! Operations and constants for architecture-sized signed integers (`int` type)
+#![unstable]
#![doc(primitive = "int")]
use from_str::FromStr;
/// assert!(num == Some(123456789));
/// ```
#[inline]
+#[experimental = "might need to return Result"]
pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> {
strconv::from_str_bytes_common(buf, radix, true, false, false,
strconv::ExpNone, false, false)
}
+#[experimental = "might need to return Result"]
impl FromStr for $T {
#[inline]
fn from_str(s: &str) -> Option<$T> {
}
}
+#[experimental = "might need to return Result"]
impl FromStrRadix for $T {
#[inline]
fn from_str_radix(s: &str, radix: uint) -> Option<$T> {
/// # Examples
///
/// ```
+/// #![allow(deprecated)]
+///
/// std::int::to_str_bytes(123, 10, |v| {
/// assert!(v == "123".as_bytes());
/// });
/// ```
#[inline]
+#[deprecated = "just use .to_string(), or a BufWriter with write! if you mustn't allocate"]
pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
use io::{Writer, Seek};
// The radix can be as low as 2, so we need at least 64 characters for a
f(buf.slice(0, amt))
}
+#[deprecated = "use fmt::radix"]
impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
}
/// A generic trait for converting a value to a string with a radix (base)
+#[deprecated = "use fmt::radix"]
pub trait ToStrRadix {
fn to_str_radix(&self, radix: uint) -> String;
}
/// A generic trait for converting a string with a radix (base) to a value
+#[experimental = "might need to return Result"]
pub trait FromStrRadix {
fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
}
/// A utility function that just calls FromStrRadix::from_str_radix.
+#[experimental = "might need to return Result"]
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
FromStrRadix::from_str_radix(str, radix)
}
/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T:Num + NumCast + Show>(ten: T, two: T) {
- assert_eq!(ten.add(&two), cast(12).unwrap());
- assert_eq!(ten.sub(&two), cast(8).unwrap());
- assert_eq!(ten.mul(&two), cast(20).unwrap());
- assert_eq!(ten.div(&two), cast(5).unwrap());
- assert_eq!(ten.rem(&two), cast(0).unwrap());
+ assert_eq!(ten.add(&two), cast(12i).unwrap());
+ assert_eq!(ten.sub(&two), cast(8i).unwrap());
+ assert_eq!(ten.mul(&two), cast(20i).unwrap());
+ assert_eq!(ten.div(&two), cast(5i).unwrap());
+ assert_eq!(ten.rem(&two), cast(0i).unwrap());
assert_eq!(ten.add(&two), ten + two);
assert_eq!(ten.sub(&two), ten - two);
assert_eq!(result, naive_pow($num, $exp));
}}
)
- assert_pow!((3, 0 ) => 1);
- assert_pow!((5, 1 ) => 5);
- assert_pow!((-4, 2 ) => 16);
- assert_pow!((0.5, 5 ) => 0.03125);
- assert_pow!((8, 3 ) => 512);
- assert_pow!((8.0, 5 ) => 32768.0);
- assert_pow!((8.5, 5 ) => 44370.53125);
- assert_pow!((2u64, 50) => 1125899906842624);
+ assert_pow!((3i, 0 ) => 1);
+ assert_pow!((5i, 1 ) => 5);
+ assert_pow!((-4i, 2 ) => 16);
+ assert_pow!((0.5f64, 5 ) => 0.03125);
+ assert_pow!((8i, 3 ) => 512);
+ assert_pow!((8.0f64, 5 ) => 32768.0);
+ assert_pow!((8.5f64, 5 ) => 44370.53125);
+ assert_pow!((2u64, 50) => 1125899906842624);
}
}
#[bench]
fn bench_pow_function(b: &mut Bencher) {
- let v = Vec::from_fn(1024, |n| n);
- b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});
+ let v = Vec::from_fn(1024u, |n| n);
+ b.iter(|| {v.iter().fold(0u, |old, new| num::pow(old, *new));});
}
}
//! Operations and constants for unsigned 16-bits integers (`u16` type)
+#![unstable]
#![doc(primitive = "u16")]
use from_str::FromStr;
//! Operations and constants for unsigned 32-bits integers (`u32` type)
+#![unstable]
#![doc(primitive = "u32")]
use from_str::FromStr;
//! Operations and constants for unsigned 64-bits integer (`u64` type)
+#![unstable]
#![doc(primitive = "u64")]
use from_str::FromStr;
//! Operations and constants for unsigned 8-bits integers (`u8` type)
+#![unstable]
#![doc(primitive = "u8")]
use from_str::FromStr;
//! Operations and constants for architecture-sized unsigned integers (`uint` type)
+#![unstable]
#![doc(primitive = "uint")]
use from_str::FromStr;
/// assert!(num == Some(123456789));
/// ```
#[inline]
+#[experimental = "might need to return Result"]
pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> {
strconv::from_str_bytes_common(buf, radix, false, false, false,
strconv::ExpNone, false, false)
}
+#[experimental = "might need to return Result"]
impl FromStr for $T {
#[inline]
fn from_str(s: &str) -> Option<$T> {
}
}
+#[experimental = "might need to return Result"]
impl FromStrRadix for $T {
#[inline]
fn from_str_radix(s: &str, radix: uint) -> Option<$T> {
/// # Examples
///
/// ```
+/// #![allow(deprecated)]
+///
/// std::uint::to_str_bytes(123, 10, |v| {
/// assert!(v == "123".as_bytes());
/// });
/// ```
#[inline]
+#[deprecated = "just use .to_string(), or a BufWriter with write! if you mustn't allocate"]
pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
use io::{Writer, Seek};
// The radix can be as low as 2, so we need at least 64 characters for a
f(buf.slice(0, amt))
}
+#[deprecated = "use fmt::radix"]
impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
/// use std::rand::{task_rng, sample};
///
/// let mut rng = task_rng();
-/// let sample = sample(&mut rng, range(1, 100), 5);
+/// let sample = sample(&mut rng, range(1i, 100), 5);
/// println!("{}", sample);
/// ```
pub fn sample<T, I: Iterator<T>, R: Rng>(rng: &mut R,
#[test]
fn test_gen_range() {
let mut r = task_rng();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let a = r.gen_range(-3i, 42);
assert!(a >= -3 && a < 42);
- assert_eq!(r.gen_range(0, 1), 0);
- assert_eq!(r.gen_range(-12, -11), -12);
+ assert_eq!(r.gen_range(0i, 1), 0);
+ assert_eq!(r.gen_range(-12i, -11), -12);
}
- for _ in range(0, 1000) {
- let a = r.gen_range(10, 42);
+ for _ in range(0u, 1000) {
+ let a = r.gen_range(10i, 42);
assert!(a >= 10 && a < 42);
- assert_eq!(r.gen_range(0, 1), 0);
+ assert_eq!(r.gen_range(0i, 1), 0);
assert_eq!(r.gen_range(3_000_000u, 3_000_001), 3_000_000);
}
#[test]
fn test_choose() {
let mut r = task_rng();
- assert_eq!(r.choose([1, 1, 1]).map(|&x|x), Some(1));
+ assert_eq!(r.choose([1i, 1, 1]).map(|&x|x), Some(1));
let v: &[int] = &[];
assert_eq!(r.choose(v), None);
let mut r = task_rng();
let empty: &mut [int] = &mut [];
r.shuffle(empty);
- let mut one = [1];
+ let mut one = [1i];
r.shuffle(one);
assert_eq!(one.as_slice(), &[1]);
- let mut two = [1, 2];
+ let mut two = [1i, 2];
r.shuffle(two);
assert!(two == [1, 2] || two == [2, 1]);
- let mut x = [1, 1, 1];
+ let mut x = [1i, 1, 1];
r.shuffle(x);
assert_eq!(x.as_slice(), &[1, 1, 1]);
}
fn test_task_rng() {
let mut r = task_rng();
r.gen::<int>();
- let mut v = [1, 1, 1];
+ let mut v = [1i, 1, 1];
r.shuffle(v);
assert_eq!(v.as_slice(), &[1, 1, 1]);
assert_eq!(r.gen_range(0u, 1u), 0u);
#[test]
fn test_sample() {
- let min_val = 1;
- let max_val = 100;
+ let min_val = 1i;
+ let max_val = 100i;
let mut r = task_rng();
let vals = range(min_val, max_val).collect::<Vec<int>>();
fn test_os_rng_tasks() {
let mut txs = vec!();
- for _ in range(0, 20) {
+ for _ in range(0u, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(proc() {
task::deschedule();
let mut v = [0u8, .. 1000];
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
let _c = Cleanup { handle: process, SymCleanup: SymCleanup };
// And now that we're done with all the setup, do the stack walking!
- let mut i = 0;
+ let mut i = 0i;
try!(write!(w, "stack backtrace:\n"));
while StackWalk64(image, process, thread, &mut frame, &mut context,
0 as *libc::c_void, 0 as *libc::c_void,
#[test]
fn test_get_ref_method() {
- let mut f = Future::from_value(22);
+ let mut f = Future::from_value(22i);
assert_eq!(*f.get_ref(), 22);
}
fn test_task_pool() {
let f: || -> proc(uint):Send -> uint = || { proc(i) i };
let mut pool = TaskPool::new(4, f);
- for _ in range(0, 8) {
+ for _ in range(0u, 8) {
pool.execute(proc(i) println!("Hello from thread {}!", *i));
}
}
fn test_vectors() {
let x: Vec<int> = vec![];
assert_eq!(x.to_str(), "[]".to_string());
- assert_eq!((vec![1]).to_str(), "[1]".to_string());
- assert_eq!((vec![1, 2, 3]).to_str(), "[1, 2, 3]".to_string());
- assert!((vec![vec![], vec![1], vec![1, 1]]).to_str() ==
+ assert_eq!((vec![1i]).to_str(), "[1]".to_string());
+ assert_eq!((vec![1i, 2, 3]).to_str(), "[1, 2, 3]".to_string());
+ assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_str() ==
"[[], [1], [1, 1]]".to_string());
}
}
#[test]
fn option_swap() {
- let p = AtomicOption::new(box 1);
- let a = box 2;
+ let p = AtomicOption::new(box 1i);
+ let a = box 2i;
let b = p.swap(a, SeqCst);
#[test]
fn option_take() {
- let p = AtomicOption::new(box 1);
+ let p = AtomicOption::new(box 1i);
assert!(p.take(SeqCst) == Some(box 1));
assert!(p.take(SeqCst) == None);
- let p2 = box 2;
+ let p2 = box 2i;
p.swap(p2, SeqCst);
assert!(p.take(SeqCst) == Some(box 2));
#[test]
fn option_fill() {
- let p = AtomicOption::new(box 1);
- assert!(p.fill(box 2, SeqCst).is_some()); // should fail; shouldn't leak!
+ let p = AtomicOption::new(box 1i);
+ assert!(p.fill(box 2i, SeqCst).is_some()); // should fail; shouldn't leak!
assert!(p.take(SeqCst) == Some(box 1));
- assert!(p.fill(box 2, SeqCst).is_none()); // shouldn't fail
+ assert!(p.fill(box 2i, SeqCst).is_none()); // shouldn't fail
assert!(p.take(SeqCst) == Some(box 2));
}
}
//! // Create a simple streaming channel
//! let (tx, rx) = channel();
//! spawn(proc() {
-//! tx.send(10);
+//! tx.send(10i);
//! });
-//! assert_eq!(rx.recv(), 10);
+//! assert_eq!(rx.recv(), 10i);
//! ```
//!
//! Shared usage:
//! ```
//! // Create a shared channel which can be sent along from many tasks
//! let (tx, rx) = channel();
-//! for i in range(0, 10) {
+//! for i in range(0i, 10i) {
//! let tx = tx.clone();
//! spawn(proc() {
//! tx.send(i);
//! })
//! }
//!
-//! for _ in range(0, 10) {
+//! for _ in range(0i, 10i) {
//! let j = rx.recv();
//! assert!(0 <= j && j < 10);
//! }
//! Synchronous channels:
//!
//! ```
-//! let (tx, rx) = sync_channel(0);
+//! let (tx, rx) = sync_channel::<int>(0);
//! spawn(proc() {
//! // This will wait for the parent task to start receiving
//! tx.send(53);
/// let (tx, rx) = sync_channel(1);
///
/// // this returns immediately
-/// tx.send(1);
+/// tx.send(1i);
///
/// spawn(proc() {
/// // this will block until the previous message has been received
-/// tx.send(2);
+/// tx.send(2i);
/// });
///
-/// assert_eq!(rx.recv(), 1);
-/// assert_eq!(rx.recv(), 2);
+/// assert_eq!(rx.recv(), 1i);
+/// assert_eq!(rx.recv(), 2i);
/// ```
pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
let a = Arc::new(Unsafe::new(sync::Packet::new(bound)));
/// let (tx, rx) = channel();
///
/// // This send is always successful
- /// assert_eq!(tx.send_opt(1), Ok(()));
+ /// assert_eq!(tx.send_opt(1i), Ok(()));
///
/// // This send will fail because the receiver is gone
/// drop(rx);
- /// assert_eq!(tx.send_opt(1), Err(1));
+ /// assert_eq!(tx.send_opt(1i), Err(1));
/// ```
pub fn send_opt(&self, t: T) -> Result<(), T> {
// In order to prevent starvation of other tasks in situations where
}
test!(fn smoke() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
tx.send(1);
assert_eq!(rx.recv(), 1);
})
test!(fn drop_full() {
let (tx, _rx) = channel();
- tx.send(box 1);
+ tx.send(box 1i);
})
test!(fn drop_full_shared() {
let (tx, _rx) = channel();
drop(tx.clone());
drop(tx.clone());
- tx.send(box 1);
+ tx.send(box 1i);
})
test!(fn smoke_shared() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
tx.send(1);
assert_eq!(rx.recv(), 1);
let tx = tx.clone();
})
test!(fn smoke_threads() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
spawn(proc() {
tx.send(1);
});
})
test!(fn smoke_port_gone() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
drop(rx);
tx.send(1);
} #[should_fail])
test!(fn smoke_shared_port_gone() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
drop(rx);
tx.send(1);
} #[should_fail])
test!(fn smoke_shared_port_gone2() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
drop(rx);
let tx2 = tx.clone();
drop(tx);
} #[should_fail])
test!(fn port_gone_concurrent() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
spawn(proc() {
rx.recv();
});
} #[should_fail])
test!(fn port_gone_concurrent_shared() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
let tx2 = tx.clone();
spawn(proc() {
rx.recv();
} #[should_fail])
test!(fn chan_gone_concurrent() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
spawn(proc() {
tx.send(1);
tx.send(1);
} #[should_fail])
test!(fn stress() {
- let (tx, rx) = channel();
+ let (tx, rx) = channel::<int>();
spawn(proc() {
- for _ in range(0, 10000) { tx.send(1); }
+ for _ in range(0u, 10000) { tx.send(1i); }
});
- for _ in range(0, 10000) {
+ for _ in range(0u, 10000) {
assert_eq!(rx.recv(), 1);
}
})
let tx4 = tx3.clone();
spawn(proc() {
tx1.send(());
- for _ in range(0, 40) {
+ for _ in range(0i, 40) {
assert_eq!(rx2.recv(), 1);
}
tx3.send(());
});
rx1.recv();
native::task::spawn(proc() {
- for _ in range(0, 40) {
+ for _ in range(0i, 40) {
tx2.send(1);
}
tx4.send(());
let (tx, rx) = channel::<int>();
let (dtx, drx) = channel();
native::task::spawn(proc() {
- for _ in range(0, 40) {
+ for _ in range(0i, 40) {
assert_eq!(rx.recv(), 1);
}
dtx.send(());
});
- for _ in range(0, 40) {
+ for _ in range(0u, 40) {
tx.send(1);
}
drx.recv();
for _ in range(0, stress_factor()) {
let (tx, rx) = channel();
spawn(proc() {
- tx.send(box 10);
+ tx.send(box 10i);
});
spawn(proc() {
- assert!(rx.recv() == box 10);
+ assert!(rx.recv() == box 10i);
});
}
})
test!(fn recv_a_lot() {
// Regression test that we don't run out of stack in scheduler context
let (tx, rx) = channel();
- for _ in range(0, 10000) { tx.send(()); }
- for _ in range(0, 10000) { rx.recv(); }
+ for _ in range(0i, 10000) { tx.send(()); }
+ for _ in range(0i, 10000) { rx.recv(); }
})
test!(fn shared_chan_stress() {
tx2.send(());
});
// make sure the other task has gone to sleep
- for _ in range(0, 5000) { task::deschedule(); }
+ for _ in range(0u, 5000) { task::deschedule(); }
// upgrade to a shared chan and send a message
let t = tx.clone();
let (tx, rx) = channel();
let t = Thread::start(proc() {
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
tx.send(());
}
});
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
rx.recv();
}
t.join();
}
cdone.send(());
});
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
tx.send(());
}
t.join();
}
test!(fn smoke() {
- let (tx, rx) = sync_channel(1);
+ let (tx, rx) = sync_channel::<int>(1);
tx.send(1);
assert_eq!(rx.recv(), 1);
})
test!(fn drop_full() {
let (tx, _rx) = sync_channel(1);
- tx.send(box 1);
+ tx.send(box 1i);
})
test!(fn smoke_shared() {
- let (tx, rx) = sync_channel(1);
+ let (tx, rx) = sync_channel::<int>(1);
tx.send(1);
assert_eq!(rx.recv(), 1);
let tx = tx.clone();
})
test!(fn smoke_threads() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
tx.send(1);
});
})
test!(fn smoke_port_gone() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
drop(rx);
tx.send(1);
} #[should_fail])
test!(fn smoke_shared_port_gone2() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
drop(rx);
let tx2 = tx.clone();
drop(tx);
} #[should_fail])
test!(fn port_gone_concurrent() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
rx.recv();
});
} #[should_fail])
test!(fn port_gone_concurrent_shared() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
let tx2 = tx.clone();
spawn(proc() {
rx.recv();
} #[should_fail])
test!(fn chan_gone_concurrent() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
tx.send(1);
tx.send(1);
} #[should_fail])
test!(fn stress() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
- for _ in range(0, 10000) { tx.send(1); }
+ for _ in range(0u, 10000) { tx.send(1); }
});
- for _ in range(0, 10000) {
+ for _ in range(0u, 10000) {
assert_eq!(rx.recv(), 1);
}
})
test!(fn oneshot_multi_thread_send_recv_stress() {
for _ in range(0, stress_factor()) {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<Box<int>>(0);
spawn(proc() {
- tx.send(box 10);
+ tx.send(box 10i);
});
spawn(proc() {
- assert!(rx.recv() == box 10);
+ assert!(rx.recv() == box 10i);
});
}
})
test!(fn stream_send_recv_stress() {
for _ in range(0, stress_factor()) {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<Box<int>>(0);
send(tx, 0);
recv(rx, 0);
test!(fn recv_a_lot() {
// Regression test that we don't run out of stack in scheduler context
let (tx, rx) = sync_channel(10000);
- for _ in range(0, 10000) { tx.send(()); }
- for _ in range(0, 10000) { rx.recv(); }
+ for _ in range(0u, 10000) { tx.send(()); }
+ for _ in range(0u, 10000) { rx.recv(); }
})
test!(fn shared_chan_stress() {
// This bug used to end up in a livelock inside of the Receiver destructor
// because the internal state of the Shared packet was corrupted
test!(fn destroy_upgraded_shared_port_when_sender_still_active() {
- let (tx, rx) = sync_channel(0);
- let (tx2, rx2) = sync_channel(0);
+ let (tx, rx) = sync_channel::<()>(0);
+ let (tx2, rx2) = sync_channel::<()>(0);
spawn(proc() {
rx.recv(); // wait on a oneshot
drop(rx); // destroy a shared
tx2.send(());
});
// make sure the other task has gone to sleep
- for _ in range(0, 5000) { task::deschedule(); }
+ for _ in range(0u, 5000) { task::deschedule(); }
// upgrade to a shared chan and send a message
let t = tx.clone();
test!(fn try_recvs_off_the_runtime() {
use std::rt::thread::Thread;
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<()>(0);
let (cdone, pdone) = channel();
let t = Thread::start(proc() {
let mut hits = 0;
}
cdone.send(());
});
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
tx.send(());
}
t.join();
})
test!(fn send_opt1() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() { rx.recv(); });
assert_eq!(tx.send_opt(1), Ok(()));
})
test!(fn send_opt2() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() { drop(rx); });
assert_eq!(tx.send_opt(1), Err(1));
})
test!(fn send_opt3() {
- let (tx, rx) = sync_channel(1);
+ let (tx, rx) = sync_channel::<int>(1);
assert_eq!(tx.send_opt(1), Ok(()));
spawn(proc() { drop(rx); });
assert_eq!(tx.send_opt(1), Err(1));
})
test!(fn send_opt4() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
let tx2 = tx.clone();
let (done, donerx) = channel();
let done2 = done.clone();
})
test!(fn try_send1() {
- let (tx, _rx) = sync_channel(0);
+ let (tx, _rx) = sync_channel::<int>(0);
assert_eq!(tx.try_send(1), Err(Full(1)));
})
test!(fn try_send2() {
- let (tx, _rx) = sync_channel(1);
+ let (tx, _rx) = sync_channel::<int>(1);
assert_eq!(tx.try_send(1), Ok(()));
assert_eq!(tx.try_send(1), Err(Full(1)));
})
test!(fn try_send3() {
- let (tx, rx) = sync_channel(1);
+ let (tx, rx) = sync_channel::<int>(1);
assert_eq!(tx.try_send(1), Ok(()));
drop(rx);
assert_eq!(tx.try_send(1), Err(RecvDisconnected(1)));
})
test!(fn try_send4() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
- for _ in range(0, 1000) { task::deschedule(); }
+ for _ in range(0u, 1000) { task::deschedule(); }
assert_eq!(tx.try_send(1), Ok(()));
});
assert_eq!(rx.recv(), 1);
//! let (tx1, rx1) = channel();
//! let (tx2, rx2) = channel();
//!
-//! tx1.send(1);
-//! tx2.send(2);
+//! tx1.send(1i);
+//! tx2.send(2i);
//!
//! select! {
//! val = rx1.recv() => {
-//! assert_eq!(val, 1);
+//! assert_eq!(val, 1i);
//! },
//! val = rx2.recv() => {
-//! assert_eq!(val, 2);
+//! assert_eq!(val, 2i);
//! }
//! }
//! ```
let (tx3, rx3) = channel::<int>();
spawn(proc() {
- for _ in range(0, 20) { task::deschedule(); }
+ for _ in range(0u, 20) { task::deschedule(); }
tx1.send(1);
rx3.recv();
- for _ in range(0, 20) { task::deschedule(); }
+ for _ in range(0u, 20) { task::deschedule(); }
});
select! (
let (tx3, rx3) = channel::<()>();
spawn(proc() {
- for _ in range(0, 20) { task::deschedule(); }
+ for _ in range(0u, 20) { task::deschedule(); }
tx1.send(1);
tx2.send(2);
rx3.recv();
tx3.send(());
});
- for _ in range(0, 1000) { task::deschedule(); }
+ for _ in range(0u, 1000) { task::deschedule(); }
drop(tx1.clone());
tx2.send(());
rx3.recv();
tx2.send(());
});
- for _ in range(0, 100) { task::deschedule() }
+ for _ in range(0u, 100) { task::deschedule() }
tx1.send(());
rx2.recv();
})
tx2.send(());
});
- for _ in range(0, 100) { task::deschedule() }
+ for _ in range(0u, 100) { task::deschedule() }
tx1.send(());
rx2.recv();
})
tx2.send(());
});
- for _ in range(0, 100) { task::deschedule() }
+ for _ in range(0u, 100) { task::deschedule() }
tx1.send(());
rx2.recv();
})
test!(fn sync1() {
- let (tx, rx) = sync_channel(1);
+ let (tx, rx) = sync_channel::<int>(1);
tx.send(1);
select! {
n = rx.recv() => { assert_eq!(n, 1); }
})
test!(fn sync2() {
- let (tx, rx) = sync_channel(0);
+ let (tx, rx) = sync_channel::<int>(0);
spawn(proc() {
- for _ in range(0, 100) { task::deschedule() }
+ for _ in range(0u, 100) { task::deschedule() }
tx.send(1);
});
select! {
})
test!(fn sync3() {
- let (tx1, rx1) = sync_channel(0);
- let (tx2, rx2) = channel();
+ let (tx1, rx1) = sync_channel::<int>(0);
+ let (tx2, rx2): (Sender<int>, Receiver<int>) = channel();
spawn(proc() { tx1.send(1); });
spawn(proc() { tx2.send(2); });
select! {
// size.
//
// The size in question is 1 << MIN_BITS
-static MIN_BITS: int = 7;
+static MIN_BITS: uint = 7;
struct Deque<T> {
bottom: AtomicInt,
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *T,
- log_size: int,
+ log_size: uint,
}
impl<T: Send> BufferPool<T> {
Stealer { deque: b, noshare: marker::NoShare })
}
- fn alloc(&self, bits: int) -> Box<Buffer<T>> {
+ fn alloc(&mut self, bits: uint) -> Box<Buffer<T>> {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|x| x.size() >= (1 << bits)) {
// personally going to heavily comment what's going on here.
impl<T: Send> Deque<T> {
- fn new(pool: BufferPool<T>) -> Deque<T> {
+ fn new(mut pool: BufferPool<T>) -> Deque<T> {
let buf = pool.alloc(MIN_BITS);
Deque {
bottom: AtomicInt::new(0),
}
#[inline]
-fn buffer_alloc_size<T>(log_size: int) -> uint {
+fn buffer_alloc_size<T>(log_size: uint) -> uint {
(1 << log_size) * size_of::<T>()
}
impl<T: Send> Buffer<T> {
- unsafe fn new(log_size: int) -> Buffer<T> {
+ unsafe fn new(log_size: uint) -> Buffer<T> {
let size = buffer_alloc_size::<T>(log_size);
let buffer = allocate(size, min_align_of::<T>());
Buffer {
// Again, unsafe because this has incredibly dubious ownership violations.
// It is assumed that this buffer is immediately dropped.
unsafe fn resize(&self, b: int, t: int, delta: int) -> Buffer<T> {
- let buf = Buffer::new(self.log_size + delta);
+ // NB: not entirely obvious, but thanks to 2's complement,
+ // casting delta to uint and then adding gives the desired
+ // effect.
+ let buf = Buffer::new(self.log_size + delta as uint);
for i in range(t, b) {
buf.put(i, self.get(i));
}
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
- w.push(1);
+ w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
let mut rng = rand::task_rng();
let mut expected = 0;
while expected < AMT {
- if rng.gen_range(0, 3) == 2 {
+ if rng.gen_range(0i, 3) == 2 {
match w.pop() {
None => {}
Some(2) => unsafe { HITS.fetch_add(1, SeqCst); },
let mut myhit = false;
'outer: loop {
for _ in range(0, rng.gen_range(0, AMT)) {
- if !myhit && rng.gen_range(0, 3) == 2 {
+ if !myhit && rng.gen_range(0i, 3) == 2 {
match w.pop() {
None => {}
Some((1, 2)) => myhit = true,
/// ```
/// use sync::{RWLock, Arc};
///
-/// let lock1 = Arc::new(RWLock::new(1));
+/// let lock1 = Arc::new(RWLock::new(1i));
/// let lock2 = lock1.clone();
///
/// spawn(proc() {
/// use sync::{Arc, Barrier};
///
/// let barrier = Arc::new(Barrier::new(10));
-/// for _ in range(0, 10) {
+/// for _ in range(0u, 10) {
/// let c = barrier.clone();
/// // The same messages will be printed together.
/// // You will NOT see any interleaving.
#[test] #[should_fail]
fn test_mutex_arc_poison() {
- let arc = Arc::new(Mutex::new(1));
+ let arc = Arc::new(Mutex::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.lock();
fn test_mutex_arc_nested() {
// Tests nested mutexes and access
// to underlying data.
- let arc = Arc::new(Mutex::new(1));
+ let arc = Arc::new(Mutex::new(1i));
let arc2 = Arc::new(Mutex::new(arc));
task::spawn(proc() {
let lock = arc2.lock();
#[test] #[should_fail]
fn test_rw_arc_poison_wr() {
- let arc = Arc::new(RWLock::new(1));
+ let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.write();
}
#[test] #[should_fail]
fn test_rw_arc_poison_ww() {
- let arc = Arc::new(RWLock::new(1));
+ let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.write();
}
#[test]
fn test_rw_arc_no_poison_rr() {
- let arc = Arc::new(RWLock::new(1));
+ let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.read();
}
#[test]
fn test_rw_arc_no_poison_rw() {
- let arc = Arc::new(RWLock::new(1));
+ let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.read();
}
#[test]
fn test_rw_arc_no_poison_dr() {
- let arc = Arc::new(RWLock::new(1));
+ let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
let _ = task::try(proc() {
let lock = arc2.write().downgrade();
#[test]
fn test_rw_arc() {
- let arc = Arc::new(RWLock::new(0));
+ let arc = Arc::new(RWLock::new(0i));
let arc2 = arc.clone();
let (tx, rx) = channel();
task::spawn(proc() {
let mut lock = arc2.write();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
let tmp = *lock;
*lock = -1;
task::deschedule();
// Readers try to catch the writer in the act
let mut children = Vec::new();
- for _ in range(0, 5) {
+ for _ in range(0u, 5) {
let arc3 = arc.clone();
children.push(try_future(proc() {
let lock = arc3.read();
// (4) tells writer and all other readers to contend as it downgrades.
// (5) Writer attempts to set state back to 42, while downgraded task
// and all reader tasks assert that it's 31337.
- let arc = Arc::new(RWLock::new(0));
+ let arc = Arc::new(RWLock::new(0i));
// Reader tasks
let mut reader_convos = Vec::new();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
let ((tx1, rx1), (tx2, rx2)) = (channel(), channel());
reader_convos.push((tx1, rx2));
let arcn = arc.clone();
let lock = lock.downgrade();
// if writer mistakenly got in, make sure it mutates state
// before we assert on it
- for _ in range(0, 5) { task::deschedule(); }
+ for _ in range(0u, 5) { task::deschedule(); }
// make sure writer didn't get in.
assert!(*lock);
}
// deschedules in the intuitively-right locations made it even less
// likely, and I wasn't sure why :( . This is a mediocre "next best"
// option.
- for _ in range(0, 8) {
+ for _ in range(0u, 8) {
test_rw_write_cond_downgrade_read_race_helper();
}
}
let barrier = Arc::new(Barrier::new(10));
let (tx, rx) = channel();
- for _ in range(0, 9) {
+ for _ in range(0u, 9) {
let c = barrier.clone();
let tx = tx.clone();
spawn(proc() {
barrier.wait();
// Now, the barrier is cleared and we should get data.
- for _ in range(0, 9) {
+ for _ in range(0u, 9) {
rx.recv();
}
}
#[test]
fn smoke_once() {
static mut o: Once = ONCE_INIT;
- let mut a = 0;
+ let mut a = 0i;
unsafe { o.doit(|| a += 1); }
assert_eq!(a, 1);
unsafe { o.doit(|| a += 1); }
static mut run: bool = false;
let (tx, rx) = channel();
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
let tx = tx.clone();
spawn(proc() {
- for _ in range(0, 4) { task::deschedule() }
+ for _ in range(0u, 4) { task::deschedule() }
unsafe {
o.doit(|| {
assert!(!run);
assert!(run);
}
- for _ in range(0, 10) {
+ for _ in range(0u, 10) {
rx.recv();
}
}
});
// Uncomment if you wish to test for sem races. Not
// valgrind-friendly.
- /* for _ in range(0, 1000) { task::deschedule(); } */
+ /* for _ in range(0u, 1000) { task::deschedule(); } */
// Need to wait outside the exclusive.
if waiter_nobe.is_some() {
let _ = waiter_nobe.unwrap().recv();
let s2 = s.clone();
task::spawn(proc() {
let _g = s2.access();
- for _ in range(0, 5) { task::deschedule(); }
+ for _ in range(0u, 5) { task::deschedule(); }
});
let _g = s.access();
- for _ in range(0, 5) { task::deschedule(); }
+ for _ in range(0u, 5) { task::deschedule(); }
}
#[test]
fn test_sem_as_cvar() {
s2.acquire();
tx.send(());
});
- for _ in range(0, 5) { task::deschedule(); }
+ for _ in range(0u, 5) { task::deschedule(); }
s.release();
let _ = rx.recv();
let s = Arc::new(Semaphore::new(0));
let s2 = s.clone();
task::spawn(proc() {
- for _ in range(0, 5) { task::deschedule(); }
+ for _ in range(0u, 5) { task::deschedule(); }
s2.release();
let _ = rx.recv();
});
tx.send(());
});
rx.recv(); // wait for child to come alive
- for _ in range(0, 5) { task::deschedule(); } // let the child contend
+ for _ in range(0u, 5) { task::deschedule(); } // let the child contend
}
rx.recv(); // wait for child to be done
}
}
fn access_shared(sharedstate: *mut int, m: &Arc<Mutex>, n: uint) {
- for _ in range(0, n) {
+ for _ in range(0u, n) {
let _g = m.lock();
let oldval = unsafe { *sharedstate };
task::deschedule();
let m = Arc::new(Mutex::new());
let mut rxs = Vec::new();
- for _ in range(0, num_waiters) {
+ for _ in range(0u, num_waiters) {
let mi = m.clone();
let (tx, rx) = channel();
rxs.push(rx);
fn access_shared(sharedstate: &mut int, x: &Arc<RWLock>,
mode: RWLockMode, n: uint) {
- for _ in range(0, n) {
+ for _ in range(0u, n) {
lock_rwlock_in_mode(x, mode, || {
let oldval = *sharedstate;
task::deschedule();
let x = Arc::new(RWLock::new());
let mut rxs = Vec::new();
- for _ in range(0, num_waiters) {
+ for _ in range(0u, num_waiters) {
let xi = x.clone();
let (tx, rx) = channel();
rxs.push(rx);
#[test]
fn smoke() {
let q = Queue::new(0);
- q.push(1);
+ q.push(1i);
q.push(2);
assert_eq!(q.pop(), Some(1));
assert_eq!(q.pop(), Some(2));
#[test]
fn smoke_bound() {
let q = Queue::new(1);
- q.push(1);
+ q.push(1i);
q.push(2);
assert_eq!(q.pop(), Some(1));
assert_eq!(q.pop(), Some(2));
let b = a.clone();
let (tx, rx) = channel();
native::task::spawn(proc() {
- for _ in range(0, 100000) {
+ for _ in range(0u, 100000) {
loop {
match b.pop() {
Some(1) => break,
}
tx.send(());
});
- for _ in range(0, 100000) {
+ for _ in range(0i, 100000) {
a.push(1);
}
rx.recv();
impl Architecture {
fn bit(&self) -> u32 {
- 1 << (*self as u32)
+ 1 << (*self as uint)
}
}
assert_eq!(i, abi_data.abi.index());
}
- let bits = 1 << (X86 as u32);
- let bits = bits | 1 << (X86_64 as u32);
+ let bits = 1 << (X86 as uint);
+ let bits = bits | 1 << (X86_64 as uint);
assert_eq!(IntelBits, bits);
- let bits = 1 << (Arm as u32);
+ let bits = 1 << (Arm as uint);
assert_eq!(ArmBits, bits);
}
impl fmt::Show for IntTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}",
- ast_util::int_ty_to_str(*self, None, ast_util::AutoSuffix))
+ write!(f, "{}", ast_util::int_ty_to_str(*self, None))
}
}
impl fmt::Show for UintTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}",
- ast_util::uint_ty_to_str(*self, None, ast_util::AutoSuffix))
+ write!(f, "{}", ast_util::uint_ty_to_str(*self, None))
}
}
return match e.node { ExprPath(_) => true, _ => false };
}
-pub enum SuffixMode {
- ForceSuffix,
- AutoSuffix,
-}
-
// Get a string representation of a signed int type, with its value.
// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
-pub fn int_ty_to_str(t: IntTy, val: Option<i64>, mode: SuffixMode) -> String {
+pub fn int_ty_to_str(t: IntTy, val: Option<i64>) -> String {
let s = match t {
- TyI if val.is_some() => match mode {
- AutoSuffix => "",
- ForceSuffix => "i",
- },
+ TyI if val.is_some() => "i",
TyI => "int",
TyI8 => "i8",
TyI16 => "i16",
// Get a string representation of an unsigned int type, with its value.
// We want to avoid "42uint" in favor of "42u"
-pub fn uint_ty_to_str(t: UintTy, val: Option<u64>, mode: SuffixMode) -> String {
+pub fn uint_ty_to_str(t: UintTy, val: Option<u64>) -> String {
let s = match t {
- TyU if val.is_some() => match mode {
- AutoSuffix => "",
- ForceSuffix => "u",
- },
+ TyU if val.is_some() => "u",
TyU => "uint",
TyU8 => "u8",
TyU16 => "u16",
.collect());
let mut es = Vec::new();
while p.token != token::EOF {
- if es.len() != 0 && !p.eat(&token::COMMA) {
+ es.push(cx.expand_expr(p.parse_expr()));
+ if p.eat(&token::COMMA) {
+ continue;
+ }
+ if p.token != token::EOF {
cx.span_err(sp, "expected token: `,`");
return None;
}
- es.push(cx.expand_expr(p.parse_expr()));
}
Some(es)
}
pub mod rt {
use ast;
+ use codemap::Spanned;
use ext::base::ExtCtxt;
use parse::token;
use parse;
fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> ;
}
+ impl ToTokens for TokenTree {
+ fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
+ vec!(self.clone())
+ }
+ }
+
impl ToTokens for Vec<TokenTree> {
fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
(*self).clone()
}
}
+ impl<T: ToTokens> ToTokens for Spanned<T> {
+ fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
+ // FIXME: use the span?
+ self.node.to_tokens(cx)
+ }
+ }
+
/* Should be (when bugs in default methods are fixed):
trait ToSource : ToTokens {
*/
+ // FIXME: Move this trait to pprust and get rid of *_to_str?
pub trait ToSource {
// Takes a thing and generates a string containing rust code for it.
fn to_source(&self) -> String;
}
- impl ToSource for ast::Ident {
- fn to_source(&self) -> String {
- token::get_ident(*self).get().to_string()
- }
- }
-
- impl ToSource for Gc<ast::Item> {
- fn to_source(&self) -> String {
- pprust::item_to_str(&**self)
- }
- }
-
- impl<'a> ToSource for &'a [Gc<ast::Item>] {
- fn to_source(&self) -> String {
- self.iter()
- .map(|i| i.to_source())
- .collect::<Vec<String>>()
- .connect("\n\n")
- .to_string()
- }
- }
-
- impl ToSource for ast::Ty {
- fn to_source(&self) -> String {
- pprust::ty_to_str(self)
- }
- }
-
- impl<'a> ToSource for &'a [ast::Ty] {
- fn to_source(&self) -> String {
- self.iter()
- .map(|i| i.to_source())
- .collect::<Vec<String>>()
- .connect(", ")
- .to_string()
- }
- }
+ macro_rules! impl_to_source(
+ (Gc<$t:ty>, $pp:ident) => (
+ impl ToSource for Gc<$t> {
+ fn to_source(&self) -> String {
+ pprust::$pp(&**self)
+ }
+ }
+ );
+ ($t:ty, $pp:ident) => (
+ impl ToSource for $t {
+ fn to_source(&self) -> String {
+ pprust::$pp(self)
+ }
+ }
+ );
+ )
- impl ToSource for Generics {
- fn to_source(&self) -> String {
- pprust::generics_to_str(self)
- }
+ fn slice_to_source<'a, T: ToSource>(sep: &'static str, xs: &'a [T]) -> String {
+ xs.iter()
+ .map(|i| i.to_source())
+ .collect::<Vec<String>>()
+ .connect(sep)
+ .to_string()
}
- impl ToSource for Gc<ast::Expr> {
- fn to_source(&self) -> String {
- pprust::expr_to_str(&**self)
- }
- }
+ macro_rules! impl_to_source_slice(
+ ($t:ty, $sep:expr) => (
+ impl<'a> ToSource for &'a [$t] {
+ fn to_source(&self) -> String {
+ slice_to_source($sep, *self)
+ }
+ }
+ )
+ )
- impl ToSource for ast::Block {
+ impl ToSource for ast::Ident {
fn to_source(&self) -> String {
- pprust::block_to_str(self)
+ token::get_ident(*self).get().to_string()
}
}
- impl ToSource for ast::Arg {
- fn to_source(&self) -> String {
- pprust::arg_to_str(self)
- }
- }
+ impl_to_source!(ast::Ty, ty_to_str)
+ impl_to_source!(ast::Block, block_to_str)
+ impl_to_source!(ast::Arg, arg_to_str)
+ impl_to_source!(Generics, generics_to_str)
+ impl_to_source!(Gc<ast::Item>, item_to_str)
+ impl_to_source!(Gc<ast::Expr>, expr_to_str)
+ impl_to_source!(Gc<ast::Pat>, pat_to_str)
+ impl_to_source_slice!(ast::Ty, ", ")
+ impl_to_source_slice!(Gc<ast::Item>, "\n\n")
impl<'a> ToSource for &'a str {
fn to_source(&self) -> String {
}
}
- impl ToSource for int {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for i8 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI8));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for i16 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI16));
- pprust::lit_to_str(&lit)
- }
- }
-
-
- impl ToSource for i32 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI32));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for i64 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI64));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for uint {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for u8 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU8));
- pprust::lit_to_str(&lit)
- }
- }
-
- impl ToSource for u16 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU16));
- pprust::lit_to_str(&lit)
- }
- }
+ macro_rules! impl_to_source_int(
+ (signed, $t:ty, $tag:ident) => (
+ impl ToSource for $t {
+ fn to_source(&self) -> String {
+ let lit = dummy_spanned(ast::LitInt(*self as i64, ast::$tag));
+ pprust::lit_to_str(&lit)
+ }
+ }
+ );
+ (unsigned, $t:ty, $tag:ident) => (
+ impl ToSource for $t {
+ fn to_source(&self) -> String {
+ let lit = dummy_spanned(ast::LitUint(*self as u64, ast::$tag));
+ pprust::lit_to_str(&lit)
+ }
+ }
+ );
+ )
- impl ToSource for u32 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU32));
- pprust::lit_to_str(&lit)
- }
- }
+ impl_to_source_int!(signed, int, TyI)
+ impl_to_source_int!(signed, i8, TyI8)
+ impl_to_source_int!(signed, i16, TyI16)
+ impl_to_source_int!(signed, i32, TyI32)
+ impl_to_source_int!(signed, i64, TyI64)
- impl ToSource for u64 {
- fn to_source(&self) -> String {
- let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU64));
- pprust::lit_to_str(&lit)
- }
- }
+ impl_to_source_int!(unsigned, uint, TyU)
+ impl_to_source_int!(unsigned, u8, TyU8)
+ impl_to_source_int!(unsigned, u16, TyU16)
+ impl_to_source_int!(unsigned, u32, TyU32)
+ impl_to_source_int!(unsigned, u64, TyU64)
// Alas ... we write these out instead. All redundant.
)
)
- macro_rules! impl_to_tokens_self(
+ macro_rules! impl_to_tokens_lifetime(
($t:ty) => (
impl<'a> ToTokens for $t {
fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
impl_to_tokens!(ast::Ident)
impl_to_tokens!(Gc<ast::Item>)
- impl_to_tokens_self!(&'a [Gc<ast::Item>])
+ impl_to_tokens!(Gc<ast::Pat>)
+ impl_to_tokens_lifetime!(&'a [Gc<ast::Item>])
impl_to_tokens!(ast::Ty)
- impl_to_tokens_self!(&'a [ast::Ty])
+ impl_to_tokens_lifetime!(&'a [ast::Ty])
impl_to_tokens!(Generics)
impl_to_tokens!(Gc<ast::Expr>)
impl_to_tokens!(ast::Block)
impl_to_tokens!(ast::Arg)
- impl_to_tokens_self!(&'a str)
+ impl_to_tokens_lifetime!(&'a str)
impl_to_tokens!(())
impl_to_tokens!(char)
impl_to_tokens!(bool)
}
// parse an expression, subject to the given restriction
- fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
+ pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
let old = self.restriction;
self.restriction = r;
let e = self.parse_assign_expr();
res.push_char('\'');
res
}
- LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i),
- ast_util::ForceSuffix),
- LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u),
- ast_util::ForceSuffix),
+ LIT_INT(i, t) => ast_util::int_ty_to_str(t, Some(i)),
+ LIT_UINT(u, t) => ast_util::uint_ty_to_str(t, Some(u)),
LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str() }
LIT_FLOAT(s, t) => {
let mut body = String::from_str(get_ident(s).get());
let n: uint = 3 * linewidth;
debug!("mk_printer {}", linewidth);
let token: Vec<Token> = Vec::from_elem(n, Eof);
- let size: Vec<int> = Vec::from_elem(n, 0);
+ let size: Vec<int> = Vec::from_elem(n, 0i);
let scan_stack: Vec<uint> = Vec::from_elem(n, 0u);
Printer {
out: out,
}
ast::LitInt(i, t) => {
word(&mut self.s,
- ast_util::int_ty_to_str(t, Some(i),
- ast_util::AutoSuffix).as_slice())
+ ast_util::int_ty_to_str(t, Some(i)).as_slice())
}
ast::LitUint(u, t) => {
word(&mut self.s,
- ast_util::uint_ty_to_str(t, Some(u),
- ast_util::ForceSuffix).as_slice())
+ ast_util::uint_ty_to_str(t, Some(u)).as_slice())
}
ast::LitIntUnsuffixed(i) => {
word(&mut self.s, format!("{}", i).as_slice())
#[test]
fn test_push_get() {
let mut v = SmallVector::zero();
- v.push(1);
+ v.push(1i);
assert_eq!(1, v.len());
assert_eq!(&1, v.get(0));
v.push(2);
#[test]
fn test_from_iter() {
- let v: SmallVector<int> = (vec!(1, 2, 3)).move_iter().collect();
+ let v: SmallVector<int> = (vec!(1i, 2, 3)).move_iter().collect();
assert_eq!(3, v.len());
assert_eq!(&1, v.get(0));
assert_eq!(&2, v.get(1));
let v: Vec<int> = v.move_iter().collect();
assert_eq!(Vec::new(), v);
- let v = SmallVector::one(1);
- assert_eq!(vec!(1), v.move_iter().collect());
+ let v = SmallVector::one(1i);
+ assert_eq!(vec!(1i), v.move_iter().collect());
- let v = SmallVector::many(vec!(1, 2, 3));
- assert_eq!(vec!(1, 2, 3), v.move_iter().collect());
+ let v = SmallVector::many(vec!(1i, 2i, 3i));
+ assert_eq!(vec!(1i, 2i, 3i), v.move_iter().collect());
}
#[test]
#[test]
fn test_expect_one_one() {
- assert_eq!(1, SmallVector::one(1).expect_one(""));
- assert_eq!(1, SmallVector::many(vec!(1)).expect_one(""));
+ assert_eq!(1i, SmallVector::one(1i).expect_one(""));
+ assert_eq!(1i, SmallVector::many(vec!(1i)).expect_one(""));
}
}
'c' => if stack.len() > 0 {
match stack.pop().unwrap() {
// if c is 0, use 0200 (128) for ncurses compatibility
- Number(c) => output.push(if c == 0 { 128 } else { c } as u8),
+ Number(c) => {
+ output.push(if c == 0 {
+ 128u8
+ } else {
+ c as u8
+ })
+ }
_ => return Err("a non-char was used with %c".to_string())
}
} else { return Err("stack is empty".to_string()) },
let magic = try!(file.read_le_u16());
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x} but found {:x}",
- 0x011A, magic as uint));
+ 0x011Au, magic as uint));
}
let names_bytes = try!(file.read_le_i16()) as int;
}
pub fn write_metric_diff(&mut self, diff: &MetricDiff) -> io::IoResult<()> {
- let mut noise = 0;
- let mut improved = 0;
- let mut regressed = 0;
- let mut added = 0;
- let mut removed = 0;
+ let mut noise = 0u;
+ let mut improved = 0u;
+ let mut regressed = 0u;
+ let mut added = 0u;
+ let mut removed = 0u;
for (k, v) in diff.iter() {
match *v {
assert_eq!(out, expected);
}
- t(&Summary::new([-2.0, -1.0]),
+ t(&Summary::new([-2.0f64, -1.0f64]),
"-2 |[------******#*****---]| -1".to_string());
- t(&Summary::new([0.0, 2.0]),
+ t(&Summary::new([0.0f64, 2.0f64]),
"0 |[-------*****#*******---]| 2".to_string());
- t(&Summary::new([-2.0, 0.0]),
+ t(&Summary::new([-2.0f64, 0.0f64]),
"-2 |[------******#******---]| 0".to_string());
}
#[test]
fn test_sum_f64s() {
- assert_eq!([0.5, 3.2321, 1.5678].sum(), 5.2999);
+ assert_eq!([0.5f64, 3.2321f64, 1.5678f64].sum(), 5.2999);
}
#[test]
fn test_sum_f64_between_ints_that_sum_to_0() {
- assert_eq!([1e30, 1.2, -1e30].sum(), 1.2);
+ assert_eq!([1e30f64, 1.2f64, -1e30f64].sum(), 1.2);
}
}
#[bench]
pub fn sum_three_items(b: &mut Bencher) {
b.iter(|| {
- [1e20, 1.5, -1e20].sum();
+ [1e20f64, 1.5f64, -1e20f64].sum();
})
}
#[bench]
pub fn sum_many_f64(b: &mut Bencher) {
- let nums = [-1e30, 1e60, 1e30, 1.0, -1e60];
+ let nums = [-1e30f64, 1e60, 1e30, 1.0, -1e60];
let v = Vec::from_fn(500, |i| nums[i%5]);
b.iter(|| {
}
pub fn foo() {
- let a = &1 as &inner::Trait;
+ let a = &1i as &inner::Trait;
a.f();
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// force-host
+
+#![feature(phase, plugin_registrar)]
+
+extern crate syntax;
+
+// Load rustc as a plugin to get macros
+#[phase(plugin, link)]
+extern crate rustc;
+
+use syntax::ast;
+use syntax::parse::token;
+use rustc::lint::{Context, LintPass, LintPassObject, LintArray};
+use rustc::plugin::Registry;
+
+declare_lint!(TEST_LINT, Warn,
+ "Warn about items named 'lintme'")
+
+struct Pass;
+
+impl LintPass for Pass {
+ fn get_lints(&self) -> LintArray {
+ lint_array!(TEST_LINT)
+ }
+
+ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
+ let name = token::get_ident(it.ident);
+ if name.get() == "lintme" {
+ cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
+ }
+ }
+}
+
+#[plugin_registrar]
+pub fn plugin_registrar(reg: &mut Registry) {
+ reg.register_lint_pass(box Pass as LintPassObject);
+}
use std::gc::{Gc, GC};
#[macro_export]
-macro_rules! exported_macro (() => (2))
+macro_rules! exported_macro (() => (2i))
-macro_rules! unexported_macro (() => (3))
+macro_rules! unexported_macro (() => (3i))
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
}
fn shift_push() {
- let mut v1 = Vec::from_elem(30000, 1);
+ let mut v1 = Vec::from_elem(30000, 1i);
let mut v2 = Vec::new();
while v1.len() > 0 {
let mut path = Path::new(env!("CFG_SRC_DIR"));
path.push("src/test/bench/shootout-k-nucleotide.data");
- for _ in range(0, 3) {
+ for _ in range(0u, 3) {
let mut reader = BufferedReader::new(File::open(&path).unwrap());
for _line in reader.lines() {
}
let mut pixels = [0f32, ..256*256];
let n2d = Noise2DContext::new();
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
for y in range(0u, 256) {
for x in range(0u, 256) {
let v = n2d.get(x as f32 * 0.1, y as f32 * 0.1);
let mut messages = range_step(min_depth, max_depth + 1, 2).map(|depth| {
use std::num::pow;
- let iterations = pow(2, (max_depth - depth + min_depth) as uint);
+ let iterations = pow(2i, (max_depth - depth + min_depth) as uint);
Future::spawn(proc() {
let mut chk = 0;
for i in range(1, iterations + 1) {
to_rendezvous: Sender<CreatureInfo>,
to_rendezvous_log: Sender<String>
) {
- let mut creatures_met = 0;
+ let mut creatures_met = 0i32;
let mut evil_clones_met = 0;
let mut rendezvous = from_rendezvous.iter();
let mut perm = Vec::from_fn(n, |e| ((n + e - i) % n + 1) as i32);
let mut tperm = perm.clone();
let mut count = Vec::from_elem(n, 0u);
- let mut perm_count = 0;
+ let mut perm_count = 0i;
let mut checksum = 0;
for countdown in range(1, fact(n - 1) + 1).rev() {
if x < 0 || x > 4 {return None;}
let y = y + dy;
if y < 0 || y > 9 {return None;}
- m |= 1 << (y * 5 + x);
+ m |= 1 << (y * 5 + x) as uint;
}
Some(m)
}
// (i/5, i%5).
fn make_masks() -> Vec<Vec<Vec<u64> > > {
let pieces = vec!(
- vec!((0,0),(0,1),(0,2),(0,3),(1,3)),
- vec!((0,0),(0,2),(0,3),(1,0),(1,1)),
- vec!((0,0),(0,1),(0,2),(1,2),(2,1)),
- vec!((0,0),(0,1),(0,2),(1,1),(2,1)),
- vec!((0,0),(0,2),(1,0),(1,1),(2,1)),
- vec!((0,0),(0,1),(0,2),(1,1),(1,2)),
- vec!((0,0),(0,1),(1,1),(1,2),(2,1)),
- vec!((0,0),(0,1),(0,2),(1,0),(1,2)),
- vec!((0,0),(0,1),(0,2),(1,2),(1,3)),
- vec!((0,0),(0,1),(0,2),(0,3),(1,2)));
+ vec!((0i,0i),(0,1),(0,2),(0,3),(1,3)),
+ vec!((0i,0i),(0,2),(0,3),(1,0),(1,1)),
+ vec!((0i,0i),(0,1),(0,2),(1,2),(2,1)),
+ vec!((0i,0i),(0,1),(0,2),(1,1),(2,1)),
+ vec!((0i,0i),(0,2),(1,0),(1,1),(2,1)),
+ vec!((0i,0i),(0,1),(0,2),(1,1),(1,2)),
+ vec!((0i,0i),(0,1),(1,1),(1,2),(2,1)),
+ vec!((0i,0i),(0,1),(0,2),(1,0),(1,2)),
+ vec!((0i,0i),(0,1),(0,2),(1,2),(1,3)),
+ vec!((0i,0i),(0,1),(0,2),(0,3),(1,2)));
// To break the central symetry of the problem, every
// transformation must be taken except for one piece (piece 3
.map(|(id, p)| transform(p, id != 3))
.collect();
- range(0, 50).map(|yx| {
+ range(0i, 50).map(|yx| {
transforms.iter().enumerate().map(|(id, t)| {
t.iter().filter_map(|p| mask(yx / 5, yx % 5, id, p)).collect()
}).collect()
// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
for id in range(0u8, 10) {
- if m & (1 << (id + 50)) != 0 {return id;}
+ if m & (1 << (id + 50) as uint) != 0 {return id;}
}
fail!("{:016x} does not have a valid identifier", m);
}
}
fn stress_task(id: int) {
- let mut i = 0;
+ let mut i = 0i;
loop {
- let n = 15;
+ let n = 15i;
assert_eq!(fib(n), fib(n));
i += 1;
println!("{}: Completed {} iterations", id, i);
let num_trials = 10;
for n in range(1, max + 1) {
- for _ in range(0, num_trials) {
+ for _ in range(0u, num_trials) {
let start = time::precise_time_ns();
let fibn = fib(n);
let stop = time::precise_time_ns();
} else {
FromStr::from_str(args[1].as_slice()).unwrap()
};
- let u = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
- let v = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
- let tmp = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
- for _ in range(0, 10) {
+ let u = Arc::new(RWLock::new(Vec::from_elem(n, 1f64)));
+ let v = Arc::new(RWLock::new(Vec::from_elem(n, 1f64)));
+ let tmp = Arc::new(RWLock::new(Vec::from_elem(n, 1f64)));
+ for _ in range(0u8, 10) {
mult_AtAv(u.clone(), v.clone(), tmp.clone());
mult_AtAv(v.clone(), u.clone(), tmp.clone());
}
}
fn main() {
- for _ in range(1, 100_000) {
+ for _ in range(1u32, 100_000) {
spawn(proc() {})
}
}
impl Colors {
fn new(start_color: u8) -> Colors {
// Sets bits 9..start_color
- let tails = !0u16 << start_color;
+ let tails = !0u16 << start_color as uint;
return Colors(HEADS & tails);
}
fn remove(&mut self, color: u8) {
if color != 0u8 {
let Colors(val) = *self;
- let mask = !(1u16 << color);
+ let mask = !(1u16 << color as uint);
*self = Colors(val & mask);
}
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+
+#![feature(phase)]
+#![deny(test_lint)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { } //~ ERROR item is named 'lintme'
+
+pub fn main() {
+ lintme();
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+// compile-flags: -D test-lint
+
+#![feature(phase)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { } //~ ERROR item is named 'lintme'
+
+pub fn main() {
+ lintme();
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+
+#![feature(phase)]
+#![forbid(test_lint)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { } //~ ERROR item is named 'lintme'
+
+#[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
+pub fn main() {
+ lintme();
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+// compile-flags: -F test-lint
+
+#![feature(phase)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { } //~ ERROR item is named 'lintme'
+
+#[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
+pub fn main() {
+ lintme();
+}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Issue #12534.
+
+struct A(Box<uint>);
+
+fn f(a @ A(u): A) -> Box<uint> { //~ ERROR cannot bind by-move with sub-bindings
+ drop(a);
+ u
+}
+
+fn main() {}
+
}
fn main() {
- let i = 8;
+ let i = 8i;
let f = coerce(|| println!("{:?}", i) );
f();
}
let mut v = box 3;
let mut x = &mut v;
- for _ in range(0, 3) {
+ for _ in range(0i, 3) {
borrow(v); //~ ERROR cannot borrow
}
*x = box 5;
None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
- x = Some(0);
+ x = Some(0i);
}
Some(ref _i) => {
- x = Some(1); //~ ERROR cannot assign
+ x = Some(1i); //~ ERROR cannot assign
}
}
x.clone(); // just to prevent liveness warnings
}
fn box_imm() {
- let v = box 3;
+ let v = box 3i;
let _w = &v;
task::spawn(proc() {
println!("v={}", *v);
}
fn box_imm_explicit() {
- let v = box 3;
+ let v = box 3i;
let _w = &v;
task::spawn(proc() {
println!("v={}", *v);
use std::gc::GC;
fn testfn(cond: bool) {
- let mut x = box(GC) 3;
- let mut y = box(GC) 4;
+ let mut x = box(GC) 3i;
+ let mut y = box(GC) 4i;
// borrow x and y
let r_x = &*x;
println!("*r = {}, exp = {}", *r, exp);
assert_eq!(*r, exp);
- x = box(GC) 5; //~ERROR cannot assign to `x` because it is borrowed
- y = box(GC) 6; //~ERROR cannot assign to `y` because it is borrowed
+ x = box(GC) 5i; //~ERROR cannot assign to `x` because it is borrowed
+ y = box(GC) 6i; //~ERROR cannot assign to `y` because it is borrowed
println!("*r = {}, exp = {}", *r, exp);
assert_eq!(*r, exp);
- assert_eq!(x, box(GC) 5);
- assert_eq!(y, box(GC) 6);
+ assert_eq!(x, box(GC) 5i);
+ assert_eq!(y, box(GC) 6i);
}
pub fn main() {
fn test(cond: bool) {
let v;
while cond {
- v = 3;
+ v = 3i;
break;
}
println!("{}", v); //~ ERROR use of possibly uninitialized variable: `v`
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
- let foo = ['h' as u8, 'i' as u8, 0 as u8];
- let bar = &foo as *u8; //~ ERROR mismatched types
-}
// if n > m, it's a type mismatch error.
// n < m
- let &x = &(&1 as &T);
- let &x = &&(&1 as &T);
- let &&x = &&(&1 as &T);
+ let &x = &(&1i as &T);
+ let &x = &&(&1i as &T);
+ let &&x = &&(&1i as &T);
// n == m
- let &x = &1 as &T; //~ ERROR cannot be dereferenced
- let &&x = &(&1 as &T); //~ ERROR cannot be dereferenced
- let box x = box 1 as Box<T>; //~ ERROR cannot be dereferenced
+ let &x = &1i as &T; //~ ERROR cannot be dereferenced
+ let &&x = &(&1i as &T); //~ ERROR cannot be dereferenced
+ let box x = box 1i as Box<T>; //~ ERROR cannot be dereferenced
// n > m
- let &&x = &1 as &T; //~ ERROR found an `&`-pointer pattern
- let &&&x = &(&1 as &T); //~ ERROR found an `&`-pointer pattern
- let box box x = box 1 as Box<T>; //~ ERROR found a box pattern
+ let &&x = &1i as &T; //~ ERROR found an `&`-pointer pattern
+ let &&&x = &(&1i as &T); //~ ERROR found an `&`-pointer pattern
+ let box box x = box 1i as Box<T>; //~ ERROR found a box pattern
}
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait Foo {}
+
+struct A;
+
+impl Foo for A {}
+
+struct B<'a>(&'a Foo);
+
+fn foo<'a>(a: &Foo) -> B<'a> {
+ B(a) //~ ERROR cannot infer an appropriate lifetime
+}
+
+fn main() {
+ let _test = foo(&A);
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub enum T {
+ T1(()),
+ T2(())
+}
+
+pub enum V {
+ V1(int),
+ V2(bool)
+}
+
+fn main() {
+ match (T1(()), V2(true)) {
+ //~^ ERROR non-exhaustive patterns: `(T1(()), V2(_))` not covered
+ (T1(()), V1(i)) => (),
+ (T2(()), V2(b)) => ()
+ }
+}
}
fn main() {
- let v = &5;
+ let v = &5i;
println!("{}", f(v)());
}
fn bar(int_param: int) {}
fn main() {
- let foo: [u8, ..4] = [1u8, ..4u8];
+ let foo: [u8, ..4] = [1u8, ..4u];
bar(foo);
//~^ ERROR mismatched types: expected `int` but found `[u8, .. 4]`
// (expected int but found vector)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ignore-test FIXME: #13992
-
struct A { foo: int }
fn main() {
- let A { foo, foo } = A { foo: 3 }; //~ ERROR: field `foo` bound twice
+ let A { foo, foo } = A { foo: 3 };
+ //~^ ERROR: identifier `foo` is bound more than once in the same pattern
}
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait X {
+ fn get_i(&self) -> int;
+}
+
+
+struct B {
+ i: int
+}
+
+impl X for B {
+ fn get_i(&self) -> int {
+ self.i
+ }
+}
+
+struct A<'a> {
+ p: &'a X
+}
+
+fn make_a<'a>(p: &'a X) -> A<'a> {
+ A { p: p }
+}
+
+fn make_make_a() -> A {
+ let b: Box<B> = box B {i:1};
+ let bb: &B = b; //~ ERROR does not live long enough
+ make_a(bb)
+}
+
+fn main() {
+ let _a = make_make_a();
+}
// ~Repeat<&'blk int> where blk is the lifetime of the block below.
let y = {
- let tmp0 = 3;
+ let tmp0 = 3i;
let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough
repeater(tmp1)
};
}
pub fn foo() {
- let a = &1 as &inner::Trait;
+ let a = &1i as &inner::Trait;
a.f();
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![forbid(experimental)]
+
+#[allow(experimental)] //~ ERROR allow(experimental) overruled by outer forbid(experimental)
+fn main() {
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: -F experimental
+
+#[allow(experimental)] //~ ERROR allow(experimental) overruled by outer forbid(experimental)
+fn main() {
+}
// Tests that a function with a ! annotation always actually fails
// error-pattern: some control paths may return
-fn bad_bang(i: uint) -> ! { println!("{}", 3); }
+fn bad_bang(i: uint) -> ! { println!("{}", 3i); }
fn main() { bad_bang(5u); }
extern crate debug;
fn main() {
- let x = box 5;
+ let x = box 5i;
let y = x;
println!("{:?}", *x); //~ ERROR use of partially moved value: `*x`
y.clone();
//~^ NOTE maybe a missing `()` to call it? If not, try an anonymous
// Ensure the span is useful
- let ys = &[1,2,3,4,5,6,7];
+ let ys = &[1i,2,3,4,5,6,7];
let a = ys.iter()
.map(|x| x)
.filter(|&&x| x == 1)
use std::task;
fn main() {
- let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
task::spawn(proc() {
use std::task;
fn main() {
- let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
task::spawn(proc() {
// Check that non constant exprs fail for vector repeat syntax
fn main() {
- fn bar(n: int) {
+ fn bar(n: uint) {
let _x = [0, ..n]; //~ ERROR expected constant integer for repeat count but found variable
}
}
}
}
-fn main() {
- struct_with_a_nested_enum_and_vector();
- enum_with_multiple_missing_variants();
- enum_struct_variant();
+fn missing_nil() {
+ match ((), false) {
+ //~^ ERROR non-exhaustive patterns: `((), false)` not covered
+ ((), true) => ()
+ }
}
+
+fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn env<'a>(_: &'a uint, blk: |p: ||: 'a|) {
+fn env<'a>(blk: |p: ||: 'a|) {
// Test that the closure here cannot be assigned
// the lifetime `'a`, which outlives the current
// block.
- //
- // FIXME(#4846): The `&'a uint` parameter is needed to ensure that `'a`
- // is a free and not bound region name.
let mut state = 0;
let statep = &mut state;
blk(|| *statep = 1); //~ ERROR cannot infer
}
-fn no_env_no_for<'a>(_: &'a uint, blk: |p: |||: 'a) {
+fn no_env_no_for<'a>(blk: |p: |||: 'a) {
// Test that a closure with no free variables CAN
// outlive the block in which it is created.
- //
- // FIXME(#4846): The `&'a uint` parameter is needed to ensure that `'a`
- // is a free and not bound region name.
blk(|| ())
}
use std::gc::GC;
fn testfn(cond: bool) {
- let mut x = box(GC) 3;
- let mut y = box(GC) 4;
+ let mut x = box(GC) 3i;
+ let mut y = box(GC) 4i;
let mut a = &*x;
- let mut exp = 3;
+ let mut exp = 3i;
if cond {
a = &*y;
exp = 4;
}
- x = box(GC) 5; //~ERROR cannot assign to `x` because it is borrowed
- y = box(GC) 6; //~ERROR cannot assign to `y` because it is borrowed
+ x = box(GC) 5i; //~ERROR cannot assign to `x` because it is borrowed
+ y = box(GC) 6i; //~ERROR cannot assign to `y` because it is borrowed
assert_eq!(*a, exp);
- assert_eq!(x, box(GC) 5);
- assert_eq!(y, box(GC) 6);
+ assert_eq!(x, box(GC) 5i);
+ assert_eq!(y, box(GC) 6i);
}
pub fn main() {}
fn wants_static_fn(_x: ||: 'static) {}
fn main() {
- let i = 3;
+ let i = 3i;
wants_static_fn(|| { //~ ERROR cannot infer
println!("i={}", i);
})
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Issue #12470.
+
+trait X {
+ fn get_i(&self) -> int;
+}
+
+struct B {
+ i: int
+}
+
+impl X for B {
+ fn get_i(&self) -> int {
+ self.i
+ }
+}
+
+impl Drop for B {
+ fn drop(&mut self) {
+ println!("drop");
+ }
+}
+
+struct A<'r> {
+ p: &'r X
+}
+
+fn make_a<'r>(p:&'r X) -> A<'r> {
+ A{p:p}
+}
+
+fn make_make_a() -> A {
+ let b: Box<B> = box B {
+ i: 1,
+ };
+ let bb: &B = b; //~ ERROR `*b` does not live long enough
+ make_a(bb)
+}
+
+fn main() {
+ let a = make_make_a();
+ println!("{}", a.p.get_i());
+}
let mut x;
if cond {
- x = &3; //~ ERROR borrowed value does not live long enough
- assert_eq!(*x, 3);
+ x = &3i; //~ ERROR borrowed value does not live long enough
+ assert_eq!(*x, 3i);
}
}
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
fn main() {
let n = 1;
let a = [0, ..n]; //~ ERROR expected constant integer for repeat count but found variable
+ let b = [0, ..()]; //~ ERROR expected positive integer for repeat count but found ()
+ //~^ ERROR: expected `uint` but found `()`
+ let c = [0, ..true]; //~ ERROR expected positive integer for repeat count but found boolean
+ //~^ ERROR: expected `uint` but found `bool`
+ let d = [0, ..0.5]; //~ ERROR expected positive integer for repeat count but found float
+ //~^ ERROR: expected `uint` but found `<generic float #0>`
+ let e = [0, .."foo"]; //~ ERROR expected positive integer for repeat count but found string
+ //~^ ERROR: expected `uint` but found `&'static str`
+ let f = [0, ..-4];
+ //~^ ERROR expected positive integer for repeat count but found negative integer
}
fn main() {
10i.dup::<int>(); //~ ERROR does not take type parameters
10i.blah::<int, int>(); //~ ERROR incorrect number of type parameters
- (box 10 as Box<bar>).dup(); //~ ERROR contains a self-type
+ (box 10i as Box<bar>).dup(); //~ ERROR contains a self-type
}
fn main() {
- let _ = dup_tup(&1, &2.5);
- let _ = dup_tup(&3.5, &4_u16);
- let _ = dup_tup(&5, &Struct { a: 6, b: 7.5 });
+ let _ = dup_tup(&1i, &2.5f64);
+ let _ = dup_tup(&3.5f64, &4_u16);
+ let _ = dup_tup(&5i, &Struct { a: 6, b: 7.5 });
}
fn zzz() {()}
}
fn main() {
- outer(-1);
- outer(-2.5);
+ outer(-1i);
+ outer(-2.5f64);
}
fn zzz() {()}
fn main() {
let x: Box<Tr+ Share>;
- box() 1 as Box<Tr+ Share>;
+ box() 1i as Box<Tr+ Share>;
}
// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14`, right: `15`)
fn main() {
- assert_eq!(14,15);
+ assert_eq!(14i,15i);
}
// error-pattern:failed at 'test-assert-fmt 42 rust'
fn main() {
- assert!(false, "test-assert-fmt {} {}", 42, "rust");
+ assert!(false, "test-assert-fmt {} {}", 42i, "rust");
}
fn main() {
- fail!(box 413 as Box<::std::any::Any+Send>);
+ fail!(box 413i as Box<::std::any::Any+Send>);
}
// error-pattern:failed at 'test-fail-fmt 42 rust'
fn main() {
- fail!("test-fail-fmt {} {}", 42, "rust");
+ fail!("test-fail-fmt {} {}", 42i, "rust");
}
}
fn main() {
- let y = box 0;
+ let y = box 0i;
let x: Gc<proc():Send> = box(GC) (proc() {
println!("{:?}", y.clone());
});
}
fn main() {
- let x = box(GC) box box 0;
+ let x = box(GC) box box 0i;
failfn();
println!("{:?}", x);
}
}
fn main() {
- let x = box(GC) box 0;
+ let x = box(GC) box 0i;
failfn();
println!("{:?}", x);
}
}
fn main() {
- let x = box(GC) vec!(0, 1, 2, 3, 4, 5);
+ let x = box(GC) vec!(0i, 1, 2, 3, 4, 5);
failfn();
println!("{:?}", x);
}
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
- let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
+ let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
.write_str("mod unicode_input_multiple_files_chars;");
}
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
- for _ in range(0, 30) {
+ for _ in range(0u, 30) {
let _ = w.write_char(random_char());
}
}
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
- let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
+ let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("span_main.rs");
- for _ in range(0, 100) {
+ for _ in range(0u, 100) {
let n = task_rng().gen_range(3u, 20);
{
--- /dev/null
+-include ../tools.mk
+
+all:
+ $(RUSTC) -v
+ $(RUSTC) -v verbose
+ $(RUSTC) -v bad_arg && exit 1 || exit 0
+ $(RUSTC) --version verbose
+ $(RUSTC) --version bad_arg && exit 1 || exit 0
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+// compile-flags: -A test-lint
+
+#![feature(phase)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { }
+
+pub fn main() {
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:lint_plugin_test.rs
+// ignore-stage1
+// ignore-pretty
+
+#![feature(phase)]
+
+#[phase(plugin)]
+extern crate lint_plugin_test;
+
+fn lintme() { } //~ WARNING item is named 'lintme'
+
+#[allow(test_lint)]
+pub fn main() {
+ fn lintme() { }
+}
pub fn main() {
let a = hexfloat!("0x1.999999999999ap-4");
- assert_eq!(a, 0.1);
+ assert_eq!(a, 0.1f64);
let b = hexfloat!("-0x1.fffp-4", f32);
assert_eq!(b, -0.12498474_f32);
let c = hexfloat!("0x.12345p5", f64);
assert_eq!(i32_a * i32_a * i32_a, 1000);
assert_eq!(i32_a * i32_a * i32_a * i32_a, 10000);
assert_eq!(i32_a * i32_a / i32_a * i32_a, 100);
- assert_eq!(i32_a * (i32_a - 1) << 2 + i32_a, 368640);
+ assert_eq!(i32_a * (i32_a - 1) << (2 + i32_a as uint), 368640);
let i32_b: int = 0x10101010;
assert_eq!(i32_b + 1 - 1, i32_b);
assert_eq!(i32_b << 1, i32_b << 1);
struct Point { x : int }
pub fn main() {
- assert_eq!(14,14);
+ assert_eq!(14i,14i);
assert_eq!("abc".to_string(),"abc".to_string());
assert_eq!(box Point{x:34},box Point{x:34});
assert_eq!(&Point{x:34},&Point{x:34});
pub fn main() {
println!("{:?}", f(Triple {x: 3, y: 4, z: 5}, 4).a.x);
- println!("{:?}", f(5, 6).a);
+ println!("{:?}", f(5i, 6i).a);
}
// except according to those terms.
pub fn main() {
- let mut sum = 0;
+ let mut sum = 0i;
let xs = vec!(1, 2, 3, 4, 5);
for x in xs.iter() {
sum += *x;
}
pub fn main() {
- let mut v = vec!(1);
+ let mut v = vec!(1i);
v.push_val(2);
v.push_val(3);
assert_eq!(v, vec!(1, 2, 3));
assert!(!out.status.success());
let s = str::from_utf8(out.error.as_slice()).unwrap();
let mut i = 0;
- for _ in range(0, 2) {
+ for _ in range(0i, 2) {
i += s.slice_from(i + 10).find_str("stack backtrace").unwrap() + 10;
}
assert!(s.slice_from(i + 10).find_str("stack backtrace").is_none(),
assert_eq!(-2147483648i32 - 1i32, 2147483647i32);
assert_eq!(-9223372036854775808i64 - 1i64, 9223372036854775807i64);
- assert_eq!(-9223372036854775808 - 1, 9223372036854775807);
+ assert_eq!(-9223372036854775808i - 1, 9223372036854775807);
}
// Check that issue #954 stays fixed
pub fn main() {
- match -1 { -1 => {}, _ => fail!("wat") }
- assert_eq!(1-1, 0);
+ match -1i { -1 => {}, _ => fail!("wat") }
+ assert_eq!(1i-1, 0i);
}
}
fn test_box() {
- assert_eq!(box(GC) 10, box(GC) 10);
+ assert_eq!(box(GC) 10i, box(GC) 10i);
}
fn test_ptr() {
unsafe {
- let p1: *u8 = ::std::mem::transmute(0);
- let p2: *u8 = ::std::mem::transmute(0);
- let p3: *u8 = ::std::mem::transmute(1);
+ let p1: *u8 = ::std::mem::transmute(0u);
+ let p2: *u8 = ::std::mem::transmute(0u);
+ let p3: *u8 = ::std::mem::transmute(1u);
assert_eq!(p1, p2);
assert!(p1 != p3);
}
pub fn main() {
- for _ in range(0, 10000) { bitv_test(); }
+ for _ in range(0i, 10000) { bitv_test(); }
}
println!("{}", b);
assert_eq!(b, 1);
assert_eq!(a, 2);
- assert_eq!(!0xf0 & 0xff, 0xf);
- assert_eq!(0xf0 | 0xf, 0xff);
- assert_eq!(0xf << 4, 0xf0);
- assert_eq!(0xf0 >> 4, 0xf);
- assert_eq!(-16 >> 2, -4);
- assert_eq!(0b1010_1010 | 0b0101_0101, 0xff);
+ assert_eq!(!0xf0i & 0xff, 0xf);
+ assert_eq!(0xf0i | 0xf, 0xff);
+ assert_eq!(0xfi << 4, 0xf0);
+ assert_eq!(0xf0i >> 4, 0xf);
+ assert_eq!(-16i >> 2, -4);
+ assert_eq!(0b1010_1010i | 0b0101_0101, 0xff);
}
pub fn main() {
let num = 12;
- assert_eq!(if (true) { 12 } else { 12 } - num, 0);
- assert_eq!(12 - if (true) { 12 } else { 12 }, 0);
- if (true) { 12; } {-num};
- if (true) { 12; }; {-num};
- if (true) { 12; };;; -num;
+ assert_eq!(if (true) { 12i } else { 12 } - num, 0);
+ assert_eq!(12i - if (true) { 12i } else { 12 }, 0);
+ if (true) { 12i; } {-num};
+ if (true) { 12i; }; {-num};
+ if (true) { 12i; };;; -num;
}
fn iter_vec<T>(v: Vec<T> , f: |&T|) { for x in v.iter() { f(x); } }
pub fn main() {
- let v = vec!(1, 2, 3, 4, 5, 6, 7);
- let mut odds = 0;
+ let v = vec!(1i, 2, 3, 4, 5, 6, 7);
+ let mut odds = 0i;
iter_vec(v, |i| {
if *i % 2 == 1 {
odds += 1;
fn iter_vec<T>(v: Vec<T> , f: |&T|) { for x in v.iter() { f(x); } }
pub fn main() {
- let v = vec!(1, 2, 3, 4, 5);
+ let v = vec!(1i, 2, 3, 4, 5);
let mut sum = 0;
iter_vec(v.clone(), |i| {
iter_vec(v.clone(), |j| {
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Basic boolean tests
+
+fn main() {
+ assert_eq!(false.eq(&true), false);
+ assert_eq!(false == false, true);
+ assert_eq!(false != true, true);
+ assert_eq!(false.ne(&false), false);
+
+ assert_eq!(false.bitand(&false), false);
+ assert_eq!(true.bitand(&false), false);
+ assert_eq!(false.bitand(&true), false);
+ assert_eq!(true.bitand(&true), true);
+
+ assert_eq!(false & false, false);
+ assert_eq!(true & false, false);
+ assert_eq!(false & true, false);
+ assert_eq!(true & true, true);
+
+ assert_eq!(false.bitor(&false), false);
+ assert_eq!(true.bitor(&false), true);
+ assert_eq!(false.bitor(&true), true);
+ assert_eq!(true.bitor(&true), true);
+
+ assert_eq!(false | false, false);
+ assert_eq!(true | false, true);
+ assert_eq!(false | true, true);
+ assert_eq!(true | true, true);
+
+ assert_eq!(false.bitxor(&false), false);
+ assert_eq!(true.bitxor(&false), true);
+ assert_eq!(false.bitxor(&true), true);
+ assert_eq!(true.bitxor(&true), false);
+
+ assert_eq!(false ^ false, false);
+ assert_eq!(true ^ false, true);
+ assert_eq!(false ^ true, true);
+ assert_eq!(true ^ true, false);
+
+ assert_eq!(!true, false);
+ assert_eq!(!false, true);
+
+ let s = false.to_str();
+ assert_eq!(s.as_slice(), "false");
+ let s = true.to_str();
+ assert_eq!(s.as_slice(), "true");
+
+ assert!(true > false);
+ assert!(!(false > true));
+
+ assert!(false < true);
+ assert!(!(true < false));
+
+ assert!(false <= false);
+ assert!(false >= false);
+ assert!(true <= true);
+ assert!(true >= true);
+
+ assert!(false <= true);
+ assert!(!(false >= true));
+ assert!(true >= false);
+ assert!(!(true <= false));
+
+ assert!(true.cmp(&true) == Equal);
+ assert!(false.cmp(&false) == Equal);
+ assert!(true.cmp(&false) == Greater);
+ assert!(false.cmp(&true) == Less);
+}
// except according to those terms.
pub fn main() {
- let x = [22];
+ let x = [22i];
let y = &x[0];
assert_eq!(*y, 22);
}
}
pub fn main() {
- let mut data = [1, 2, 3];
+ let mut data = [1i, 2, 3];
{
let slice = MutSlice { data: data };
slice.data[0] += 4;
None => {
// It is ok to reassign x here, because there is in
// fact no outstanding loan of x!
- x = Some(0);
+ x = Some(0i);
}
Some(_) => { }
}
#![feature(managed_boxes)]
pub fn main() {
- let (&x, &y) = (&3, &'a');
+ let (&x, &y) = (&3i, &'a');
assert_eq!(x, 3);
assert_eq!(y, 'a');
}
}
pub fn main() {
- assert_eq!(foo(&3), 3);
+ assert_eq!(foo(&3i), 3i);
assert_eq!(foo(&'a'), 'a');
}
use std::gc::GC;
pub fn main() {
- assert!((box(GC) 1 < box(GC) 3));
+ assert!((box(GC) 1i < box(GC) 3i));
assert!((box(GC) box(GC) "hello ".to_string() >
box(GC) box(GC) "hello".to_string()));
assert!((box(GC) box(GC) box(GC) "hello".to_string() !=
// except according to those terms.
fn main() {
- let box x = box 3;
- match box 3 {
+ let box x = box 3i;
+ match box 3i {
box y => {
assert!(x == y);
println!("{} {}", x, y);
// except according to those terms.
pub fn main() {
- let mut i = 0;
+ let mut i = 0i;
while i < 20 { i += 1; if i == 10 { break; } }
assert_eq!(i, 10);
loop { i += 1; if i == 20 { break; } }
assert_eq!(i, 20);
- let xs = [1, 2, 3, 4, 5, 6];
+ let xs = [1i, 2, 3, 4, 5, 6];
for x in xs.iter() {
if *x == 3 { break; } assert!((*x <= 3));
}
i += 1; if i % 2 == 0 { continue; } assert!((i % 2 != 0));
if i >= 10 { break; }
}
- let ys = vec!(1, 2, 3, 4, 5, 6);
+ let ys = vec!(1i, 2, 3, 4, 5, 6);
for x in ys.iter() {
if *x % 2 == 0 { continue; }
assert!((*x % 2 != 0));
pub fn main() {
- assert_eq!(3.hi(), "hello: 3".to_string());
- assert_eq!(Some(Some(3)).hi(),
+ assert_eq!(3i.hi(), "hello: 3".to_string());
+ assert_eq!(Some(Some(3i)).hi(),
"something!something!hello: 3".to_string());
assert_eq!(None::<int>.hi(), "hello - none".to_string());
assert_eq!(Some(None::<int>).hi(), "something!hello - none".to_string());
- assert_eq!(Some(3).hi(), "something!hello: 3".to_string());
+ assert_eq!(Some(3i).hi(), "something!hello: 3".to_string());
}
pub fn main() {
let (tx, rx) = channel();
- foo(31337, tx);
- assert!(rx.recv() == 31337);
+ foo(31337i, tx);
+ assert!(rx.recv() == 31337i);
}
}
pub fn main() {
- let (tx, rx) = channel();
- foo(X(31337), tx);
- assert!(rx.recv() == X(31337));
+ let (tx, rx): (Sender<X<int>>, Receiver<X<int>>) = channel();
+ foo(X(31337i), tx);
+ assert!(rx.recv() == X(31337i));
}
}
pub fn main() {
- let (tx, rx) = channel();
- foo(31337, tx);
- assert!(rx.recv() == 31337);
+ let (tx, rx): (Sender<int>, Receiver<int>) = channel();
+ foo(31337i, tx);
+ assert!(rx.recv() == 31337i);
}
assert_eq!(b'\xF0', 240u8);
assert_eq!(FOO, 240u8);
- assert_eq!([42, ..b'\t'].as_slice(), &[42, 42, 42, 42, 42, 42, 42, 42, 42]);
-
match 42 {
b'*' => {},
_ => fail!()
pub fn main() {
//let bt0 = sys::rusti::frame_address(1u32);
//println!("%?", bt0);
- cci_iter_lib::iter([1, 2, 3], |i| {
+ cci_iter_lib::iter([1i, 2, 3], |i| {
println!("{}", *i);
//assert!(bt0 == sys::rusti::frame_address(2u32));
})
pub fn main() {
let f = {|i| i};
- assert_eq!(f(2), 2);
- assert_eq!(f(5), 5);
+ assert_eq!(f(2i), 2i);
+ assert_eq!(f(5i), 5i);
}
}
pub fn main() {
- let x: int = 2 + 2;
+ let x: int = 2i + 2;
println!("{}", x);
println!("hello, world");
- println!("{}", 10);
+ println!("{}", 10i);
}
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
pub fn main() {
assert_eq!(format!(concat!("foo", "bar", "{}"), "baz"), "foobarbaz".to_string());
assert_eq!(format!(concat!()), "".to_string());
+ // check trailing comma is allowed in concat
+ assert_eq!(concat!("qux", "quux",).to_string(), "quxquux".to_string());
assert_eq!(
concat!(1, 2i, 3u, 4f32, 4.0, 'a', true, ()),
pub fn main() {
- static FOO: int = 2;
- let _v = [0, ..FOO*3*2/2];
+ static FOO: uint = 2;
+ let _v = [0i, ..FOO*3*2/2];
}
static BAR: int = 3;
pub fn main() {
- let x: int = 3;
+ let x: int = 3i;
let y = match x {
- FOO => 1,
- BAR => 2,
- _ => 3
+ FOO => 1i,
+ BAR => 2i,
+ _ => 3i
};
assert_eq!(y, 2);
}
use std::gc::GC;
pub fn main() {
- let x = box(GC) Cell::new(5);
- x.set(1000);
+ let x = box(GC) Cell::new(5i);
+ x.set(1000i);
println!("{:?}", x.get());
}
use std::rc::Rc;
fn main() {
- let x = Rc::new([1, 2, 3, 4]);
+ let x = Rc::new([1i, 2, 3, 4]);
assert!(*x == [1, 2, 3, 4]);
}
pub fn main() {
let e0 = E0;
- let e11 = E1(1);
- let e12 = E1(2);
- let e21 = E2(1, 1);
- let e22 = E2(1, 2);
+ let e11 = E1(1i);
+ let e12 = E1(2i);
+ let e21 = E2(1i, 1i);
+ let e22 = E2(1i, 2i);
// in order for both PartialOrd and Ord
let es = [e0, e11, e12, e21, e22];
pub fn main() {
- let (es11, es12, es21, es22) = (ES1 {x: 1}, ES1 {x: 2}, ES2 {x: 1, y: 1}, ES2 {x: 1, y: 2});
+ let (es11, es12, es21, es22) = (ES1 {
+ x: 1i
+ }, ES1 {
+ x: 2i
+ }, ES2 {
+ x: 1i,
+ y: 1i
+ }, ES2 {
+ x: 1i,
+ y: 2i
+ });
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
}
pub fn main() {
- let s1 = S {x: 1, y: 1};
- let s2 = S {x: 1, y: 2};
+ let s1 = S {x: 1i, y: 1i};
+ let s2 = S {x: 1i, y: 2i};
// in order for both PartialOrd and Ord
let ss = [s1, s2];
pub fn main() {
- let ts1 = TS(1, 1);
- let ts2 = TS(1, 2);
+ let ts1 = TS(1i, 1i);
+ let ts2 = TS(1i, 2i);
// in order for both PartialOrd and Ord
let tss = [ts1, ts2];
pub fn main() {
// check there's no segfaults
- for _ in range(0, 20) {
+ for _ in range(0i, 20) {
rand::random::<A>();
rand::random::<B>();
rand::random::<C>();
}
pub fn main() {
- let a = Foo { x: 1, y: 2.0, z: 3 };
- let b = Foo { x: 1, y: 2.0, z: 3 };
+ let a = Foo { x: 1, y: 2.0f64, z: 3 };
+ let b = Foo { x: 1, y: 2.0f64, z: 3 };
assert_eq!(a, b);
assert!(!(a != b));
assert!(a.eq(&b));
struct A { a: int }
pub fn main() {
- let _x: Option<f64> = foo_func(0);
+ let _x: Option<f64> = foo_func(0i);
}
pub fn main() {
// Basic usage
- t!(to_str(1.2345678e-5, 10u, true, s::SignNeg, s::DigMax(6), s::ExpDec, false),
+ t!(to_str(1.2345678e-5f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpDec, false),
"1.234568e-5")
// Hexadecimal output
- t!(to_str(7.281738281250e+01, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false),
+ t!(to_str(7.281738281250e+01f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false),
"+1.2345p+6")
- t!(to_str(-1.777768135071e-02, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false),
+ t!(to_str(-1.777768135071e-02f64, 16u, true, s::SignAll, s::DigMax(6), s::ExpBin, false),
"-1.2345p-6")
// Some denormals
- t!(to_str(4.9406564584124654e-324, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false),
+ t!(to_str(4.9406564584124654e-324f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false),
"1p-1074")
- t!(to_str(2.2250738585072009e-308, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false),
+ t!(to_str(2.2250738585072009e-308f64, 10u, true, s::SignNeg, s::DigMax(6), s::ExpBin, false),
"1p-1022")
}
fn test_rec() { let rs = { RS {v1: 10, v2: 20} }; assert!((rs.v2 == 20)); }
fn test_filled_with_stuff() {
- let rs = { let mut a = 0; while a < 10 { a += 1; } a };
+ let rs = { let mut a = 0i; while a < 10 { a += 1; } a };
assert_eq!(rs, 10);
}
fn test_generic() {
fn f<T>(t: T) -> T { t }
- assert_eq!(f(10), 10);
+ assert_eq!(f(10i), 10);
}
fn test_alt() {
// Tests for if as expressions returning boxed types
fn test_box() {
- let rs = if true { box(GC) 100 } else { box(GC) 101 };
+ let rs = if true { box(GC) 100i } else { box(GC) 101i };
assert_eq!(*rs, 100);
}
fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
- let x = if true { 10 } else { fail!() };
- assert_eq!(x, 10);
+ let x = if true { 10i } else { fail!() };
+ assert_eq!(x, 10i);
}
fn test_elseif_fail() {
- let x = if false { 0 } else if false { fail!() } else { 10 };
- assert_eq!(x, 10);
+ let x = if false { 0 } else if false { fail!() } else { 10i };
+ assert_eq!(x, 10i);
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
// Tests for if as expressions returning boxed types
fn test_box() {
- let rs = if true { box 100 } else { box 101 };
- assert_eq!(*rs, 100);
+ let rs = if true { box 100i } else { box 101i };
+ assert_eq!(*rs, 100i);
}
pub fn main() { test_box(); }
// Tests for match as expressions resulting in boxed types
fn test_box() {
- let res = match true { true => { box(GC) 100 } _ => fail!("wat") };
- assert_eq!(*res, 100);
+ let res = match true { true => { box(GC) 100i } _ => fail!("wat") };
+ assert_eq!(*res, 100i);
}
fn test_str() {
}
fn test_box() {
- let r = match true { true => { vec!(10) } false => { fail!() } };
- assert_eq!(*r.get(0), 10);
+ let r = match true { true => { vec!(10i) } false => { fail!() } };
+ assert_eq!(*r.get(0), 10i);
}
pub fn main() { test_simple(); test_box(); }
// Tests for match as expressions resulting in boxed types
fn test_box() {
- let res = match true { true => { box 100 }, _ => fail!() };
- assert_eq!(*res, 100);
+ let res = match true { true => { box 100i }, _ => fail!() };
+ assert_eq!(*res, 100i);
}
pub fn main() { test_box(); }
pub fn main() {
println!("{}", match red {
- red => { 1 }
- green => { 2 }
- blue => { 3 }
+ red => { 1i }
+ green => { 2i }
+ blue => { 3i }
});
}
// except according to those terms.
pub fn main() {
- let arr = [1,2,3];
+ let arr = [1i,2i,3i];
let arr2 = arr;
- assert_eq!(arr[1], 2);
- assert_eq!(arr2[2], 3);
+ assert_eq!(arr[1], 2i);
+ assert_eq!(arr2[2], 3i);
}
extern crate debug;
pub fn main() {
- let pi = 3.1415927;
+ let pi = 3.1415927f64;
println!("{:?}", -pi * (pi + 2.0 / pi) - pi * 5.0);
if pi == 5.0 || pi < 10.0 || pi <= 2.0 || pi != 22.0 / 7.0 || pi >= 10.0
|| pi > 1.0 {
pub fn main() {
- let a = 1.5e6;
- let b = 1.5E6;
- let c = 1e6;
- let d = 1E6;
+ let a = 1.5e6f64;
+ let b = 1.5E6f64;
+ let c = 1e6f64;
+ let d = 1E6f64;
let e = 3.0f32;
let f = 5.9f64;
let g = 1e6f32;
let h = 1.0e7f64;
let i = 1.0E7f64;
- let j = 3.1e+9;
- let k = 3.2e-10;
+ let j = 3.1e+9f64;
+ let k = 3.2e-10f64;
assert_eq!(a, b);
assert!((c < b));
assert_eq!(c, d);
pub fn main() {
let mut h = HashMap::new();
- let kvs = [(1, 10), (2, 20), (3, 30)];
+ let kvs = [(1i, 10i), (2i, 20i), (3i, 30i)];
for &(k,v) in kvs.iter() {
h.insert(k,v);
}
pub fn main() {
let mut h = HashMap::new();
- let kvs = [(1, 10), (2, 20), (3, 30)];
+ let kvs = [(1i, 10i), (2i, 20i), (3i, 30i)];
for &(k,v) in kvs.iter() {
h.insert(k,v);
}
- let mut x = 0;
- let mut y = 0;
+ let mut x = 0i;
+ let mut y = 0i;
for (&k,&v) in h.iter() {
x += k;
y += v;
// except according to those terms.
pub fn main() {
- let x = [1,..100];
- let mut y = 0;
+ let x = [1i,..100];
+ let mut y = 0i;
for (n,i) in x.iter().enumerate() {
if n < 10 {
continue;
fn id<T:Send>(t: T) -> T { return t; }
pub fn main() {
- let expected = box 100;
+ let expected = box 100i;
let actual = id::<Box<int>>(expected.clone());
println!("{:?}", *actual);
assert_eq!(*expected, *actual);
fn f<T>(x: Gc<T>) -> Gc<T> { return x; }
-pub fn main() { let x = f(box(GC) 3); println!("{:?}", *x); }
+pub fn main() { let x = f(box(GC) 3i); println!("{:?}", *x); }
fn f<T>(x: Box<T>) -> Box<T> { return x; }
-pub fn main() { let x = f(box 3); println!("{:?}", *x); }
+pub fn main() { let x = f(box 3i); println!("{:?}", *x); }
}
pub fn main() {
- assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
+ assert_eq!(vec_utils::map_(&vec!(1i,2i,3i), |&x| x+1), vec!(2i,3i,4i));
}
fn get_third<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; }
pub fn main() {
- println!("{:?}", get_third((1, 2, 3)));
- assert_eq!(get_third((1, 2, 3)), 3);
+ println!("{:?}", get_third((1i, 2i, 3i)));
+ assert_eq!(get_third((1i, 2i, 3i)), 3);
assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8);
}
struct Pair { x: int, y: int }
pub fn main() {
- let a =
+ let a: int =
match 10 { x if x < 7 => { 1 } x if x < 11 => { 2 } 10 => { 3 } _ => { 4 } };
assert_eq!(a, 2);
- let b =
+ let b: int =
match (Pair {x: 10, y: 20}) {
x if x.x < 5 && x.y < 5 => { 1 }
Pair {x: x, y: y} if x == 10 && y == 20 => { 2 }
macro_rules! run_once {
($e: expr) => {
// ditto
- 'x: for _ in range(0, 1) { $e }
+ 'x: for _ in range(0i, 1) { $e }
}
}
pub fn main() {
let mut i = 0i;
- let j = {
+ let j: int = {
'x: loop {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
};
assert_eq!(j, 1i);
- let k = {
- 'x: for _ in range(0, 1) {
+ let k: int = {
+ 'x: for _ in range(0i, 1) {
// ditto
loop_x!(break 'x);
i += 1;
};
assert_eq!(k, 1i);
- let n = {
- 'x: for _ in range(0, 1) {
+ let n: int = {
+ 'x: for _ in range(0i, 1) {
// ditto
run_once!(continue 'x);
i += 1;
macro_rules! run_once {
($e: expr) => {
// ditto
- 'x: for _ in range(0, 1) { $e }
+ 'x: for _ in range(0i, 1) { $e }
}
}
pub fn main() {
- 'x: for _ in range(0, 1) {
+ 'x: for _ in range(0i, 1) {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
fail!("break doesn't act hygienically inside for loop");
fail!("break doesn't act hygienically inside infinite loop");
}
- 'x: for _ in range(0, 1) {
+ 'x: for _ in range(0i, 1) {
// ditto
run_once!(continue 'x);
fail!("continue doesn't act hygienically inside for loop");
pub fn main() {
// Make sure there's a poly formatter that takes anything
- t!(format!("{:?}", 1), "1");
+ t!(format!("{:?}", 1i), "1");
t!(format!("{:?}", A), "A");
t!(format!("{:?}", ()), "()");
- t!(format!("{:?}", box(GC) (box 1, "foo")), "box(GC) (box 1, \"foo\")");
+ t!(format!("{:?}", box(GC) (box 1i, "foo")), "box(GC) (box 1, \"foo\")");
// Various edge cases without formats
t!(format!(""), "");
// At least exercise all the formats
t!(format!("{:b}", true), "true");
t!(format!("{:c}", '☃'), "☃");
- t!(format!("{:d}", 10), "10");
- t!(format!("{:i}", 10), "10");
+ t!(format!("{:d}", 10i), "10");
+ t!(format!("{:i}", 10i), "10");
t!(format!("{:u}", 10u), "10");
t!(format!("{:o}", 10u), "12");
t!(format!("{:x}", 10u), "a");
t!(format!("{:d}", A), "aloha");
t!(format!("{:d}", B), "adios");
t!(format!("foo {:s} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃");
- t!(format!("{1} {0}", 0, 1), "1 0");
- t!(format!("{foo} {bar}", foo=0, bar=1), "0 1");
- t!(format!("{foo} {1} {bar} {0}", 0, 1, foo=2, bar=3), "2 1 3 0");
+ t!(format!("{1} {0}", 0i, 1i), "1 0");
+ t!(format!("{foo} {bar}", foo=0i, bar=1i), "0 1");
+ t!(format!("{foo} {1} {bar} {0}", 0i, 1i, foo=2i, bar=3i), "2 1 3 0");
t!(format!("{} {0}", "a"), "a a");
- t!(format!("{foo_bar}", foo_bar=1), "1");
- t!(format!("{:d}", 5 + 5), "10");
+ t!(format!("{foo_bar}", foo_bar=1i), "1");
+ t!(format!("{:d}", 5i + 5i), "10");
// Formatting strings and their arguments
t!(format!("{:s}", "a"), "a");
test_order();
// make sure that format! doesn't move out of local variables
- let a = box 3;
+ let a = box 3i;
format!("{:?}", a);
format!("{:?}", a);
// io::Writer instance.
fn test_write() {
let mut buf = MemWriter::new();
- write!(&mut buf as &mut io::Writer, "{}", 3);
+ write!(&mut buf as &mut io::Writer, "{}", 3i);
{
let w = &mut buf as &mut io::Writer;
- write!(w, "{foo}", foo=4);
+ write!(w, "{foo}", foo=4i);
write!(w, "{:s}", "hello");
writeln!(w, "{}", "line");
writeln!(w, "{foo}", foo="bar");
let mut buf = MemWriter::new();
{
let w = &mut buf as &mut io::Writer;
- format_args!(|args| { write!(w, "{}", args); }, "{}", 1);
+ format_args!(|args| { write!(w, "{}", args); }, "{}", 1i);
format_args!(|args| { write!(w, "{}", args); }, "test");
- format_args!(|args| { write!(w, "{}", args); }, "{test}", test=3);
+ format_args!(|args| { write!(w, "{}", args); }, "{test}", test=3i);
}
let s = str::from_utf8(buf.unwrap().as_slice()).unwrap().to_string();
t!(s, "1test3");
pub fn main() {
assert_eq!(size_of::<u8>(), 1);
- let (mut x, mut y) = (1, 2);
+ let (mut x, mut y) = (1i, 2i);
swap(&mut x, &mut y);
assert_eq!(x, 2);
assert_eq!(y, 1);
// except according to those terms.
pub fn main() {
- let a = 0xBEEF;
- let b = 0o755;
- let c = 0b10101;
- let d = -0xBEEF;
- let e = -0o755;
- let f = -0b10101;
+ let a = 0xBEEFi;
+ let b = 0o755i;
+ let c = 0b10101i;
+ let d = -0xBEEFi;
+ let e = -0o755i;
+ let f = -0b10101i;
assert_eq!(a, 48879);
assert_eq!(b, 493);
pub fn main() {
unsafe {
- let mut x = box 1;
+ let mut x = box 1i;
assert_eq!(rusti::atomic_load(&*x), 1);
*x = 5;
pub fn main() {
unsafe {
- let x = box 1;
+ let x = box 1i;
let mut y = rusti::init();
let mut z: *uint = transmute(&x);
rusti::move_val_init(&mut y, x);
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
- for _ in range(0, 1000) {
+ for _ in range(0i, 1000i) {
println!("hello?");
}
- for _ in range(0, 1000) {
+ for _ in range(0i, 1000i) {
println!("hello?");
}
return;
extern crate foo = "issue-11225-1";
pub fn main() {
- foo::foo(1);
+ foo::foo(1i);
}
extern crate foo = "issue-11225-2";
pub fn main() {
- foo::foo(1);
+ foo::foo(1i);
}
// except according to those terms.
pub fn main() {
- let x = 1;
- let y = 2;
+ let x = 1i;
+ let y = 2i;
- assert_eq!(3, match (x, y) {
+ assert_eq!(3i, match (x, y) {
(1, 1) => 1,
(2, 2) => 2,
(1..2, 2) => 3,
});
// nested tuple
- assert_eq!(3, match ((x, y),) {
+ assert_eq!(3i, match ((x, y),) {
((1, 1),) => 1,
((2, 2),) => 2,
((1..2, 2),) => 3,
}
fn lit_shadow_range() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
1 if false => 1,
1..2 => 2,
_ => 3
});
- let x = 0;
- assert_eq!(2, match x+1 {
+ let x = 0i;
+ assert_eq!(2i, match x+1 {
0 => 0,
1 if false => 1,
1..2 => 2,
_ => 3
});
- assert_eq!(2, match val() {
+ assert_eq!(2i, match val() {
1 if false => 1,
1..2 => 2,
_ => 3
});
- assert_eq!(2, match CONST {
+ assert_eq!(2i, match CONST {
0 => 0,
1 if false => 1,
1..2 => 2,
});
// value is out of the range of second arm, should match wildcard pattern
- assert_eq!(3, match 3 {
+ assert_eq!(3i, match 3 {
1 if false => 1,
1..2 => 2,
_ => 3
}
fn range_shadow_lit() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
1..2 if false => 1,
1 => 2,
_ => 3
});
- let x = 0;
- assert_eq!(2, match x+1 {
+ let x = 0i;
+ assert_eq!(2i, match x+1 {
0 => 0,
1..2 if false => 1,
1 => 2,
_ => 3
});
- assert_eq!(2, match val() {
+ assert_eq!(2i, match val() {
1..2 if false => 1,
1 => 2,
_ => 3
});
- assert_eq!(2, match CONST {
+ assert_eq!(2i, match CONST {
0 => 0,
1..2 if false => 1,
1 => 2,
});
// ditto
- assert_eq!(3, match 3 {
+ assert_eq!(3i, match 3 {
1..2 if false => 1,
1 => 2,
_ => 3
}
fn range_shadow_range() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
0..2 if false => 1,
1..3 => 2,
_ => 3,
});
- let x = 0;
- assert_eq!(2, match x+1 {
+ let x = 0i;
+ assert_eq!(2i, match x+1 {
100 => 0,
0..2 if false => 1,
1..3 => 2,
_ => 3,
});
- assert_eq!(2, match val() {
+ assert_eq!(2i, match val() {
0..2 if false => 1,
1..3 => 2,
_ => 3,
});
- assert_eq!(2, match CONST {
+ assert_eq!(2i, match CONST {
100 => 0,
0..2 if false => 1,
1..3 => 2,
});
// ditto
- assert_eq!(3, match 5 {
+ assert_eq!(3i, match 5 {
0..2 if false => 1,
1..3 => 2,
_ => 3,
}
fn multi_pats_shadow_lit() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
100 => 0,
0 | 1..10 if false => 1,
1 => 2,
}
fn multi_pats_shadow_range() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
100 => 0,
0 | 1..10 if false => 1,
1..3 => 2,
}
fn lit_shadow_multi_pats() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
100 => 0,
1 if false => 1,
0 | 1..10 => 2,
}
fn range_shadow_multi_pats() {
- assert_eq!(2, match 1 {
+ assert_eq!(2i, match 1 {
100 => 0,
1..3 if false => 1,
0 | 1..10 => 2,
// which is a rare combination of vector patterns, multiple wild-card
// patterns and guard functions.
let r = match [Bar(0, false)].as_slice() {
- [Bar(_, pred)] if pred => 1,
- [Bar(_, pred)] if !pred => 2,
- _ => 0,
+ [Bar(_, pred)] if pred => 1i,
+ [Bar(_, pred)] if !pred => 2i,
+ _ => 0i,
};
assert_eq!(2, r);
}
let (tx, rx) = channel();
spawn(proc() { helper(rx) });
let (snd, rcv) = channel();
- for _ in range(1, 100000) {
+ for _ in range(1i, 100000i) {
snd.send(1);
let (tx2, rx2) = channel();
tx.send(tx2);
fn main() {
let r = match (FooNullary, 'a') {
- (FooUint(..), 'a'..'z') => 1,
- (FooNullary, 'x') => 2,
+ (FooUint(..), 'a'..'z') => 1i,
+ (FooNullary, 'x') => 2i,
_ => 0
};
assert_eq!(r, 0);
let r = match (FooUint(0), 'a') {
- (FooUint(1), 'a'..'z') => 1,
- (FooUint(..), 'x') => 2,
- (FooNullary, 'a') => 3,
+ (FooUint(1), 'a'..'z') => 1i,
+ (FooUint(..), 'x') => 2i,
+ (FooNullary, 'a') => 3i,
_ => 0
};
assert_eq!(r, 0);
let r = match ('a', FooUint(0)) {
- ('a'..'z', FooUint(1)) => 1,
- ('x', FooUint(..)) => 2,
- ('a', FooNullary) => 3,
+ ('a'..'z', FooUint(1)) => 1i,
+ ('x', FooUint(..)) => 2i,
+ ('a', FooNullary) => 3i,
_ => 0
};
assert_eq!(r, 0);
let r = match ('a', 'a') {
- ('a'..'z', 'b') => 1,
- ('x', 'a'..'z') => 2,
+ ('a'..'z', 'b') => 1i,
+ ('x', 'a'..'z') => 2i,
_ => 0
};
assert_eq!(r, 0);
let r = match ('a', 'a') {
- ('a'..'z', 'b') => 1,
- ('x', 'a'..'z') => 2,
- ('a', 'a') => 3,
+ ('a'..'z', 'b') => 1i,
+ ('x', 'a'..'z') => 2i,
+ ('a', 'a') => 3i,
_ => 0
};
assert_eq!(r, 3);
fn main() {
let x = match A(3) {
- A(..) => 1
+ A(..) => 1i
};
assert_eq!(x, 1);
let x = match A(4) {
- A(1) => 1,
- A(..) => 2
+ A(1) => 1i,
+ A(..) => 2i
};
assert_eq!(x, 2);
// There's no particularly good reason to support this, but it's currently allowed,
// and this makes sure it doesn't ICE or break LLVM.
let x = match B {
- B(..) => 3
+ B(..) => 3i
};
assert_eq!(x, 3);
}
--- /dev/null
+// 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(phase)]
+
+#[phase(plugin, link)] extern crate std;
+
+fn main() {}
fn main() {
let x = match Foo(42) {
- Foo(..) => 1,
+ Foo(..) => 1i,
_ if true => 0,
Bar(..) => fail!("Oh dear")
};
assert_eq!(x, 1);
let x = match Foo(42) {
- _ if true => 0,
+ _ if true => 0i,
Foo(..) => 1,
Bar(..) => fail!("Oh dear")
};
// except according to those terms.
fn main() {
- let mut x = &[1, 2, 3, 4];
+ let mut x = &[1i, 2, 3, 4];
let mut result = vec!();
loop {
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub enum T {
+ T1(()),
+ T2(())
+}
+
+pub enum V {
+ V1(int),
+ V2(bool)
+}
+
+fn foo(x: (T, V)) -> String {
+ match x {
+ (T1(()), V1(i)) => format!("T1(()), V1({})", i),
+ (T2(()), V2(b)) => format!("T2(()), V2({})", b),
+ _ => String::new()
+ }
+}
+
+
+fn main() {
+ assert_eq!(foo((T1(()), V1(99))), "T1(()), V1(99)".to_string());
+ assert_eq!(foo((T2(()), V2(true))), "T2(()), V2(true)".to_string());
+}
extern crate debug;
pub fn main() {
- let mut x = 0;
+ let mut x = 0i;
'foo: loop {
'bar: loop {
}
pub fn main() {
- let z = box 22;
+ let z = box 22i;
a_val(z.clone(), z.clone());
}
// except according to those terms.
pub fn main() {
- let x = 1;
- let y = 1;
+ let x = 1i;
+ let y = 1i;
assert_eq!(&x, &y);
}
// except according to those terms.
pub fn main() {
- let mut x = 0;
- for _ in range(0, 4096) { x += 1; }
+ let mut x = 0i;
+ for _ in range(0i, 4096) { x += 1; }
assert_eq!(x, 4096);
println!("x = {}", x);
}
// except according to those terms.
pub fn main() {
- let mut x = box 3;
+ let mut x = box 3i;
x = x;
assert_eq!(*x, 3);
}
pub fn main() {
let mut table = HashMap::new();
- table.insert("one".to_string(), 1);
- table.insert("two".to_string(), 2);
+ table.insert("one".to_string(), 1i);
+ table.insert("two".to_string(), 2i);
assert!(check_strs(table.to_str().as_slice(), "{one: 1, two: 2}") ||
check_strs(table.to_str().as_slice(), "{two: 2, one: 1}"));
}
// Usage with failing inference
pub fn main() {
- let a = Vec2 { x: 3.0, y: 4.0 };
+ let a = Vec2 { x: 3.0f64, y: 4.0f64 };
// the following compiles and works properly
- let v1: Vec2 = a * 3.0;
+ let v1: Vec2 = a * 3.0f64;
println!("{} {}", v1.x, v1.y);
// the following compiles but v2 will not be Vec2 yet and
// using it later will cause an error that the type of v2
// must be known
- let v2 = a * 3.0;
+ let v2 = a * 3.0f64;
println!("{} {}", v2.x, v2.y); // error regarding v2's type
}
// except according to those terms.
pub fn main() {
- let mut count = 0;
- for _ in range(0, 999_999) { count += 1; }
+ let mut count = 0i;
+ for _ in range(0i, 999_999) { count += 1; }
assert_eq!(count, 999_999);
println!("{}", count);
}
}
pub fn main() {
- let inner = 5;
+ let inner = 5i;
let outer = Outer::new(&inner as &Inner);
outer.inner.print();
}
}
fn main() {
- assert_eq!(foo([1, 2, 3]), (1, 3, 6));
+ assert_eq!(foo([1i, 2i, 3i]), (1i, 3i, 6i));
let [a, b, c, d] = bar("foo", "bar");
assert_eq!(a, "foo");
assert_eq!(a, "baz");
assert!(xs == ["foo", "foo"]);
assert_eq!(d, "baz");
-}
\ No newline at end of file
+}
// except according to those terms.
fn main() {
- let x = match Some(1) {
- ref _y @ Some(_) => 1,
- None => 2,
+ let x = match Some(1i) {
+ ref _y @ Some(_) => 1i,
+ None => 2i,
};
assert_eq!(x, 1);
}
let ints = integers();
let threes = periodical(3);
let fives = periodical(5);
- for _ in range(1, 100) {
+ for _ in range(1i, 100i) {
match (ints.recv(), threes.recv(), fives.recv()) {
(_, true, true) => println!("FizzBuzz"),
(_, true, false) => println!("Fizz"),
impl X for int {}
pub struct Z<'a>(Enum<&'a X>);
- fn foo() { let x = 42; let z = Z(A(&x as &X)); let _ = z; }
+ fn foo() { let x = 42i; let z = Z(A(&x as &X)); let _ = z; }
}
mod b {
}
fn bar() {
- let x = 42;
+ let x = 42i;
let _y = Y { x: Some(&x as &X) };
}
}
pub trait X { fn f(&self); }
impl X for int { fn f(&self) {} }
pub struct Z<'a>(Option<&'a X>);
- fn main() { let x = 42; let z = Z(Some(&x as &X)); let _ = z; }
+ fn main() { let x = 42i; let z = Z(Some(&x as &X)); let _ = z; }
}
pub fn main() {}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test #9737
+
+#![feature(macro_rules)]
+
+macro_rules! f((v: $x:expr) => ( println!("{:?}", $x) ))
+
+fn main () {
+ let v = 5;
+ f!(v: 3);
+}
use issue2378b::{two_maybes};
pub fn main() {
- let x = two_maybes{a: just(3), b: just(5)};
+ let x = two_maybes{a: just(3i), b: just(5i)};
assert_eq!(x[0u], (3, 5));
}
#[attr2 = "val"]
fn f() { }
- /* FIXME: Issue #493
#[attr1 = "val"]
#[attr2 = "val"]
mod mod1 {
}
- pub mod rustrt {
+ mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {
}
}
- */
}
}
}
pub fn main() {
- let x = 3;
+ let x = 3i;
let y = repeater(box x);
assert_eq!(x, y.get());
}
}
}
- 'bar: for _ in range(0, 100) {
+ 'bar: for _ in range(0i, 100i) {
loop {
break 'bar;
}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test #9383
+
+#![feature(macro_rules)]
+
+// shouldn't affect evaluation of $ex:
+macro_rules! bad_macro (($ex:expr) => ({(|_x| { $ex }) (9) }))
+
+fn takes_x(_x : int) {
+ assert_eq!(bad_macro!(_x),8);
+}
+fn main() {
+ takes_x(8);
+}
struct A { a: Box<int> }
fn foo() -> ||: 'static -> int {
- let k = box 22;
+ let k = box 22i;
let _u = A {a: k.clone()};
let result: ||: 'static -> int = || 22;
result
pub fn main() {
fn invoke(f: ||) { f(); }
- let k = box 22;
+ let k = box 22i;
let _u = A {a: k.clone()};
invoke(|| println!("{:?}", k.clone()) )
}
#![feature(macro_rules)]
// shouldn't affect evaluation of $ex:
-macro_rules! bad_macro (($ex:expr) => ({let _x = 9; $ex}))
+macro_rules! bad_macro (($ex:expr) => ({let _x = 9i; $ex}))
pub fn main() {
- let _x = 8;
- assert_eq!(bad_macro!(_x),8)
+ let _x = 8i;
+ assert_eq!(bad_macro!(_x),8i)
}
extern crate debug;
pub fn main() {
- let x = vec!(1, 2, 3);
- let mut y = 0;
+ let x = vec!(1i, 2i, 3i);
+ let mut y = 0i;
for i in x.iter() { println!("{:?}", *i); y += *i; }
println!("{:?}", y);
assert_eq!(y, 6);
fn test() {
let v;
loop {
- v = 3;
+ v = 3i;
break;
}
println!("{}", v);
}
pub fn main() {
- println!("{}", 1);
- println!("{}", 2.0);
+ println!("{}", 1i);
+ println!("{}", 2.0f64);
println!("{:?}", Three);
- println!("{:?}", vec!(4));
+ println!("{:?}", vec!(4i));
}
// except according to those terms.
pub fn main() {
- let x = vec!(10, 20, 30);
- let mut sum = 0;
+ let x = vec!(10i, 20i, 30i);
+ let mut sum = 0i;
for x in x.iter() { sum += *x; }
assert_eq!(sum, 60);
}
extern crate macro_crate_def_only;
pub fn main() {
- assert_eq!(5, make_a_5!());
+ assert_eq!(5i, make_a_5!());
}
extern crate macro_export_inner_module;
pub fn main() {
- assert_eq!(1, foo!());
+ assert_eq!(1i, foo!());
}
}
pub fn main() {
- assert_eq!(1, f(Some('x')));
- assert_eq!(2, f(Some('y')));
- assert_eq!(3, f(None));
+ assert_eq!(1u, f(Some('x')));
+ assert_eq!(2u, f(Some('y')));
+ assert_eq!(3u, f(None));
- assert_eq!(1, match Some('x') {
- Some(char_x!()) => 1,
- _ => 2,
+ assert_eq!(1i, match Some('x') {
+ Some(char_x!()) => 1i,
+ _ => 2i,
});
- assert_eq!(1, match Some('x') {
- some!(char_x!()) => 1,
- _ => 2,
+ assert_eq!(1i, match Some('x') {
+ some!(char_x!()) => 1i,
+ _ => 2i,
});
- assert_eq!(1, match Some('x') {
- indirect!() => 1,
- _ => 2,
+ assert_eq!(1i, match Some('x') {
+ indirect!() => 1i,
+ _ => 2i,
});
- assert_eq!(3, {
- let ident_pat!(x) = 2;
- x+1
+ assert_eq!(3i, {
+ let ident_pat!(x) = 2i;
+ x+1i
});
}
)
);
- mylet!(y, 8*2);
- assert_eq!(y, 16);
+ mylet!(y, 8i*2);
+ assert_eq!(y, 16i);
myfn!(mult, (a,b), { a*b } );
assert_eq!(mult(2, add(4,4)), 16);
macro_rules! actually_an_expr_macro (
- () => ( 16 )
+ () => ( 16i )
)
- assert_eq!({ actually_an_expr_macro!() }, 16);
+ assert_eq!({ actually_an_expr_macro!() }, 16i);
}
#![feature(macro_rules)]
#[cfg(foo)]
-macro_rules! foo( () => (1) )
+macro_rules! foo( () => (1i) )
#[cfg(not(foo))]
-macro_rules! foo( () => (2) )
+macro_rules! foo( () => (2i) )
pub fn main() {
- assert_eq!(foo!(), 1);
+ assert_eq!(foo!(), 1i);
}
#![feature(macro_rules)]
#[cfg(foo)]
-macro_rules! foo( () => (1) )
+macro_rules! foo( () => (1i) )
#[cfg(not(foo))]
-macro_rules! foo( () => (2) )
+macro_rules! foo( () => (2i) )
pub fn main() {
- assert_eq!(foo!(), 2);
+ assert_eq!(foo!(), 2i);
}
}
fn test2() {
- match (1, 2, 3) {
+ match (1i, 2i, 3i) {
(1, a, b) | (2, b, a) => {
assert_eq!(a, 2);
assert_eq!(b, 3);
}
fn test3() {
- match (1, 2, 3) {
+ match (1i, 2i, 3i) {
(1, ref a, ref b) | (2, ref b, ref a) => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
}
fn test4() {
- match (1, 2, 3) {
+ match (1i, 2i, 3i) {
(1, a, b) | (2, b, a) if a == 2 => {
assert_eq!(a, 2);
assert_eq!(b, 3);
}
fn test5() {
- match (1, 2, 3) {
+ match (1i, 2i, 3i) {
(1, ref a, ref b) | (2, ref b, ref a) if *a == 2 => {
assert_eq!(*a, 2);
assert_eq!(*b, 3);
// except according to those terms.
pub fn main() {
- let mut v = Some(22);
+ let mut v = Some(22i);
match v {
None => {}
Some(ref mut p) => { *p += 1; }
_ => fail!()
}
- let x = match "a" { "a" => 1, "b" => 2, _ => fail!() };
+ let x = match "a" { "a" => 1i, "b" => 2i, _ => fail!() };
assert_eq!(x, 1);
match "a" { "a" => { } "b" => { }, _ => fail!() }
extern crate debug;
pub fn main() {
- match box 100 {
+ match box 100i {
box x => {
println!("{:?}", x);
assert_eq!(x, 100);
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test #9384
+
+#![feature(macro_rules)]
+
+// shouldn't affect evaluation of $ex.
+macro_rules! bad_macro (($ex:expr) => (
+ {match 9 {_x => $ex}}
+))
+
+fn main() {
+ match 8 {
+ _x => assert_eq!(bad_macro!(_x),8)
+ }
+}
pub fn main() {
- match vec!(1, 2, 3) {
+ match vec!(1i, 2i, 3i) {
x => {
assert_eq!(x.len(), 3);
assert_eq!(*x.get(0), 1);
// begin failing.
mod m {
- pub fn f() -> Vec<int> { Vec::from_elem(1u, 0) }
+ pub fn f() -> Vec<int> { Vec::from_elem(1u, 0i) }
}
pub fn main() { let _x = m::f(); }
}
pub fn main() {
- let foo = F { a: 1 };
+ let foo = F { a: 1i };
foo.serialize(1i);
- let bar = F { a: F {a: 1 } };
+ let bar = F { a: F {a: 1i } };
bar.serialize(2i);
}
}
pub fn main() {
- f(3);
+ f(3i);
}
impl Foo for X {}
pub fn main() {
- let (a, mut b) = (23, 4);
+ let (a, mut b) = (23i, 4i);
assert_eq!(a, 23);
assert_eq!(b, 4);
b = a + b;
Baz(f32, u8)
}
- let (x, mut y) = (32, Foo(21));
+ let (x, mut y) = (32i, Foo(21));
match x {
mut z @ 32 => {
// except according to those terms.
fn test1() {
- let mut ints = [0, ..32];
+ let mut ints = [0i, ..32];
ints[0] += 1;
assert_eq!(ints[0], 1);
}
fn test2() {
- let mut ints = [0, ..32];
+ let mut ints = [0i, ..32];
for i in ints.mut_iter() { *i += 22; }
for i in ints.iter() { assert!(*i == 22); }
}
match Some::<int>(5) {
Some::<int>(_x) => {
let mut bar;
- match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } }
+ match None::<int> { None::<int> => { bar = 5i; } _ => { baz(); } }
println!("{:?}", bar);
}
None::<int> => { println!("hello"); }
}
pub fn main() {
- let mv = myvec(vec!(1, 2, 3));
+ let mv = myvec(vec!(1i, 2, 3));
let mv_clone = mv.clone();
let mv_clone = myvec_deref(mv_clone);
assert_eq!(*mv_clone.get(1), 2);
let bar = "bar".to_string();
let mut list = AssociationList {pairs: Vec::new()};
- list.push(foo.clone(), 22);
- list.push(bar.clone(), 44);
+ list.push(foo.clone(), 22i);
+ list.push(bar.clone(), 44i);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
pub fn main() {
- let a = &[1, 2, 3];
+ let a = &[1i, 2i, 3i];
assert_eq!(DerefArray {inner: a}[1], 2);
}
}
pub fn main() {
- let nested = DerefWrapper {x: true, y: DerefWrapper {x: 0, y: 1}};
+ let nested = DerefWrapper {x: true, y: DerefWrapper {x: 0i, y: 1i}};
// Use the first field that you can find.
assert_eq!(nested.x, true);
// Also go through multiple levels of indirection.
assert_eq!(Rc::new(nested).x, true);
- let nested_priv = priv_test::DerefWrapperHideX::new(true, DerefWrapper {x: 0, y: 1});
+ let nested_priv = priv_test::DerefWrapperHideX::new(true, DerefWrapper {x: 0i, y: 1i});
// FIXME(eddyb) #12808 should skip private fields.
// assert_eq!(nested_priv.x, 0);
assert_eq!((*nested_priv).x, 0);
extern crate overloaded_autoderef_xc;
fn main() {
- assert!(overloaded_autoderef_xc::check(5, 5));
+ assert!(overloaded_autoderef_xc::check(5i, 5i));
}
assert_eq!(point.x, 2);
assert_eq!(point.y, 4);
- let i = Rc::new(RefCell::new(2));
+ let i = Rc::new(RefCell::new(2i));
let i_value = *i.borrow();
*i.borrow_mut() = 5;
assert_eq!((i_value, *i.borrow()), (2, 5));
p.borrow_mut().y += 3;
assert_eq!(*p.borrow(), Point {x: 3, y: 5});
- let v = Rc::new(RefCell::new([1, 2, 3]));
+ let v = Rc::new(RefCell::new([1i, 2, 3]));
v.borrow_mut()[0] = 3;
v.borrow_mut()[1] += 3;
assert_eq!((v.borrow()[0], v.borrow()[1], v.borrow()[2]), (3, 5, 3));
}
pub fn main() {
- let mut n = DerefCounter::new(0);
+ let mut n = DerefCounter::new(0i);
let mut v = DerefCounter::new(Vec::new());
let _ = *n; // Immutable deref + copy a POD.
assert_eq!(n.counts(), (2, 1)); assert_eq!(v.counts(), (1, 1));
let mut v2 = Vec::new();
- v2.push(1);
+ v2.push(1i);
*n = 5; *v = v2; // Mutable deref + assignment.
assert_eq!(n.counts(), (2, 2)); assert_eq!(v.counts(), (1, 2));
}
pub fn main() {
- assert_eq!(*Rc::new(5), 5);
- assert_eq!(***Rc::new(box box 5), 5);
+ assert_eq!(*Rc::new(5i), 5);
+ assert_eq!(***Rc::new(box box 5i), 5);
assert_eq!(*Rc::new(Point {x: 2, y: 4}), Point {x: 2, y: 4});
- let i = Rc::new(RefCell::new(2));
+ let i = Rc::new(RefCell::new(2i));
let i_value = *(*i).borrow();
*(*i).borrow_mut() = 5;
assert_eq!((i_value, *(*i).borrow()), (2, 5));
(*(*p).borrow_mut()).y += 3;
assert_eq!(*(*p).borrow(), Point {x: 3, y: 5});
- let v = Rc::new(RefCell::new(vec!(1, 2, 3)));
+ let v = Rc::new(RefCell::new(vec!(1i, 2, 3)));
*(*(*v).borrow_mut()).get_mut(0) = 3;
*(*(*v).borrow_mut()).get_mut(1) += 3;
assert_eq!((*(*(*v).borrow()).get(0),
is_static::<proc():'static>();
- let a = 3;
+ let a = 3i;
bar::<proc()>(proc() {
let b = &a;
println!("{}", *b);
#![feature(globs)]
-// FIXME #3654
-
mod a {
pub fn f() {}
pub fn g() {}
use reexported_static_methods::Bort;
pub fn main() {
- assert_eq!(42, Foo::foo());
- assert_eq!(84, Baz::bar());
- assert!(Boz::boz(1));
+ assert_eq!(42i, Foo::foo());
+ assert_eq!(84i, Baz::bar());
+ assert!(Boz::boz(1i));
assert_eq!("bort()".to_string(), Bort::bort());
}
}
pub fn main() {
- let mut i = 3;
+ let mut i = 3i;
assert_eq!(i, 3);
{
let cl = || i += 1;
}
impl<'t> MakerTrait<'t> for Box<Trait<'t>> {
- fn mk() -> Box<Trait<'t>> { box() (4,5) as Box<Trait> }
+ fn mk() -> Box<Trait<'t>> { box() (4i,5i) as Box<Trait> }
}
enum List<'l> {
}
pub fn main() {
- let t = (2,3);
+ let t = (2i,3i);
let o = &t as &Trait;
let s1 = Struct1 { f: o };
let s2 = Struct2 { f: o };
}
pub fn main() {
- let b1 = Box { t: &3 };
- assert_eq!(add(b1, b1), 6);
+ let b1 = Box { t: &3i };
+ assert_eq!(add(b1, b1), 6i);
}
}
pub fn main() {
- let b1 = Box { t: &3 };
- assert_eq!(add(b1, b1), 6);
+ let b1 = Box { t: &3i };
+ assert_eq!(add(b1, b1), 6i);
}
fn borrow<'r, T>(x: &'r T) -> &'r T {x}
pub fn main() {
- let x = box(GC) 3;
+ let x = box(GC) 3i;
loop {
let y = borrow(x);
assert_eq!(*x, *y);
}
pub fn main() {
- let mut x = Some(23);
+ let mut x = Some(23i);
{
let y = get(&x);
assert_eq!(*y, 23);
}
- x = Some(24);
+ x = Some(24i);
{
let y = get(&x);
pub fn main() {
let x = [ [true], ..512 ];
- let y = [ 0, ..1 ];
+ let y = [ 0i, ..1 ];
println!("{:?}", x);
println!("{:?}", y);
assert!(("hello".to_string() < "hellr".to_string()));
assert!(("hello ".to_string() > "hello".to_string()));
assert!(("hello".to_string() != "there".to_string()));
- assert!((vec!(1, 2, 3, 4) > vec!(1, 2, 3)));
- assert!((vec!(1, 2, 3) < vec!(1, 2, 3, 4)));
- assert!((vec!(1, 2, 4, 4) > vec!(1, 2, 3, 4)));
- assert!((vec!(1, 2, 3, 4) < vec!(1, 2, 4, 4)));
- assert!((vec!(1, 2, 3) <= vec!(1, 2, 3)));
- assert!((vec!(1, 2, 3) <= vec!(1, 2, 3, 3)));
- assert!((vec!(1, 2, 3, 4) > vec!(1, 2, 3)));
- assert_eq!(vec!(1, 2, 3), vec!(1, 2, 3));
- assert!((vec!(1, 2, 3) != vec!(1, 1, 3)));
+ assert!((vec!(1i, 2, 3, 4) > vec!(1, 2, 3)));
+ assert!((vec!(1i, 2, 3) < vec!(1, 2, 3, 4)));
+ assert!((vec!(1i, 2, 4, 4) > vec!(1, 2, 3, 4)));
+ assert!((vec!(1i, 2, 3, 4) < vec!(1, 2, 4, 4)));
+ assert!((vec!(1i, 2, 3) <= vec!(1, 2, 3)));
+ assert!((vec!(1i, 2, 3) <= vec!(1, 2, 3, 3)));
+ assert!((vec!(1i, 2, 3, 4) > vec!(1, 2, 3)));
+ assert_eq!(vec!(1i, 2, 3), vec!(1, 2, 3));
+ assert!((vec!(1i, 2, 3) != vec!(1, 1, 3)));
}
}
fn test_misc() {
- assert_eq!(1 << 1i8 << 1u8 << 1i16 << 1u8 << 1u64, 32);
+ assert_eq!(1i << 1 << 1 << 1 << 1 << 1, 32);
}
fn test_expr() {
let v10 = 10 as uint;
let v4 = 4 as u8;
let v2 = 2 as u8;
- assert_eq!(v10 >> v2, v2 as uint);
- assert_eq!(v10 << v4, 160 as uint);
+ assert_eq!(v10 >> v2 as uint, v2 as uint);
+ assert_eq!(v10 << v4 as uint, 160 as uint);
let v10 = 10 as u8;
let v4 = 4 as uint;
let v2 = 2 as uint;
- assert_eq!(v10 >> v2, v2 as u8);
- assert_eq!(v10 << v4, 160 as u8);
+ assert_eq!(v10 >> v2 as uint, v2 as u8);
+ assert_eq!(v10 << v4 as uint, 160 as u8);
let v10 = 10 as int;
let v4 = 4 as i8;
let v2 = 2 as i8;
- assert_eq!(v10 >> v2, v2 as int);
- assert_eq!(v10 << v4, 160 as int);
+ assert_eq!(v10 >> v2 as uint, v2 as int);
+ assert_eq!(v10 << v4 as uint, 160 as int);
let v10 = 10 as i8;
let v4 = 4 as int;
let v2 = 2 as int;
- assert_eq!(v10 >> v2, v2 as i8);
- assert_eq!(v10 << v4, 160 as i8);
+ assert_eq!(v10 >> v2 as uint, v2 as i8);
+ assert_eq!(v10 << v4 as uint, 160 as i8);
let v10 = 10 as uint;
let v4 = 4 as int;
let v2 = 2 as int;
- assert_eq!(v10 >> v2, v2 as uint);
- assert_eq!(v10 << v4, 160 as uint);
+ assert_eq!(v10 >> v2 as uint, v2 as uint);
+ assert_eq!(v10 << v4 as uint, 160 as uint);
}
fn test_const() {
- static r1_1: uint = 10u >> 2u8;
- static r2_1: uint = 10u << 4u8;
+ static r1_1: uint = 10u >> 2u;
+ static r2_1: uint = 10u << 4u;
assert_eq!(r1_1, 2 as uint);
assert_eq!(r2_1, 160 as uint);
assert_eq!(r1_2, 2 as u8);
assert_eq!(r2_2, 160 as u8);
- static r1_3: int = 10 >> 2i8;
- static r2_3: int = 10 << 4i8;
+ static r1_3: int = 10 >> 2u;
+ static r2_3: int = 10 << 4u;
assert_eq!(r1_3, 2 as int);
assert_eq!(r2_3, 160 as int);
- static r1_4: i8 = 10i8 >> 2;
- static r2_4: i8 = 10i8 << 4;
+ static r1_4: i8 = 10i8 >> 2u;
+ static r2_4: i8 = 10i8 << 4u;
assert_eq!(r1_4, 2 as i8);
assert_eq!(r2_4, 160 as i8);
- static r1_5: uint = 10u >> 2i8;
- static r2_5: uint = 10u << 4i8;
+ static r1_5: uint = 10u >> 2u;
+ static r2_5: uint = 10u << 4u;
assert_eq!(r1_5, 2 as uint);
assert_eq!(r2_5, 160 as uint);
}
-pub fn main() { let mut n; n = 1; println!("{}", n); }
+pub fn main() { let mut n; n = 1i; println!("{}", n); }
assert_eq!(10u.plus(), 30);
assert_eq!(("hi".to_string()).plus(), 200);
- assert_eq!((vec!(1)).length_().str(), "1".to_string());
- let vect = vec!(3, 4).map_(|a| *a + 4);
+ assert_eq!((vec!(1i)).length_().str(), "1".to_string());
+ let vect = vec!(3i, 4).map_(|a| *a + 4);
assert_eq!(*vect.get(0), 7);
- let vect = (vec!(3, 4)).map_::<uint>(|a| *a as uint + 4u);
+ let vect = (vec!(3i, 4)).map_::<uint>(|a| *a as uint + 4u);
assert_eq!(*vect.get(0), 7u);
let mut x = 0u;
10u.multi(|_n| x += 2u );
pub fn main() {
let foo = Foo {
- bar: 0,
- baz: 1
+ bar: 0i,
+ baz: 1i
};
let foo_ = foo.clone();
}
pub fn main() {
- let a = (1, 2, 3);
- let b = (1, 2, 3);
+ let a = (1i, 2i, 3i);
+ let b = (1i, 2i, 3i);
assert_eq!(a, b);
assert!((a != (1, 2, 4)));
assert!((a < (1, 2, 4)));
assert!((a <= (1, 2, 4)));
- assert!(((1, 2, 4) > a));
- assert!(((1, 2, 4) >= a));
+ assert!(((1i, 2i, 4i) > a));
+ assert!(((1i, 2i, 4i) >= a));
let x = large;
let y = small;
assert!((x != y));
impl<S: Clone + Add<S, S>> Movable<S> for Point<S> {}
pub fn main() {
- let mut p = Point{ x: 1, y: 2};
+ let mut p = Point{ x: 1i, y: 2i};
p.translate(3);
assert_eq!(p.X(), 4);
}
rx1.recv();
let mut v = Vec::new();
- for _ in range(0, 10000) {
+ for _ in range(0u, 10000) {
match TcpStream::connect_timeout(addr, 100) {
Ok(e) => v.push(e),
Err(ref e) if e.kind == io::TimedOut => return,
let addr = rx.recv();
let (tx, rx) = channel();
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
let tx = tx.clone();
TaskBuilder::new().stack_size(64 * 1024).spawn(proc() {
let host = addr.ip.to_str();
// Wait for all clients to exit, but don't wait for the server to exit. The
// server just runs infinitely.
drop(tx);
- for _ in range(0, 1000) {
+ for _ in range(0u, 1000) {
rx.recv();
}
unsafe { libc::exit(0) }
impl<T> Foo for Bar<T> { }
pub fn main() {
- let a = Bar { x: 1 };
+ let a = Bar { x: 1u };
let b = &a as &Foo;
}
pub fn main() {
let t1 = Tree(box(GC) RefCell::new(TreeR{left: None,
right: None,
- val: box 1 as Box<to_str+Send>}));
+ val: box 1i as Box<to_str+Send>}));
let t2 = Tree(box(GC) RefCell::new(TreeR{left: Some(t1),
right: Some(t1),
- val: box 2 as Box<to_str+Send>}));
+ val: box 2i as Box<to_str+Send>}));
let expected =
"[2, some([1, none, none]), some([1, none, none])]".to_string();
assert!(t2.to_str_() == expected);
}
pub fn main () {
- assert_eq!(f(0, 1, 2), (1, 2));
- assert_eq!(f(0u, 1, 2), (1, 2));
+ assert_eq!(f(0i, 1i, 2i), (1, 2));
+ assert_eq!(f(0u, 1i, 2i), (1, 2));
}
}
pub fn main () {
- assert_eq!(f(0, 2), 2);
+ assert_eq!(f(0i, 2i), 2);
}
}
pub fn main () {
- assert_eq!(f(0, 1, 2), (1, 2));
- assert_eq!(f(0, 1u8, 2u8), (1u8, 2u8));
+ assert_eq!(f(0i, 1i, 2i), (1, 2));
+ assert_eq!(f(0i, 1u8, 2u8), (1u8, 2u8));
}
}
pub fn main () {
- f(0);
+ f(0i);
}
pub fn main() {
// Some tests of random things
- f(0);
+ f(0i);
- assert_eq!(A::lurr(&0, &1), 21);
+ assert_eq!(A::lurr(&0i, &1i), 21);
let a = stuff::thing { x: 0 };
let b = stuff::thing { x: 1 };
assert_eq!(a.h(), 11);
assert_eq!(c.h(), 11);
- assert_eq!(0i.thing(3.14, 1), (3.14, 1));
- assert_eq!(B::staticthing(&0i, 3.14, 1), (3.14, 1));
+ assert_eq!(0i.thing(3.14f64, 1i), (3.14f64, 1i));
+ assert_eq!(B::staticthing(&0i, 3.14f64, 1i), (3.14f64, 1i));
assert_eq!(B::<f64>::staticthing::<int>(&0i, 3.14, 1), (3.14, 1));
- assert_eq!(g(0i, 3.14, 1), (3.14, 1));
- assert_eq!(g(false, 3.14, 1), (3.14, 1));
+ assert_eq!(g(0i, 3.14f64, 1i), (3.14f64, 1i));
+ assert_eq!(g(false, 3.14f64, 1i), (3.14, 1));
let obj = box 0i as Box<A>;
assert_eq!(obj.h(), 11);
// Trying out a real one
- assert!(12.test_neq(&10));
- assert!(!10.test_neq(&10));
+ assert!(12i.test_neq(&10i));
+ assert!(!10i.test_neq(&10i));
assert!(a.test_neq(&b));
assert!(!a.test_neq(&a));
- assert!(neq(&12, &10));
- assert!(!neq(&10, &10));
+ assert!(neq(&12i, &10i));
+ assert!(!neq(&10i, &10i));
assert!(neq(&a, &b));
assert!(!neq(&a, &a));
}
impl<T> map<T> for Vec<T> {
fn map<U>(&self, f: |&T| -> U) -> Vec<U> {
let mut r = Vec::new();
- // FIXME: #7355 generates bad code with VecIterator
- for i in range(0u, self.len()) {
- r.push(f(self.get(i)));
+ for i in self.iter() {
+ r.push(f(i));
}
r
}
}
pub fn main() {
- assert_eq!(foo(vec!(1)), vec!("hi".to_string()));
+ assert_eq!(foo(vec!(1i)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
pub trait FloatExt: NumExt {}
-fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
-fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
+fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1i).unwrap() }
+fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1i).unwrap() }
pub fn main() {}
pub trait NumExt: Num + NumCast { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
- n.gt(&NumCast::from(1).unwrap())
+ n.gt(&NumCast::from(1i).unwrap())
}
pub fn main() {}
pub trait NumExt: Num + NumCast + PartialOrd { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
- *n > NumCast::from(1).unwrap()
+ *n > NumCast::from(1i).unwrap()
}
pub fn main() {}
impl NumExt for f32 {}
fn num_eq_one<T:NumExt>(n: T) {
- println!("{}", n == NumCast::from(1).unwrap())
+ println!("{}", n == NumCast::from(1i).unwrap())
}
pub fn main() {
impl NumExt for int {}
fn num_eq_one<T:NumExt>() -> T {
- NumCast::from(1).unwrap()
+ NumCast::from(1i).unwrap()
}
pub fn main() {
}
pub fn main() {
- f(&0)
+ f(&0i)
}
pub fn main() {
assert!(1.to_string() == "1".to_string());
- assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_string());
+ assert!((vec!(2i, 3, 4)).to_string() == "[2, 3, 4]".to_string());
fn indirect<T:to_str>(x: T) -> String {
format!("{}!", x.to_string())
}
- assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_string());
+ assert!(indirect(vec!(10i, 20)) == "[10, 20]!".to_string());
fn indirect2<T:to_str>(x: T) -> String {
indirect(x)
}
- assert!(indirect2(vec!(1)) == "[1]!".to_string());
+ assert!(indirect2(vec!(1i)) == "[1]!".to_string());
}
pub fn main() {
let (tx, rx) = channel();
- tx.send(42);
+ tx.send(42i);
let r = rx.recv();
println!("{:?}", r);
}
// except according to those terms.
pub fn main() {
- let mut i = box 1;
+ let mut i = box 1i;
// Should be a copy
let mut j;
j = i.clone();
#![allow(dead_assignment)]
pub fn main() {
- let i = box 1;
- let mut j = box 2;
+ let i = box 1i;
+ let mut j = box 2i;
// Should drop the previous value of j
j = i;
assert_eq!(*j, 1);
}
pub fn main() {
- let t = f(box 100);
- assert_eq!(t, box 100);
- let t = f(box box(GC) vec!(100));
- assert_eq!(t, box box(GC) vec!(100));
+ let t = f(box 100i);
+ assert_eq!(t, box 100i);
+ let t = f(box box(GC) vec!(100i));
+ assert_eq!(t, box box(GC) vec!(100i));
}
pub fn main() {
let mut i;
- i = box 1;
+ i = box 1i;
assert_eq!(*i, 1);
}
pub fn main() {
- let i = box vec!(100);
- assert_eq!(*i.get(0), 100);
+ let i = box vec!(100i);
+ assert_eq!(*i.get(0), 100i);
}
// except according to those terms.
pub fn main() {
- let i = box 100;
- assert!(i == box 100);
- assert!(i < box 101);
- assert!(i <= box 100);
- assert!(i > box 99);
- assert!(i >= box 99);
+ let i = box 100i;
+ assert!(i == box 100i);
+ assert!(i < box 101i);
+ assert!(i <= box 100i);
+ assert!(i > box 99i);
+ assert!(i >= box 99i);
}
// except according to those terms.
pub fn main() {
- let mut i = box 1;
+ let mut i = box 1i;
// Should be a copy
let mut j = i.clone();
- *i = 2;
- *j = 3;
- assert_eq!(*i, 2);
- assert_eq!(*j, 3);
+ *i = 2i;
+ *j = 3i;
+ assert_eq!(*i, 2i);
+ assert_eq!(*j, 3i);
}
// except according to those terms.
pub fn main() {
- let i = box 1;
+ let i = box 1i;
let j = i;
assert_eq!(*j, 1);
}
// except according to those terms.
pub fn main() {
- let i = box 100;
+ let i = box 100i;
let j = i;
assert_eq!(*j, 100);
}
// except according to those terms.
pub fn main() {
- let i = box 100;
+ let i = box 100i;
assert_eq!(*i, 100);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
fn f(i: Box<int>) {
assert_eq!(*i, 100);
}
pub fn main() {
- let i = box 100;
+ let i = box 100i;
f(i);
}
pub fn main() {
- let mut a = vec!(box 10);
+ let mut a = vec!(box 10i);
let b = a.clone();
assert_eq!(**a.get(0), 10);
// except according to those terms.
pub fn main() {
- let vect = vec!(box 100);
+ let vect = vec!(box 100i);
assert!(*vect.get(0) == box 100);
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i = box 100i;
+ let j = box 100i;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i = box 100i;
+ let j = box 101i;
g(i, j);
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i = box 100i;
+ let j = box 100i;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i = box 100i;
+ let j = box 101i;
g(i, j);
}
assert!(i != j);
}
- let i = box 100;
- let j = box 100;
+ let i = box 100i;
+ let j = box 100i;
f(i, j);
- let i = box 100;
- let j = box 101;
+ let i = box 100i;
+ let j = box 101i;
g(i, j);
}
extern crate debug;
pub fn main() {
- let i = box 100;
+ let i = box 100i;
println!("{:?}", i);
}
#![allow(unused_variable)]
pub fn main() {
- let i = box 100;
- let j = box 200;
+ let i = box 100i;
+ let j = box 200i;
let j = i;
assert_eq!(*j, 100);
}
pub fn main() {
let mut i;
- i = box 100;
+ i = box 100i;
assert_eq!(*i, 100);
}
// except according to those terms.
pub fn main() {
- let i = box 100;
+ let i = box 100i;
let mut j;
j = i;
assert_eq!(*j, 100);
// except according to those terms.
pub fn main() {
- let mut i = box 0;
+ let mut i = box 0i;
*i = 1;
assert_eq!(*i, 1);
}
pub fn main() {
let (tx, rx) = channel();
- tx.send(box 100);
+ tx.send(box 100i);
let v = rx.recv();
- assert_eq!(v, box 100);
+ assert_eq!(v, box 100i);
}
use std::mem::swap;
pub fn main() {
- let mut i = box 100;
- let mut j = box 200;
+ let mut i = box 100i;
+ let mut j = box 200i;
swap(&mut i, &mut j);
- assert_eq!(i, box 200);
- assert_eq!(j, box 100);
+ assert_eq!(i, box 200i);
+ assert_eq!(j, box 100i);
}
enum myoption<T> { none, some(T), }
-pub fn main() { println!("{}", 5); }
+pub fn main() { println!("{}", 5i); }
enum myoption<T> { none, some(T), }
-pub fn main() { println!("{}", 5); }
+pub fn main() { println!("{}", 5i); }
use std::num;
pub fn main() {
- let ε = 0.00001;
- let Π = 3.14;
+ let ε = 0.00001f64;
+ let Π = 3.14f64;
let लंच = Π * Π + 1.54;
assert!(num::abs((लंच - 1.54) - (Π * Π)) < ε);
assert_eq!(საჭმელად_გემრიელი_სადილი(), 0);
// Lunch in several languages.
- let ランチ = 10;
- let 午餐 = 10;
+ let ランチ = 10i;
+ let 午餐 = 10i;
- let ארוחת_צהריי = 10;
- let غداء = 10;
- let լանչ = 10;
- let обед = 10;
- let абед = 10;
- let μεσημεριανό = 10;
- let hádegismatur = 10;
- let ручек = 10;
+ let ארוחת_צהריי = 10i;
+ let غداء = 10u;
+ let լանչ = 10i;
+ let обед = 10i;
+ let абед = 10i;
+ let μεσημεριανό = 10i;
+ let hádegismatur = 10i;
+ let ручек = 10i;
- let ăn_trưa = 10;
- let อาหารกลางวัน = 10;
+ let ăn_trưa = 10i;
+ let อาหารกลางวัน = 10i;
// Lunchy arithmetic, mm.
assert_eq!(hádegismatur * ручек * обед, 1000);
- assert_eq!(10, ארוחת_צהריי);
+ assert_eq!(10i, ארוחת_צהריי);
assert_eq!(ランチ + 午餐 + μεσημεριανό, 30);
assert_eq!(ăn_trưa + อาหารกลางวัน, 20);
return (абед + լանչ) >> غداء;
pub fn main() {
- let mut v = vec!(1);
- v.push(2);
- v.push(3);
- v.push(4);
- v.push(5);
+ let mut v = vec!(1i);
+ v.push(2i);
+ v.push(3i);
+ v.push(4i);
+ v.push(5i);
assert_eq!(*v.get(0), 1);
assert_eq!(*v.get(1), 2);
assert_eq!(*v.get(2), 3);
pub fn main() {
- assert_eq!(vec!(1), vec!(1,));
- assert_eq!(vec!(1, 2, 3), vec!(1, 2, 3,));
+ assert_eq!(vec!(1i), vec!(1i,));
+ assert_eq!(vec!(1i, 2, 3), vec!(1i, 2, 3,));
}
// except according to those terms.
pub fn main() {
- let x = [1, 2, 3];
+ let x = [1i, 2, 3];
match x {
[2, _, _] => fail!(),
[1, a, b] => {
[_, _, _] => fail!(),
}
- let y = ([(1, true), (2, false)], 0.5);
+ let y = ([(1i, true), (2i, false)], 0.5f64);
match y {
([(1, a), (b, false)], _) => {
assert_eq!(a, true);
// except according to those terms.
fn a() {
- let x = [1, 2, 3];
+ let x = [1i, 2, 3];
match x {
[1, 2, 4] => unreachable!(),
[0, 2, 3, ..] => unreachable!(),
}
pub fn main() {
- let x = [1, 2, 3, 4, 5];
+ let x = [1i, 2, 3, 4, 5];
- let product = foldl(x, 1, |a, b| a * *b);
+ let product = foldl(x, 1i, |a, b| a * *b);
assert_eq!(product, 120);
- let sum = foldr(x, 0, |a, b| *a + b);
+ let sum = foldr(x, 0i, |a, b| *a + b);
assert_eq!(sum, 15);
}
// except according to those terms.
pub fn main() {
- let x = &[1, 2, 3, 4, 5];
+ let x = &[1i, 2, 3, 4, 5];
if !x.is_empty() {
let el = match x {
[1, ..ref tail] => &tail[0],
// except according to those terms.
fn a() {
- let x = [1];
+ let x = [1i];
match x {
[a] => {
assert_eq!(a, 1);
}
fn b() {
- let x = [1, 2, 3];
+ let x = [1i, 2, 3];
match x {
[a, b, ..c] => {
assert_eq!(a, 1);
}
fn c() {
- let x = [1];
+ let x = [1i];
match x {
[2, ..] => fail!(),
[..] => ()
}
fn d() {
- let x = [1, 2, 3];
+ let x = [1i, 2, 3];
let branch = match x {
- [1, 1, ..] => 0,
- [1, 2, 3, ..] => 1,
- [1, 2, ..] => 2,
+ [1, 1, ..] => 0i,
+ [1, 2, 3, ..] => 1i,
+ [1, 2, ..] => 2i,
_ => 3
};
assert_eq!(branch, 1);
// except according to those terms.
pub fn main() {
- let v = vec!(1,2,3,4,5);
+ let v = vec!(1i,2,3,4,5);
let v2 = v.slice(1, 3);
assert_eq!(v2[0], 2);
assert_eq!(v2[1], 3);
// except according to those terms.
pub fn main() {
- assert_eq!((vec!(0, 1)).to_str(), "[0, 1]".to_string());
- assert_eq!((&[1, 2]).to_str(), "[1, 2]".to_string());
+ assert_eq!((vec!(0i, 1)).to_str(), "[0, 1]".to_string());
+ assert_eq!((&[1i, 2]).to_str(), "[1, 2]".to_string());
- let foo = vec!(3, 4);
- let bar = &[4, 5];
+ let foo = vec!(3i, 4);
+ let bar = &[4i, 5];
assert_eq!(foo.to_str(), "[3, 4]".to_string());
assert_eq!(bar.to_str(), "[4, 5]".to_string());
pub fn main() {
// len can't go above 64.
for len in range(2u, MAX_LEN) {
- for _ in range(0, 10) {
+ for _ in range(0i, 10) {
let main = task_rng().gen_iter::<DropCounter>()
.take(len)
.collect::<Vec<DropCounter>>();
main.clone().as_mut_slice().sort_by(|a, b| { count += 1; a.cmp(b) });
// ... and then fail on each and every single one.
- for fail_countdown in range(0, count) {
+ for fail_countdown in range(0i, count) {
// refresh the counters.
unsafe {
drop_counts = [0, .. MAX_LEN];
fn p() -> bool { true }
let _a = (assert!((true)) == (assert!(p())));
let _c = (assert!((p())) == ());
- let _b: bool = (println!("{}", 0) == (return 0u));
+ let _b: bool = (println!("{}", 0i) == (return 0u));
}
fn angrydome() {
// Issue #825: Should recheck the loop condition after continuing
pub fn main() {
- let mut i = 1;
+ let mut i = 1i;
while i > 0 {
assert!((i > 0));
println!("{}", i);