auto merge of #8385 : cmr/rust/big-rollup, r=alexcrichton

This is a fairly large rollup, but I've tested everything locally, and none of
it should be platform-specific.

r=alexcrichton (bdfdbdd)
r=brson (d803c18)
r=alexcrichton (a5041d0)
r=bstrie (317412a)
r=alexcrichton (135c85e)
r=thestinger (8805baa)
r=pcwalton (0661178)
r=cmr (9397fe0)
r=cmr (caa4135)
r=cmr (6a21d93)
r=cmr (4dc3379)
r=cmr (0aa5154)
r=cmr (18be261)
r=thestinger (f10be03)
This commit is contained in:
bors 2013-08-08 14:32:02 -07:00
commit 8f65dbfcfa
70 changed files with 772 additions and 564 deletions

View File

@ -228,6 +228,48 @@ unsafe fn kaboom(ptr: *int) -> int { *ptr }
This function can only be called from an `unsafe` block or another `unsafe` function.
# Accessing foreign globals
Foreign APIs often export a global variable which could do something like track
global state. In order to access these variables, you declare them in `extern`
blocks with the `static` keyword:
~~~{.xfail-test}
use std::libc;
#[link_args = "-lreadline"]
extern {
static rl_readline_version: libc::c_int;
}
fn main() {
println(fmt!("You have readline version %d installed.",
rl_readline_version as int));
}
~~~
Alternatively, you may need to alter global state provided by a foreign
interface. To do this, statics can be declared with `mut` so rust can mutate
them.
~~~{.xfail-test}
use std::libc;
use std::ptr;
#[link_args = "-lreadline"]
extern {
static mut rl_prompt: *libc::c_char;
}
fn main() {
do "[my-awesome-shell] $".as_c_str |buf| {
unsafe { rl_prompt = buf; }
// get a line, process it
unsafe { rl_prompt = ptr::null(); }
}
}
~~~
# Foreign calling conventions
Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when

View File

@ -2288,8 +2288,8 @@ pub mod farm {
}
impl Farm {
priv fn feed_chickens(&self) { ... }
priv fn feed_cows(&self) { ... }
fn feed_chickens(&self) { ... }
fn feed_cows(&self) { ... }
pub fn add_chicken(&self, c: Chicken) { ... }
}

View File

@ -412,8 +412,8 @@ fn check_expected_errors(expected_errors: ~[errors::ExpectedError],
}
}
for i in range(0u, found_flags.len()) {
if !found_flags[i] {
for (i, &flag) in found_flags.iter().enumerate() {
if !flag {
let ee = &expected_errors[i];
fatal_ProcRes(fmt!("expected %s on line %u not found: %s",
ee.kind, ee.line, ee.msg), ProcRes);

View File

@ -50,6 +50,7 @@
<keyword>for</keyword>
<keyword>if</keyword>
<keyword>impl</keyword>
<keyword>in</keyword>
<keyword>let</keyword>
<keyword>log</keyword>
<keyword>loop</keyword>

View File

@ -847,22 +847,16 @@ mod tests {
}
assert_eq!(*state, 42);
*state = 31337;
// FIXME: #7372: hits type inference bug with iterators
// send to other readers
for i in range(0u, reader_convos.len()) {
match reader_convos[i] {
(ref rc, _) => rc.send(()),
}
for &(ref rc, _) in reader_convos.iter() {
rc.send(())
}
}
let read_mode = arc.downgrade(write_mode);
do (&read_mode).read |state| {
// FIXME: #7372: hits type inference bug with iterators
// complete handshake with other readers
for i in range(0u, reader_convos.len()) {
match reader_convos[i] {
(_, ref rp) => rp.recv(),
}
for &(_, ref rp) in reader_convos.iter() {
rp.recv()
}
wc1.send(()); // tell writer to try again
assert_eq!(*state, 31337);

View File

@ -145,14 +145,16 @@ impl BigBitv {
let len = b.storage.len();
assert_eq!(self.storage.len(), len);
let mut changed = false;
for i in range(0, len) {
for (i, (a, b)) in self.storage.mut_iter()
.zip(b.storage.iter())
.enumerate() {
let mask = big_mask(nbits, i);
let w0 = self.storage[i] & mask;
let w1 = b.storage[i] & mask;
let w0 = *a & mask;
let w1 = *b & mask;
let w = op(w0, w1) & mask;
if w0 != w {
changed = true;
self.storage[i] = w;
*a = w;
}
}
changed
@ -160,7 +162,7 @@ impl BigBitv {
#[inline]
pub fn each_storage(&mut self, op: &fn(v: &mut uint) -> bool) -> bool {
range(0u, self.storage.len()).advance(|i| op(&mut self.storage[i]))
self.storage.mut_iter().advance(|elt| op(elt))
}
#[inline]
@ -205,10 +207,9 @@ impl BigBitv {
#[inline]
pub fn equals(&self, b: &BigBitv, nbits: uint) -> bool {
let len = b.storage.len();
for i in range(0, len) {
for (i, elt) in b.storage.iter().enumerate() {
let mask = big_mask(nbits, i);
if mask & self.storage[i] != mask & b.storage[i] {
if mask & self.storage[i] != mask & *elt {
return false;
}
}

View File

@ -129,27 +129,27 @@ struct FileInput_ {
`Some(path)` is the file represented by `path`, `None` is
`stdin`. Consumed as the files are read.
*/
priv files: ~[Option<Path>],
files: ~[Option<Path>],
/**
The current file: `Some(r)` for an open file, `None` before
starting and after reading everything.
*/
priv current_reader: Option<@io::Reader>,
priv state: FileInputState,
current_reader: Option<@io::Reader>,
state: FileInputState,
/**
Used to keep track of whether we need to insert the newline at the
end of a file that is missing it, which is needed to separate the
last and first lines.
*/
priv previous_was_newline: bool
previous_was_newline: bool
}
// XXX: remove this when Reader has &mut self. Should be removable via
// "self.fi." -> "self." and renaming FileInput_. Documentation above
// will likely have to be updated to use `let mut in = ...`.
pub struct FileInput {
priv fi: @mut FileInput_
fi: @mut FileInput_
}
impl FileInput {
@ -198,7 +198,7 @@ impl FileInput {
FileInput::from_vec(pathed)
}
priv fn current_file_eof(&self) -> bool {
fn current_file_eof(&self) -> bool {
match self.fi.current_reader {
None => false,
Some(r) => r.eof()
@ -240,7 +240,7 @@ impl FileInput {
Returns `true` if it had to move to the next file and did
so successfully.
*/
priv fn next_file_if_eof(&self) -> bool {
fn next_file_if_eof(&self) -> bool {
match self.fi.current_reader {
None => self.next_file(),
Some(r) => {

View File

@ -43,8 +43,10 @@ static LZ_NONE : c_int = 0x0; // Huffman-coding only.
static LZ_FAST : c_int = 0x1; // LZ with only one probe
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static LZ_BEST : c_int = 0xfff; // LZ with 4095 probes, "best"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
do bytes.as_imm_buf |b, len| {
unsafe {
let mut outsz : size_t = 0;
@ -52,7 +54,33 @@ pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
rustrt::tdefl_compress_mem_to_heap(b as *c_void,
len as size_t,
&mut outsz,
LZ_NORM);
flags);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint);
libc::free(res);
out
}
}
}
pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
deflate_bytes_internal(bytes, LZ_NORM)
}
pub fn deflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
do bytes.as_imm_buf |b, len| {
unsafe {
let mut outsz : size_t = 0;
let res =
rustrt::tinfl_decompress_mem_to_heap(b as *c_void,
len as size_t,
&mut outsz,
flags);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint);
@ -63,21 +91,11 @@ pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
}
pub fn inflate_bytes(bytes: &[u8]) -> ~[u8] {
do bytes.as_imm_buf |b, len| {
unsafe {
let mut outsz : size_t = 0;
let res =
rustrt::tinfl_decompress_mem_to_heap(b as *c_void,
len as size_t,
&mut outsz,
0);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint);
libc::free(res);
out
}
inflate_bytes_internal(bytes, 0)
}
pub fn inflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
@ -109,4 +127,12 @@ mod tests {
assert_eq!(input, out);
}
}
#[test]
fn test_zlib_flate() {
let bytes = ~[1, 2, 3, 4, 5];
let deflated = deflate_bytes(bytes);
let inflated = inflate_bytes(deflated);
assert_eq!(inflated, bytes);
}
}

View File

@ -46,7 +46,7 @@ impl<A> Drop for Future<A> {
fn drop(&self) {}
}
priv enum FutureState<A> {
enum FutureState<A> {
Pending(~fn() -> A),
Evaluating,
Forced(A)

View File

@ -114,7 +114,8 @@ pub enum Occur {
pub struct Opt {
name: Name,
hasarg: HasArg,
occur: Occur
occur: Occur,
aliases: ~[Opt],
}
fn mkname(nm: &str) -> Name {
@ -127,29 +128,29 @@ fn mkname(nm: &str) -> Name {
/// Create an option that is required and takes an argument
pub fn reqopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Req};
return Opt {name: mkname(name), hasarg: Yes, occur: Req, aliases: ~[]};
}
/// Create an option that is optional and takes an argument
pub fn optopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Optional};
return Opt {name: mkname(name), hasarg: Yes, occur: Optional, aliases: ~[]};
}
/// Create an option that is optional and does not take an argument
pub fn optflag(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: No, occur: Optional};
return Opt {name: mkname(name), hasarg: No, occur: Optional, aliases: ~[]};
}
/** Create an option that is optional, does not take an argument,
* and may occur multiple times.
*/
pub fn optflagmulti(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: No, occur: Multi};
return Opt {name: mkname(name), hasarg: No, occur: Multi, aliases: ~[]};
}
/// Create an option that is optional and takes an optional argument
pub fn optflagopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Maybe, occur: Optional};
return Opt {name: mkname(name), hasarg: Maybe, occur: Optional, aliases: ~[]};
}
/**
@ -157,7 +158,7 @@ pub fn optflagopt(name: &str) -> Opt {
* multiple times
*/
pub fn optmulti(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Multi};
return Opt {name: mkname(name), hasarg: Yes, occur: Multi, aliases: ~[]};
}
#[deriving(Clone, Eq)]
@ -189,7 +190,20 @@ fn name_str(nm: &Name) -> ~str {
}
fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> {
opts.iter().position(|opt| opt.name == nm)
// search main options
let pos = opts.iter().position(|opt| opt.name == nm);
if pos.is_some() {
return pos
}
// search in aliases
for candidate in opts.iter() {
if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() {
return opts.iter().position(|opt| opt.name == candidate.name);
}
}
None
}
/**
@ -488,8 +502,6 @@ pub mod groups {
use getopts::{HasArg, Long, Maybe, Multi, No, Occur, Opt, Optional, Req};
use getopts::{Short, Yes};
use std::vec;
/** one group of options, e.g., both -h and --help, along with
* their shared description and properties
*/
@ -542,6 +554,20 @@ pub mod groups {
occur: Optional};
}
/// Create a long option that can occur more than once and does not
/// take an argument
pub fn optflagmulti(short_name: &str, long_name: &str,
desc: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: short_name.to_owned(),
long_name: long_name.to_owned(),
hint: ~"",
desc: desc.to_owned(),
hasarg: No,
occur: Multi};
}
/// Create a long option that is optional and takes an optional argument
pub fn optflagopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
@ -573,7 +599,7 @@ pub mod groups {
// translate OptGroup into Opt
// (both short and long names correspond to different Opts)
pub fn long_to_short(lopt: &OptGroup) -> ~[Opt] {
pub fn long_to_short(lopt: &OptGroup) -> Opt {
let OptGroup{short_name: short_name,
long_name: long_name,
hasarg: hasarg,
@ -583,20 +609,25 @@ pub mod groups {
match (short_name.len(), long_name.len()) {
(0,0) => fail!("this long-format option was given no name"),
(0,_) => ~[Opt {name: Long((long_name)),
(0,_) => Opt {name: Long((long_name)),
hasarg: hasarg,
occur: occur}],
occur: occur,
aliases: ~[]},
(1,0) => ~[Opt {name: Short(short_name.char_at(0)),
(1,0) => Opt {name: Short(short_name.char_at(0)),
hasarg: hasarg,
occur: occur}],
occur: occur,
aliases: ~[]},
(1,_) => ~[Opt {name: Short(short_name.char_at(0)),
(1,_) => Opt {name: Long((long_name)),
hasarg: hasarg,
occur: occur},
Opt {name: Long((long_name)),
occur: occur,
aliases: ~[Opt {
name: Short(short_name.char_at(0)),
hasarg: hasarg,
occur: occur}],
occur: occur,
aliases: ~[]
}]},
(_,_) => fail!("something is wrong with the long-form opt")
}
@ -606,7 +637,7 @@ pub mod groups {
* Parse command line args with the provided long format options
*/
pub fn getopts(args: &[~str], opts: &[OptGroup]) -> ::getopts::Result {
::getopts::getopts(args, vec::flat_map(opts, long_to_short))
::getopts::getopts(args, opts.map(long_to_short))
}
/**
@ -708,7 +739,7 @@ pub mod groups {
* Fails during iteration if the string contains a non-whitespace
* sequence longer than the limit.
*/
priv fn each_split_within<'a>(ss: &'a str,
fn each_split_within<'a>(ss: &'a str,
lim: uint,
it: &fn(&'a str) -> bool) -> bool {
// Just for fun, let's write this as an state machine:
@ -778,7 +809,7 @@ pub mod groups {
}
#[test]
priv fn test_split_within() {
fn test_split_within() {
fn t(s: &str, i: uint, u: &[~str]) {
let mut v = ~[];
do each_split_within(s, i) |s| { v.push(s.to_owned()); true };
@ -1440,7 +1471,8 @@ mod tests {
#[test]
fn test_groups_long_to_short() {
let short = ~[reqopt("b"), reqopt("banana")];
let mut short = reqopt("banana");
short.aliases = ~[reqopt("b")];
let verbose = groups::reqopt("b", "banana", "some bananas", "VAL");
assert_eq!(groups::long_to_short(&verbose), short);
@ -1448,10 +1480,16 @@ mod tests {
#[test]
fn test_groups_getopts() {
let mut banana = reqopt("banana");
banana.aliases = ~[reqopt("b")];
let mut apple = optopt("apple");
apple.aliases = ~[optopt("a")];
let mut kiwi = optflag("kiwi");
kiwi.aliases = ~[optflag("k")];
let short = ~[
reqopt("b"), reqopt("banana"),
optopt("a"), optopt("apple"),
optflag("k"), optflagopt("kiwi"),
banana,
apple,
kiwi,
optflagopt("p"),
optmulti("l")
];
@ -1464,7 +1502,7 @@ mod tests {
groups::optmulti("l", "", "Desc", "VAL"),
];
let sample_args = ~[~"-k", ~"15", ~"--apple", ~"1", ~"k",
let sample_args = ~[~"--kiwi", ~"15", ~"--apple", ~"1", ~"k",
~"-p", ~"16", ~"l", ~"35"];
// FIXME #4681: sort options here?
@ -1472,6 +1510,19 @@ mod tests {
== groups::getopts(sample_args, verbose));
}
#[test]
fn test_groups_aliases_long_and_short() {
let opts = ~[
groups::optflagmulti("a", "apple", "Desc"),
];
let args = ~[~"-a", ~"--apple", ~"-a"];
let matches = groups::getopts(args, opts).unwrap();
assert_eq!(3, opt_count(&matches, "a"));
assert_eq!(3, opt_count(&matches, "apple"));
}
#[test]
fn test_groups_usage() {
let optgroups = ~[

View File

@ -59,13 +59,13 @@ pub mod BigDigit {
pub static bits: uint = 32;
pub static base: uint = 1 << bits;
priv static hi_mask: uint = (-1 as uint) << bits;
priv static lo_mask: uint = (-1 as uint) >> bits;
static hi_mask: uint = (-1 as uint) << bits;
static lo_mask: uint = (-1 as uint) >> bits;
priv fn get_hi(n: uint) -> BigDigit { (n >> bits) as BigDigit }
fn get_hi(n: uint) -> BigDigit { (n >> bits) as BigDigit }
priv fn get_lo(n: uint) -> BigDigit { (n & lo_mask) as BigDigit }
fn get_lo(n: uint) -> BigDigit { (n & lo_mask) as BigDigit }
/// Split one machine sized unsigned integer into two BigDigits.
@ -613,7 +613,7 @@ impl BigUint {
}
priv fn shl_unit(&self, n_unit: uint) -> BigUint {
fn shl_unit(&self, n_unit: uint) -> BigUint {
if n_unit == 0 || self.is_zero() { return (*self).clone(); }
return BigUint::new(vec::from_elem(n_unit, ZERO_BIG_DIGIT)
@ -621,7 +621,7 @@ impl BigUint {
}
priv fn shl_bits(&self, n_bits: uint) -> BigUint {
fn shl_bits(&self, n_bits: uint) -> BigUint {
if n_bits == 0 || self.is_zero() { return (*self).clone(); }
let mut carry = 0;
@ -637,7 +637,7 @@ impl BigUint {
}
priv fn shr_unit(&self, n_unit: uint) -> BigUint {
fn shr_unit(&self, n_unit: uint) -> BigUint {
if n_unit == 0 { return (*self).clone(); }
if self.data.len() < n_unit { return Zero::zero(); }
return BigUint::from_slice(
@ -646,7 +646,7 @@ impl BigUint {
}
priv fn shr_bits(&self, n_bits: uint) -> BigUint {
fn shr_bits(&self, n_bits: uint) -> BigUint {
if n_bits == 0 || self.data.is_empty() { return (*self).clone(); }
let mut borrow = 0;
@ -661,7 +661,7 @@ impl BigUint {
#[cfg(target_arch = "x86_64")]
priv fn get_radix_base(radix: uint) -> (uint, uint) {
fn get_radix_base(radix: uint) -> (uint, uint) {
assert!(1 < radix && radix <= 16);
match radix {
2 => (4294967296, 32),
@ -687,7 +687,7 @@ priv fn get_radix_base(radix: uint) -> (uint, uint) {
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "mips")]
priv fn get_radix_base(radix: uint) -> (uint, uint) {
fn get_radix_base(radix: uint) -> (uint, uint) {
assert!(1 < radix && radix <= 16);
match radix {
2 => (65536, 16),

View File

@ -16,7 +16,6 @@
#[allow(missing_doc)];
use std::iterator::{Iterator, IteratorUtil, Enumerate, FilterMap, Invert};
use std::uint;
use std::util::replace;
use std::vec::{VecIterator, VecMutIterator};
use std::vec;
@ -29,14 +28,12 @@ pub struct SmallIntMap<T> {
impl<V> Container for SmallIntMap<V> {
/// Return the number of elements in the map
fn len(&self) -> uint {
let mut sz = 0;
for i in range(0u, self.v.len()) {
match self.v[i] {
Some(_) => sz += 1,
None => {}
self.v.iter().count(|elt| elt.is_some())
}
}
sz
/// Return true if there are no elements in the map
fn is_empty(&self) -> bool {
self.v.iter().all(|elt| elt.is_none())
}
}
@ -116,48 +113,6 @@ impl<V> SmallIntMap<V> {
/// Create an empty SmallIntMap
pub fn new() -> SmallIntMap<V> { SmallIntMap{v: ~[]} }
/// Visit all key-value pairs in order
pub fn each<'a>(&'a self, it: &fn(&uint, &'a V) -> bool) -> bool {
for i in range(0u, self.v.len()) {
match self.v[i] {
Some(ref elt) => if !it(&i, elt) { return false; },
None => ()
}
}
true
}
/// Visit all keys in order
pub fn each_key(&self, blk: &fn(key: &uint) -> bool) -> bool {
self.each(|k, _| blk(k))
}
/// Visit all values in order
pub fn each_value<'a>(&'a self, blk: &fn(value: &'a V) -> bool) -> bool {
self.each(|_, v| blk(v))
}
/// Iterate over the map and mutate the contained values
pub fn mutate_values(&mut self, it: &fn(&uint, &mut V) -> bool) -> bool {
for i in range(0, self.v.len()) {
match self.v[i] {
Some(ref mut elt) => if !it(&i, elt) { return false; },
None => ()
}
}
true
}
/// Visit all key-value pairs in reverse order
pub fn each_reverse<'a>(&'a self, it: &fn(uint, &'a V) -> bool) -> bool {
do uint::range_rev(self.v.len(), 0) |i| {
match self.v[i] {
Some(ref elt) => it(i, elt),
None => true
}
}
}
pub fn get<'a>(&'a self, key: &uint) -> &'a V {
self.find(key).expect("key not present")
}

View File

@ -469,10 +469,7 @@ impl<T:Clone + Ord> MergeState<T> {
base2: uint, len2: uint) {
assert!(len1 != 0 && len2 != 0 && base1+len1 == base2);
let mut tmp = ~[];
for i in range(base1, base1+len1) {
tmp.push(array[i].clone());
}
let mut tmp = array.slice(base1, base1 + len1).to_owned();
let mut c1 = 0;
let mut c2 = base2;
@ -579,10 +576,7 @@ impl<T:Clone + Ord> MergeState<T> {
base2: uint, len2: uint) {
assert!(len1 != 1 && len2 != 0 && base1 + len1 == base2);
let mut tmp = ~[];
for i in range(base2, base2+len2) {
tmp.push(array[i].clone());
}
let mut tmp = array.slice(base2, base2 + len2).to_owned();
let mut c1 = base1 + len1 - 1;
let mut c2 = len2 - 1;

View File

@ -223,7 +223,7 @@ impl<'self> Stats for &'self [f64] {
// Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
// linear interpolation. If samples are not sorted, return nonsensical value.
priv fn percentile_of_sorted(sorted_samples: &[f64],
fn percentile_of_sorted(sorted_samples: &[f64],
pct: f64) -> f64 {
assert!(sorted_samples.len() != 0);
if sorted_samples.len() == 1 {

View File

@ -75,7 +75,7 @@ pub mod attr {
}
#[cfg(not(target_os = "win32"))]
priv fn cap_for_attr(attr: attr::Attr) -> &'static str {
fn cap_for_attr(attr: attr::Attr) -> &'static str {
match attr {
attr::Bold => "bold",
attr::Dim => "dim",
@ -234,7 +234,7 @@ impl Terminal {
}
}
priv fn dim_if_necessary(&self, color: color::Color) -> color::Color {
fn dim_if_necessary(&self, color: color::Color) -> color::Color {
if color >= self.num_colors && color >= 8 && color < 16 {
color-8
} else { color }

View File

@ -430,7 +430,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
}
#[deriving(Eq)]
priv struct Flags {
struct Flags {
width: uint,
precision: uint,
alternate: bool,
@ -440,13 +440,13 @@ priv struct Flags {
}
impl Flags {
priv fn new() -> Flags {
fn new() -> Flags {
Flags{ width: 0, precision: 0, alternate: false,
left: false, sign: false, space: false }
}
}
priv enum FormatOp {
enum FormatOp {
FormatDigit,
FormatOctal,
FormatHex,
@ -455,7 +455,7 @@ priv enum FormatOp {
}
impl FormatOp {
priv fn from_char(c: char) -> FormatOp {
fn from_char(c: char) -> FormatOp {
match c {
'd' => FormatDigit,
'o' => FormatOctal,
@ -465,7 +465,7 @@ impl FormatOp {
_ => fail!("bad FormatOp char")
}
}
priv fn to_char(self) -> char {
fn to_char(self) -> char {
match self {
FormatDigit => 'd',
FormatOctal => 'o',
@ -476,7 +476,7 @@ impl FormatOp {
}
}
priv fn format(val: Param, op: FormatOp, flags: Flags) -> Result<~[u8],~str> {
fn format(val: Param, op: FormatOp, flags: Flags) -> Result<~[u8],~str> {
let mut s = match val {
Number(d) => {
match op {

View File

@ -254,7 +254,7 @@ impl Tm {
}
}
priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
fn match_str(s: &str, pos: uint, needle: &str) -> bool {
let mut i = pos;
for ch in needle.byte_iter() {
@ -687,7 +687,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
}
}
priv fn do_strftime(format: &str, tm: &Tm) -> ~str {
fn do_strftime(format: &str, tm: &Tm) -> ~str {
fn parse_type(ch: char, tm: &Tm) -> ~str {
//FIXME (#2350): Implement missing types.
let die = || fmt!("strftime: can't understand this format %c ", ch);

View File

@ -13,7 +13,6 @@
//! `TotalOrd`.
use std::num;
use std::util::{swap, replace};
use std::iterator::{FromIterator, Extendable};
@ -42,39 +41,23 @@ pub struct TreeMap<K, V> {
impl<K: Eq + TotalOrd, V: Eq> Eq for TreeMap<K, V> {
fn eq(&self, other: &TreeMap<K, V>) -> bool {
if self.len() != other.len() {
false
} else {
let mut x = self.iter();
let mut y = other.iter();
for _ in range(0u, self.len()) {
if x.next().unwrap() != y.next().unwrap() {
return false
self.len() == other.len() &&
self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
true
}
}
fn ne(&self, other: &TreeMap<K, V>) -> bool { !self.eq(other) }
}
// Lexicographical comparison
fn lt<K: Ord + TotalOrd, V: Ord>(a: &TreeMap<K, V>,
b: &TreeMap<K, V>) -> bool {
let mut x = a.iter();
let mut y = b.iter();
let (a_len, b_len) = (a.len(), b.len());
for _ in range(0u, num::min(a_len, b_len)) {
let (key_a, value_a) = x.next().unwrap();
let (key_b, value_b) = y.next().unwrap();
// the Zip iterator is as long as the shortest of a and b.
for ((key_a, value_a), (key_b, value_b)) in a.iter().zip(b.iter()) {
if *key_a < *key_b { return true; }
if *key_a > *key_b { return false; }
if *value_a < *value_b { return true; }
if *value_a > *value_b { return false; }
}
a_len < b_len
a.len() < b.len()
}
impl<K: Ord + TotalOrd, V: Ord> Ord for TreeMap<K, V> {
@ -151,36 +134,11 @@ impl<K: TotalOrd, V> TreeMap<K, V> {
/// Create an empty TreeMap
pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
/// Visit all keys in order
pub fn each_key(&self, f: &fn(&K) -> bool) -> bool {
self.iter().advance(|(k, _)| f(k))
}
/// Visit all values in order
pub fn each_value<'a>(&'a self, f: &fn(&'a V) -> bool) -> bool {
self.iter().advance(|(_, v)| f(v))
}
/// Iterate over the map and mutate the contained values
pub fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool) -> bool {
mutate_values(&mut self.root, f)
}
/// Visit all key-value pairs in reverse order
pub fn each_reverse<'a>(&'a self, f: &fn(&'a K, &'a V) -> bool) -> bool {
each_reverse(&self.root, f)
}
/// Visit all keys in reverse order
pub fn each_key_reverse(&self, f: &fn(&K) -> bool) -> bool {
self.each_reverse(|k, _| f(k))
}
/// Visit all values in reverse order
pub fn each_value_reverse(&self, f: &fn(&V) -> bool) -> bool {
self.each_reverse(|_, v| f(v))
}
/// Get a lazy iterator over the key-value pairs in the map.
/// Requires that it be frozen (immutable).
pub fn iter<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
@ -192,6 +150,12 @@ impl<K: TotalOrd, V> TreeMap<K, V> {
}
}
/// Get a lazy reverse iterator over the key-value pairs in the map.
/// Requires that it be frozen (immutable).
pub fn rev_iter<'a>(&'a self) -> TreeMapRevIterator<'a, K, V> {
TreeMapRevIterator{iter: self.iter()}
}
/// Get a lazy iterator that should be initialized using
/// `iter_traverse_left`/`iter_traverse_right`/`iter_traverse_complete`.
fn iter_for_traversal<'a>(&'a self) -> TreeMapIterator<'a, K, V> {
@ -270,20 +234,18 @@ pub struct TreeMapIterator<'self, K, V> {
priv remaining_max: uint
}
impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V> {
/// Advance the iterator to the next node (in order) and return a
/// tuple with a reference to the key and value. If there are no
/// more nodes, return `None`.
fn next(&mut self) -> Option<(&'self K, &'self V)> {
impl<'self, K, V> TreeMapIterator<'self, K, V> {
#[inline(always)]
fn next_(&mut self, forward: bool) -> Option<(&'self K, &'self V)> {
while !self.stack.is_empty() || self.node.is_some() {
match *self.node {
Some(ref x) => {
self.stack.push(x);
self.node = &x.left;
self.node = if forward { &x.left } else { &x.right };
}
None => {
let res = self.stack.pop();
self.node = &res.right;
self.node = if forward { &res.right } else { &res.left };
self.remaining_max -= 1;
if self.remaining_min > 0 {
self.remaining_min -= 1;
@ -294,6 +256,15 @@ impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V
}
None
}
}
impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V> {
/// Advance the iterator to the next node (in order) and return a
/// tuple with a reference to the key and value. If there are no
/// more nodes, return `None`.
fn next(&mut self) -> Option<(&'self K, &'self V)> {
self.next_(true)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
@ -301,6 +272,25 @@ impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapIterator<'self, K, V
}
}
/// Lazy backward iterator over a map
pub struct TreeMapRevIterator<'self, K, V> {
priv iter: TreeMapIterator<'self, K, V>,
}
impl<'self, K, V> Iterator<(&'self K, &'self V)> for TreeMapRevIterator<'self, K, V> {
/// Advance the iterator to the next node (in order) and return a
/// tuple with a reference to the key and value. If there are no
/// more nodes, return `None`.
fn next(&mut self) -> Option<(&'self K, &'self V)> {
self.iter.next_(false)
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
/// iter_traverse_left, iter_traverse_right and iter_traverse_complete are used to
/// initialize TreeMapIterator pointing to element inside tree structure.
///
@ -398,6 +388,14 @@ impl<'self, T> Iterator<&'self T> for TreeSetIterator<'self, T> {
}
}
impl<'self, T> Iterator<&'self T> for TreeSetRevIterator<'self, T> {
/// Advance the iterator to the next node (in order). If there are no more nodes, return `None`.
#[inline]
fn next(&mut self) -> Option<&'self T> {
do self.iter.next().map |&(value, _)| { value }
}
}
/// A implementation of the `Set` trait on top of the `TreeMap` container. The
/// only requirement is that the type of the elements contained ascribes to the
/// `TotalOrd` trait.
@ -449,20 +447,7 @@ impl<T: TotalOrd> Set<T> for TreeSet<T> {
/// Return true if the set has no elements in common with `other`.
/// This is equivalent to checking for an empty intersection.
fn is_disjoint(&self, other: &TreeSet<T>) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() && b.is_some() {
let a1 = a.unwrap();
let b1 = b.unwrap();
match a1.cmp(b1) {
Less => a = x.next(),
Greater => b = y.next(),
Equal => return false
}
}
true
self.intersection(other).next().is_none()
}
/// Return true if the set is a subset of another
@ -521,6 +506,13 @@ impl<T: TotalOrd> TreeSet<T> {
TreeSetIterator{iter: self.map.iter()}
}
/// Get a lazy iterator over the values in the set.
/// Requires that it be frozen (immutable).
#[inline]
pub fn rev_iter<'a>(&'a self) -> TreeSetRevIterator<'a, T> {
TreeSetRevIterator{iter: self.map.rev_iter()}
}
/// Get a lazy iterator pointing to the first value not less than `v` (greater or equal).
/// If all elements in the set are less than `v` empty iterator is returned.
#[inline]
@ -535,131 +527,26 @@ impl<T: TotalOrd> TreeSet<T> {
TreeSetIterator{iter: self.map.upper_bound_iter(v)}
}
/// Visit all values in reverse order
#[inline]
pub fn each_reverse(&self, f: &fn(&T) -> bool) -> bool {
self.map.each_key_reverse(f)
}
/// Visit the values (in-order) representing the difference
pub fn difference(&self, other: &TreeSet<T>, f: &fn(&T) -> bool) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() {
if b.is_none() {
return f(a.unwrap()) && x.advance(f);
}
let a1 = a.unwrap();
let b1 = b.unwrap();
let cmp = a1.cmp(b1);
if cmp == Less {
if !f(a1) { return false; }
a = x.next();
} else {
if cmp == Equal { a = x.next() }
b = y.next();
}
}
return true;
pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> Difference<'a, T> {
Difference{a: Focus::new(self.iter()), b: Focus::new(other.iter())}
}
/// Visit the values (in-order) representing the symmetric difference
pub fn symmetric_difference(&self, other: &TreeSet<T>,
f: &fn(&T) -> bool) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() {
if b.is_none() {
return f(a.unwrap()) && x.advance(f);
}
let a1 = a.unwrap();
let b1 = b.unwrap();
let cmp = a1.cmp(b1);
if cmp == Less {
if !f(a1) { return false; }
a = x.next();
} else {
if cmp == Greater {
if !f(b1) { return false; }
} else {
a = x.next();
}
b = y.next();
}
}
b.iter().advance(|&x| f(x)) && y.advance(f)
pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet<T>)
-> SymDifference<'a, T> {
SymDifference{a: Focus::new(self.iter()), b: Focus::new(other.iter())}
}
/// Visit the values (in-order) representing the intersection
pub fn intersection(&self, other: &TreeSet<T>, f: &fn(&T) -> bool) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() && b.is_some() {
let a1 = a.unwrap();
let b1 = b.unwrap();
let cmp = a1.cmp(b1);
if cmp == Less {
a = x.next();
} else {
if cmp == Equal {
if !f(a1) { return false }
}
b = y.next();
}
}
return true;
pub fn intersection<'a>(&'a self, other: &'a TreeSet<T>)
-> Intersection<'a, T> {
Intersection{a: Focus::new(self.iter()), b: Focus::new(other.iter())}
}
/// Visit the values (in-order) representing the union
pub fn union(&self, other: &TreeSet<T>, f: &fn(&T) -> bool) -> bool {
let mut x = self.iter();
let mut y = other.iter();
let mut a = x.next();
let mut b = y.next();
while a.is_some() {
if b.is_none() {
return f(a.unwrap()) && x.advance(f);
}
let a1 = a.unwrap();
let b1 = b.unwrap();
let cmp = a1.cmp(b1);
if cmp == Greater {
if !f(b1) { return false; }
b = y.next();
} else {
if !f(a1) { return false; }
if cmp == Equal {
b = y.next();
}
a = x.next();
}
}
b.iter().advance(|&x| f(x)) && y.advance(f)
pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> Union<'a, T> {
Union{a: Focus::new(self.iter()), b: Focus::new(other.iter())}
}
}
@ -668,6 +555,143 @@ pub struct TreeSetIterator<'self, T> {
priv iter: TreeMapIterator<'self, T, ()>
}
/// Lazy backward iterator over a set
pub struct TreeSetRevIterator<'self, T> {
priv iter: TreeMapRevIterator<'self, T, ()>
}
// Encapsulate an iterator and hold its latest value until stepped forward
struct Focus<A, T> {
priv iter: T,
priv focus: Option<A>,
}
impl<A, T: Iterator<A>> Focus<A, T> {
fn new(mut it: T) -> Focus<A, T> {
Focus{focus: it.next(), iter: it}
}
fn step(&mut self) {
self.focus = self.iter.next()
}
}
/// Lazy iterator producing elements in the set difference (in-order)
pub struct Difference<'self, T> {
priv a: Focus<&'self T, TreeSetIterator<'self, T>>,
priv b: Focus<&'self T, TreeSetIterator<'self, T>>,
}
/// Lazy iterator producing elements in the set symmetric difference (in-order)
pub struct SymDifference<'self, T> {
priv a: Focus<&'self T, TreeSetIterator<'self, T>>,
priv b: Focus<&'self T, TreeSetIterator<'self, T>>,
}
/// Lazy iterator producing elements in the set intersection (in-order)
pub struct Intersection<'self, T> {
priv a: Focus<&'self T, TreeSetIterator<'self, T>>,
priv b: Focus<&'self T, TreeSetIterator<'self, T>>,
}
/// Lazy iterator producing elements in the set intersection (in-order)
pub struct Union<'self, T> {
priv a: Focus<&'self T, TreeSetIterator<'self, T>>,
priv b: Focus<&'self T, TreeSetIterator<'self, T>>,
}
impl<'self, T: TotalOrd> Iterator<&'self T> for Difference<'self, T> {
fn next(&mut self) -> Option<&'self T> {
loop {
match (self.a.focus, self.b.focus) {
(None , _ ) => return None,
(ret , None ) => { self.a.step(); return ret },
(Some(a1), Some(b1)) => {
let cmp = a1.cmp(b1);
if cmp == Less {
self.a.step();
return Some(a1);
} else {
if cmp == Equal { self.a.step() }
self.b.step();
}
}
}
}
}
}
impl<'self, T: TotalOrd> Iterator<&'self T> for SymDifference<'self, T> {
fn next(&mut self) -> Option<&'self T> {
loop {
match (self.a.focus, self.b.focus) {
(ret , None ) => { self.a.step(); return ret },
(None , ret ) => { self.b.step(); return ret },
(Some(a1), Some(b1)) => {
let cmp = a1.cmp(b1);
if cmp == Less {
self.a.step();
return Some(a1);
} else {
self.b.step();
if cmp == Greater {
return Some(b1);
} else {
self.a.step();
}
}
}
}
}
}
}
impl<'self, T: TotalOrd> Iterator<&'self T> for Intersection<'self, T> {
fn next(&mut self) -> Option<&'self T> {
loop {
match (self.a.focus, self.b.focus) {
(None , _ ) => return None,
(_ , None ) => return None,
(Some(a1), Some(b1)) => {
let cmp = a1.cmp(b1);
if cmp == Less {
self.a.step();
} else {
self.b.step();
if cmp == Equal {
return Some(a1);
}
}
},
}
}
}
}
impl<'self, T: TotalOrd> Iterator<&'self T> for Union<'self, T> {
fn next(&mut self) -> Option<&'self T> {
loop {
match (self.a.focus, self.b.focus) {
(ret , None) => { self.a.step(); return ret },
(None , ret ) => { self.b.step(); return ret },
(Some(a1), Some(b1)) => {
let cmp = a1.cmp(b1);
if cmp == Greater {
self.b.step();
return Some(b1);
} else {
self.a.step();
if cmp == Equal {
self.b.step();
}
return Some(a1);
}
}
}
}
}
}
// Nodes keep track of their level in the tree, starting at 1 in the
// leaves and with a red child sharing the level of the parent.
#[deriving(Clone)]
@ -687,18 +711,6 @@ impl<K: TotalOrd, V> TreeNode<K, V> {
}
}
fn each<'r, K: TotalOrd, V>(node: &'r Option<~TreeNode<K, V>>,
f: &fn(&'r K, &'r V) -> bool) -> bool {
node.iter().advance(|x| each(&x.left, |k,v| f(k,v)) && f(&x.key, &x.value) &&
each(&x.right, |k,v| f(k,v)))
}
fn each_reverse<'r, K: TotalOrd, V>(node: &'r Option<~TreeNode<K, V>>,
f: &fn(&'r K, &'r V) -> bool) -> bool {
node.iter().advance(|x| each_reverse(&x.right, |k,v| f(k,v)) && f(&x.key, &x.value) &&
each_reverse(&x.left, |k,v| f(k,v)))
}
fn mutate_values<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode<K, V>>,
f: &fn(&'r K, &'r mut V) -> bool)
-> bool {
@ -1129,7 +1141,7 @@ mod test_treemap {
}
#[test]
fn test_each_reverse() {
fn test_rev_iter() {
let mut m = TreeMap::new();
assert!(m.insert(3, 6));
@ -1139,12 +1151,11 @@ mod test_treemap {
assert!(m.insert(1, 2));
let mut n = 4;
do m.each_reverse |k, v| {
for (k, v) in m.rev_iter() {
assert_eq!(*k, n);
assert_eq!(*v, n * 2);
n -= 1;
true
};
}
}
#[test]
@ -1405,7 +1416,7 @@ mod test_set {
}
#[test]
fn test_each_reverse() {
fn test_rev_iter() {
let mut m = TreeSet::new();
assert!(m.insert(3));
@ -1415,11 +1426,10 @@ mod test_set {
assert!(m.insert(1));
let mut n = 4;
do m.each_reverse |x| {
for x in m.rev_iter() {
assert_eq!(*x, n);
n -= 1;
true
};
}
}
fn check(a: &[int], b: &[int], expected: &[int],
@ -1442,7 +1452,7 @@ mod test_set {
#[test]
fn test_intersection() {
fn check_intersection(a: &[int], b: &[int], expected: &[int]) {
check(a, b, expected, |x, y, z| x.intersection(y, z))
check(a, b, expected, |x, y, f| x.intersection(y).advance(f))
}
check_intersection([], [], []);
@ -1458,7 +1468,7 @@ mod test_set {
#[test]
fn test_difference() {
fn check_difference(a: &[int], b: &[int], expected: &[int]) {
check(a, b, expected, |x, y, z| x.difference(y, z))
check(a, b, expected, |x, y, f| x.difference(y).advance(f))
}
check_difference([], [], []);
@ -1476,7 +1486,7 @@ mod test_set {
fn test_symmetric_difference() {
fn check_symmetric_difference(a: &[int], b: &[int],
expected: &[int]) {
check(a, b, expected, |x, y, z| x.symmetric_difference(y, z))
check(a, b, expected, |x, y, f| x.symmetric_difference(y).advance(f))
}
check_symmetric_difference([], [], []);
@ -1491,7 +1501,7 @@ mod test_set {
fn test_union() {
fn check_union(a: &[int], b: &[int],
expected: &[int]) {
check(a, b, expected, |x, y, z| x.union(y, z))
check(a, b, expected, |x, y, f| x.union(y).advance(f))
}
check_union([], [], []);

View File

@ -159,10 +159,10 @@ impl<'self> CheckLoanCtxt<'self> {
true
};
for i in range(0u, new_loan_indices.len()) {
let old_loan = &self.all_loans[new_loan_indices[i]];
for j in range(i+1, new_loan_indices.len()) {
let new_loan = &self.all_loans[new_loan_indices[j]];
for (i, &x) in new_loan_indices.iter().enumerate() {
let old_loan = &self.all_loans[x];
for &y in new_loan_indices.slice_from(i+1).iter() {
let new_loan = &self.all_loans[y];
self.report_error_if_loans_conflict(old_loan, new_loan);
}
}

View File

@ -983,10 +983,10 @@ fn bitwise(out_vec: &mut [uint],
op: &fn(uint, uint) -> uint) -> bool {
assert_eq!(out_vec.len(), in_vec.len());
let mut changed = false;
for i in range(0u, out_vec.len()) {
let old_val = out_vec[i];
let new_val = op(old_val, in_vec[i]);
out_vec[i] = new_val;
for (out_elt, in_elt) in out_vec.mut_iter().zip(in_vec.iter()) {
let old_val = *out_elt;
let new_val = op(old_val, *in_elt);
*out_elt = new_val;
changed |= (old_val != new_val);
}
changed

View File

@ -187,12 +187,12 @@ impl<N,E> Graph<N,E> {
pub fn each_node(&self, f: &fn(NodeIndex, &Node<N>) -> bool) -> bool {
//! Iterates over all edges defined in the graph.
range(0u, self.nodes.len()).advance(|i| f(NodeIndex(i), &self.nodes[i]))
self.nodes.iter().enumerate().advance(|(i, node)| f(NodeIndex(i), node))
}
pub fn each_edge(&self, f: &fn(EdgeIndex, &Edge<E>) -> bool) -> bool {
//! Iterates over all edges defined in the graph.
range(0u, self.nodes.len()).advance(|i| f(EdgeIndex(i), &self.edges[i]))
//! Iterates over all edges defined in the graph
self.edges.iter().enumerate().advance(|(i, edge)| f(EdgeIndex(i), edge))
}
pub fn each_outgoing_edge(&self,

View File

@ -13,7 +13,7 @@ use driver::session::Session;
use metadata::csearch::{each_path, get_trait_method_def_ids};
use metadata::csearch::get_method_name_and_explicit_self;
use metadata::csearch::get_static_methods_if_impl;
use metadata::csearch::get_type_name_if_impl;
use metadata::csearch::{get_type_name_if_impl, get_struct_fields};
use metadata::cstore::find_extern_mod_stmt_cnum;
use metadata::decoder::{def_like, dl_def, dl_field, dl_impl};
use middle::lang_items::LanguageItems;
@ -1700,9 +1700,12 @@ impl Resolver {
}
def_struct(def_id) => {
debug!("(building reduced graph for external \
crate) building type %s",
crate) building type and value for %s",
final_ident);
child_name_bindings.define_type(privacy, def, dummy_sp());
if get_struct_fields(self.session.cstore, def_id).len() == 0 {
child_name_bindings.define_value(privacy, def, dummy_sp());
}
self.structs.insert(def_id);
}
def_method(*) => {

View File

@ -1742,8 +1742,7 @@ pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
_ => {}
}
for arg_n in range(0u, arg_tys.len()) {
let arg_ty = arg_tys[arg_n];
for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
let raw_llarg = raw_llargs[arg_n];
// For certain mode/type combinations, the raw llarg values are passed

View File

@ -145,8 +145,8 @@ fn classify_ty(ty: Type) -> ~[RegClass] {
}
fn all_mem(cls: &mut [RegClass]) {
for i in range(0u, cls.len()) {
cls[i] = Memory;
for elt in cls.mut_iter() {
*elt = Memory;
}
}

View File

@ -206,15 +206,8 @@ pub fn type_uses_for(ccx: @mut CrateContext, fn_id: def_id, n_tps: uint)
pub fn type_needs(cx: &Context, use_: uint, ty: ty::t) {
// Optimization -- don't descend type if all params already have this use
let len = {
let uses = &*cx.uses;
uses.len()
};
for i in range(0u, len) {
if cx.uses[i] & use_ != use_ {
if cx.uses.iter().any(|&elt| elt & use_ != use_) {
type_needs_inner(cx, use_, ty, @Nil);
return;
}
}
}

View File

@ -772,8 +772,8 @@ impl<'self> LookupContext<'self> {
self.tcx().sess.span_err(
self.expr.span,
"multiple applicable methods in scope");
for idx in range(0u, relevant_candidates.len()) {
self.report_candidate(idx, &relevant_candidates[idx].origin);
for (idx, candidate) in relevant_candidates.iter().enumerate() {
self.report_candidate(idx, &candidate.origin);
}
}

View File

@ -554,8 +554,8 @@ impl CoherenceChecker {
let mut provided_names = HashSet::new();
// Implemented methods
for i in range(0u, all_methods.len()) {
provided_names.insert(all_methods[i].ident);
for elt in all_methods.iter() {
provided_names.insert(elt.ident);
}
let r = ty::trait_methods(tcx, trait_did);

View File

@ -374,8 +374,8 @@ impl RegionVarBindings {
pub fn vars_created_since_snapshot(&mut self, snapshot: uint)
-> ~[RegionVid] {
do vec::build |push| {
for i in range(snapshot, self.undo_log.len()) {
match self.undo_log[i] {
for &elt in self.undo_log.slice_from(snapshot).iter() {
match elt {
AddVar(vid) => push(vid),
_ => ()
}

View File

@ -215,7 +215,7 @@ impl region_scope for MethodRscope {
pub struct type_rscope(Option<RegionParameterization>);
impl type_rscope {
priv fn replacement(&self) -> ty::Region {
fn replacement(&self) -> ty::Region {
if self.is_some() {
ty::re_bound(ty::br_self)
} else {

View File

@ -136,7 +136,7 @@ Additional help:
pub fn describe_warnings() {
use extra::sort::Sort;
printfln!("
println("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
@ -157,7 +157,7 @@ Available lint options:
fn padded(max: uint, s: &str) -> ~str {
str::from_bytes(vec::from_elem(max - s.len(), ' ' as u8)) + s
}
printfln!("\nAvailable lint checks:\n");
println("\nAvailable lint checks:\n");
printfln!(" %s %7.7s %s",
padded(max_key, "name"), "default", "meaning");
printfln!(" %s %7.7s %s\n",
@ -173,7 +173,7 @@ Available lint options:
}
pub fn describe_debug_flags() {
printfln!("\nAvailable debug options:\n");
println("\nAvailable debug options:\n");
let r = session::debugging_opts_map();
for tuple in r.iter() {
match *tuple {

View File

@ -54,7 +54,7 @@ pub struct CrateDoc {
pub enum ItemTag {
ModTag(ModDoc),
NmodTag(NmodDoc),
ConstTag(ConstDoc),
StaticTag(StaticDoc),
FnTag(FnDoc),
EnumTag(EnumDoc),
TraitTag(TraitDoc),
@ -95,7 +95,7 @@ pub struct NmodDoc {
index: Option<Index>
}
pub type ConstDoc = SimpleItemDoc;
pub type StaticDoc = SimpleItemDoc;
pub type FnDoc = SimpleItemDoc;
@ -214,8 +214,8 @@ impl ModDoc {
md!(FnTag)
}
pub fn consts(&self) -> ~[ConstDoc] {
md!(ConstTag)
pub fn statics(&self) -> ~[StaticDoc] {
md!(StaticTag)
}
pub fn enums(&self) -> ~[EnumDoc] {
@ -249,7 +249,7 @@ pub trait PageUtils {
fn mods(&self) -> ~[ModDoc];
fn nmods(&self) -> ~[NmodDoc];
fn fns(&self) -> ~[FnDoc];
fn consts(&self) -> ~[ConstDoc];
fn statics(&self) -> ~[StaticDoc];
fn enums(&self) -> ~[EnumDoc];
fn traits(&self) -> ~[TraitDoc];
fn impls(&self) -> ~[ImplDoc];
@ -270,8 +270,8 @@ impl PageUtils for ~[Page] {
pu!(FnTag)
}
fn consts(&self) -> ~[ConstDoc] {
pu!(ConstTag)
fn statics(&self) -> ~[StaticDoc] {
pu!(StaticTag)
}
fn enums(&self) -> ~[EnumDoc] {
@ -301,7 +301,7 @@ impl Item for ItemTag {
&doc::ModTag(ref doc) => doc.item.clone(),
&doc::NmodTag(ref doc) => doc.item.clone(),
&doc::FnTag(ref doc) => doc.item.clone(),
&doc::ConstTag(ref doc) => doc.item.clone(),
&doc::StaticTag(ref doc) => doc.item.clone(),
&doc::EnumTag(ref doc) => doc.item.clone(),
&doc::TraitTag(ref doc) => doc.item.clone(),
&doc::ImplTag(ref doc) => doc.item.clone(),

View File

@ -101,8 +101,8 @@ fn moddoc_from_mod(
))
}
ast::item_static(*) => {
Some(doc::ConstTag(
constdoc_from_const(ItemDoc)
Some(doc::StaticTag(
staticdoc_from_static(ItemDoc)
))
}
ast::item_enum(enum_definition, _) => {
@ -165,7 +165,7 @@ fn fndoc_from_fn(itemdoc: doc::ItemDoc) -> doc::FnDoc {
}
}
fn constdoc_from_const(itemdoc: doc::ItemDoc) -> doc::ConstDoc {
fn staticdoc_from_static(itemdoc: doc::ItemDoc) -> doc::StaticDoc {
doc::SimpleItemDoc {
item: itemdoc,
sig: None
@ -356,10 +356,10 @@ mod test {
}
#[test]
fn should_extract_const_name_and_id() {
fn should_extract_static_name_and_id() {
let doc = mk_doc(@"static a: int = 0;");
assert!(doc.cratemod().consts()[0].id() != 0);
assert!(doc.cratemod().consts()[0].name_() == ~"a");
assert!(doc.cratemod().statics()[0].id() != 0);
assert!(doc.cratemod().statics()[0].name_() == ~"a");
}
#[test]

View File

@ -21,7 +21,7 @@ pub struct Fold<T> {
fold_mod: FoldMod<T>,
fold_nmod: FoldNmod<T>,
fold_fn: FoldFn<T>,
fold_const: FoldConst<T>,
fold_static: FoldStatic<T>,
fold_enum: FoldEnum<T>,
fold_trait: FoldTrait<T>,
fold_impl: FoldImpl<T>,
@ -39,7 +39,7 @@ impl<T:Clone> Clone for Fold<T> {
fold_mod: self.fold_mod,
fold_nmod: self.fold_nmod,
fold_fn: self.fold_fn,
fold_const: self.fold_const,
fold_static: self.fold_static,
fold_enum: self.fold_enum,
fold_trait: self.fold_trait,
fold_impl: self.fold_impl,
@ -55,7 +55,7 @@ type FoldItem<T> = @fn(fold: &Fold<T>, doc: doc::ItemDoc) -> doc::ItemDoc;
type FoldMod<T> = @fn(fold: &Fold<T>, doc: doc::ModDoc) -> doc::ModDoc;
type FoldNmod<T> = @fn(fold: &Fold<T>, doc: doc::NmodDoc) -> doc::NmodDoc;
type FoldFn<T> = @fn(fold: &Fold<T>, doc: doc::FnDoc) -> doc::FnDoc;
type FoldConst<T> = @fn(fold: &Fold<T>, doc: doc::ConstDoc) -> doc::ConstDoc;
type FoldStatic<T> = @fn(fold: &Fold<T>, doc: doc::StaticDoc) -> doc::StaticDoc;
type FoldEnum<T> = @fn(fold: &Fold<T>, doc: doc::EnumDoc) -> doc::EnumDoc;
type FoldTrait<T> = @fn(fold: &Fold<T>, doc: doc::TraitDoc) -> doc::TraitDoc;
type FoldImpl<T> = @fn(fold: &Fold<T>, doc: doc::ImplDoc) -> doc::ImplDoc;
@ -73,7 +73,7 @@ fn mk_fold<T>(
fold_mod: FoldMod<T>,
fold_nmod: FoldNmod<T>,
fold_fn: FoldFn<T>,
fold_const: FoldConst<T>,
fold_static: FoldStatic<T>,
fold_enum: FoldEnum<T>,
fold_trait: FoldTrait<T>,
fold_impl: FoldImpl<T>,
@ -88,7 +88,7 @@ fn mk_fold<T>(
fold_mod: fold_mod,
fold_nmod: fold_nmod,
fold_fn: fold_fn,
fold_const: fold_const,
fold_static: fold_static,
fold_enum: fold_enum,
fold_trait: fold_trait,
fold_impl: fold_impl,
@ -106,7 +106,7 @@ pub fn default_any_fold<T:Clone>(ctxt: T) -> Fold<T> {
|f, d| default_any_fold_mod(f, d),
|f, d| default_any_fold_nmod(f, d),
|f, d| default_seq_fold_fn(f, d),
|f, d| default_seq_fold_const(f, d),
|f, d| default_seq_fold_static(f, d),
|f, d| default_seq_fold_enum(f, d),
|f, d| default_seq_fold_trait(f, d),
|f, d| default_seq_fold_impl(f, d),
@ -124,7 +124,7 @@ pub fn default_seq_fold<T:Clone>(ctxt: T) -> Fold<T> {
|f, d| default_seq_fold_mod(f, d),
|f, d| default_seq_fold_nmod(f, d),
|f, d| default_seq_fold_fn(f, d),
|f, d| default_seq_fold_const(f, d),
|f, d| default_seq_fold_static(f, d),
|f, d| default_seq_fold_enum(f, d),
|f, d| default_seq_fold_trait(f, d),
|f, d| default_seq_fold_impl(f, d),
@ -142,7 +142,7 @@ pub fn default_par_fold<T:Clone>(ctxt: T) -> Fold<T> {
|f, d| default_par_fold_mod(f, d),
|f, d| default_par_fold_nmod(f, d),
|f, d| default_seq_fold_fn(f, d),
|f, d| default_seq_fold_const(f, d),
|f, d| default_seq_fold_static(f, d),
|f, d| default_seq_fold_enum(f, d),
|f, d| default_seq_fold_trait(f, d),
|f, d| default_seq_fold_impl(f, d),
@ -272,8 +272,8 @@ pub fn fold_ItemTag<T>(fold: &Fold<T>, doc: doc::ItemTag) -> doc::ItemTag {
doc::FnTag(FnDoc) => {
doc::FnTag((fold.fold_fn)(fold, FnDoc))
}
doc::ConstTag(ConstDoc) => {
doc::ConstTag((fold.fold_const)(fold, ConstDoc))
doc::StaticTag(StaticDoc) => {
doc::StaticTag((fold.fold_static)(fold, StaticDoc))
}
doc::EnumTag(EnumDoc) => {
doc::EnumTag((fold.fold_enum)(fold, EnumDoc))
@ -303,10 +303,10 @@ pub fn default_seq_fold_fn<T>(
}
}
pub fn default_seq_fold_const<T>(
pub fn default_seq_fold_static<T>(
fold: &Fold<T>,
doc: doc::ConstDoc
) -> doc::ConstDoc {
doc: doc::StaticDoc
) -> doc::StaticDoc {
doc::SimpleItemDoc {
item: (fold.fold_item)(fold, doc.item.clone()),
.. doc
@ -374,7 +374,7 @@ fn default_fold_should_produce_same_doc() {
}
#[test]
fn default_fold_should_produce_same_consts() {
fn default_fold_should_produce_same_statics() {
let source = @"static a: int = 0;";
let ast = parse::from_str(source);
let doc = extract::extract(ast, ~"");

View File

@ -150,8 +150,8 @@ pub fn header_kind(doc: doc::ItemTag) -> ~str {
doc::FnTag(_) => {
~"Function"
}
doc::ConstTag(_) => {
~"Freeze"
doc::StaticTag(_) => {
~"Static"
}
doc::EnumTag(_) => {
~"Enum"
@ -321,7 +321,7 @@ fn write_item_(ctxt: &Ctxt, doc: doc::ItemTag, write_header: bool) {
doc::ModTag(ModDoc) => write_mod(ctxt, ModDoc),
doc::NmodTag(nModDoc) => write_nmod(ctxt, nModDoc),
doc::FnTag(FnDoc) => write_fn(ctxt, FnDoc),
doc::ConstTag(ConstDoc) => write_const(ctxt, ConstDoc),
doc::StaticTag(StaticDoc) => write_static(ctxt, StaticDoc),
doc::EnumTag(EnumDoc) => write_enum(ctxt, EnumDoc),
doc::TraitTag(TraitDoc) => write_trait(ctxt, TraitDoc),
doc::ImplTag(ImplDoc) => write_impl(ctxt, ImplDoc),
@ -409,9 +409,9 @@ fn code_block(s: ~str) -> ~str {
~~~", s)
}
fn write_const(
fn write_static(
ctxt: &Ctxt,
doc: doc::ConstDoc
doc: doc::StaticDoc
) {
write_sig(ctxt, doc.sig.clone());
write_common(ctxt, doc.desc(), doc.sections());
@ -775,13 +775,13 @@ mod test {
}
#[test]
fn should_write_const_header() {
fn should_write_static_header() {
let markdown = render(~"static a: bool = true;");
assert!(markdown.contains("## Freeze `a`\n\n"));
assert!(markdown.contains("## Static `a`\n\n"));
}
#[test]
fn should_write_const_description() {
fn should_write_static_description() {
let markdown = render(
~"#[doc = \"b\"]\
static a: bool = true;");

View File

@ -202,7 +202,7 @@ mod test {
let doc = mk_doc(
~"impl Foo {\
pub fn bar() { }\
priv fn baz() { }\
fn baz() { }\
}");
assert_eq!(doc.cratemod().impls()[0].methods.len(), 1);
}
@ -212,7 +212,7 @@ mod test {
let doc = mk_doc(
~"impl Foo {\
pub fn bar() { }\
priv fn baz() { }\
fn baz() { }\
}");
assert_eq!(doc.cratemod().impls()[0].methods.len(), 1);
}
@ -232,7 +232,7 @@ mod test {
let doc = mk_doc(
~"impl Foo {\
pub fn bar() { }\
priv fn baz() { }\
fn baz() { }\
}");
assert_eq!(doc.cratemod().impls()[0].methods.len(), 1);
}

View File

@ -18,7 +18,7 @@ pub fn mk_pass() -> Pass {
fn by_score(item1: &doc::ItemTag, item2: &doc::ItemTag) -> bool {
fn score(item: &doc::ItemTag) -> int {
match *item {
doc::ConstTag(_) => 0,
doc::StaticTag(_) => 0,
doc::TyTag(_) => 1,
doc::EnumTag(_) => 2,
doc::StructTag(_) => 3,
@ -43,7 +43,7 @@ fn test() {
let source =
~"mod imod { } \
static iconst: int = 0; \
static istatic: int = 0; \
fn ifn() { } \
enum ienum { ivar } \
trait itrait { fn a(); } \
@ -54,7 +54,7 @@ fn test() {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (mk_pass().f)(srv.clone(), doc);
// hidden __std_macros module at the start.
assert_eq!(doc.cratemod().items[0].name_(), ~"iconst");
assert_eq!(doc.cratemod().items[0].name_(), ~"istatic");
assert_eq!(doc.cratemod().items[1].name_(), ~"itype");
assert_eq!(doc.cratemod().items[2].name_(), ~"ienum");
assert_eq!(doc.cratemod().items[3].name_(), ~"istruct");

View File

@ -39,7 +39,7 @@ pub fn run(
let fold = Fold {
ctxt: srv.clone(),
fold_fn: fold_fn,
fold_const: fold_const,
fold_static: fold_static,
fold_enum: fold_enum,
fold_trait: fold_trait,
fold_impl: fold_impl,
@ -93,10 +93,10 @@ fn get_fn_sig(srv: astsrv::Srv, fn_id: doc::AstId) -> Option<~str> {
}
}
fn fold_const(
fn fold_static(
fold: &fold::Fold<astsrv::Srv>,
doc: doc::ConstDoc
) -> doc::ConstDoc {
doc: doc::StaticDoc
) -> doc::StaticDoc {
let srv = fold.ctxt.clone();
doc::SimpleItemDoc {
@ -109,7 +109,7 @@ fn fold_const(
}, _) => {
pprust::ty_to_str(ty, extract::interner())
}
_ => fail!("fold_const: id not bound to a const item")
_ => fail!("fold_static: id not bound to a static item")
}
}}),
.. doc
@ -384,9 +384,9 @@ mod test {
}
#[test]
fn should_add_const_types() {
fn should_add_static_types() {
let doc = mk_doc(~"static a: bool = true;");
assert!(doc.cratemod().consts()[0].sig == Some(~"bool"));
assert!(doc.cratemod().statics()[0].sig == Some(~"bool"));
}
#[test]

View File

@ -12,7 +12,7 @@
use clone::Clone;
use container::Container;
use iterator::{Iterator, range};
use iterator::Iterator;
use option::{Option, Some, None};
use sys;
use unstable::raw::Repr;
@ -92,8 +92,8 @@ pub fn append<T:Clone>(lhs: @[T], rhs: &[T]) -> @[T] {
for x in lhs.iter() {
push((*x).clone());
}
for i in range(0u, rhs.len()) {
push(rhs[i].clone());
for elt in rhs.iter() {
push(elt.clone());
}
}
}

View File

@ -314,7 +314,7 @@ mod pipesy {
#[allow(non_camel_case_types)]
pub mod oneshot {
priv use std::kinds::Send;
use std::kinds::Send;
use ptr::to_mut_unsafe_ptr;
pub fn init<T: Send>() -> (server::Oneshot<T>, client::Oneshot<T>) {
@ -341,7 +341,7 @@ mod pipesy {
#[allow(non_camel_case_types)]
pub mod client {
priv use std::kinds::Send;
use std::kinds::Send;
#[allow(non_camel_case_types)]
pub fn try_send<T: Send>(pipe: Oneshot<T>, x_0: T) ->
@ -489,7 +489,7 @@ mod pipesy {
#[allow(non_camel_case_types)]
pub mod streamp {
priv use std::kinds::Send;
use std::kinds::Send;
pub fn init<T: Send>() -> (server::Open<T>, client::Open<T>) {
pub use std::pipes::HasBuffer;
@ -501,7 +501,7 @@ mod pipesy {
#[allow(non_camel_case_types)]
pub mod client {
priv use std::kinds::Send;
use std::kinds::Send;
#[allow(non_camel_case_types)]
pub fn try_data<T: Send>(pipe: Open<T>, x_0: T) ->

View File

@ -19,7 +19,7 @@ use container::{Container, Mutable, Map, MutableMap, Set, MutableSet};
use clone::Clone;
use cmp::{Eq, Equiv};
use hash::Hash;
use iterator::{Iterator, IteratorUtil, FromIterator, Extendable, range};
use iterator::{Iterator, IteratorUtil, FromIterator, Extendable};
use iterator::{FilterMap, Chain, Repeat, Zip};
use num;
use option::{None, Option, Some};
@ -265,8 +265,8 @@ impl<K:Hash + Eq,V> Container for HashMap<K, V> {
impl<K:Hash + Eq,V> Mutable for HashMap<K, V> {
/// Clear the map, removing all key-value pairs.
fn clear(&mut self) {
for idx in range(0u, self.buckets.len()) {
self.buckets[idx] = None;
for bkt in self.buckets.mut_iter() {
*bkt = None;
}
self.size = 0;
}

View File

@ -18,9 +18,9 @@ implementing the `Iterator` trait.
*/
use cmp;
use num::{Zero, One, Saturating};
use num::{Zero, One, Integer, Saturating};
use option::{Option, Some, None};
use ops::{Add, Mul};
use ops::{Add, Mul, Sub};
use cmp::Ord;
use clone::Clone;
use uint;
@ -1531,7 +1531,7 @@ pub fn range<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> Range<A> {
Range{state: start, stop: stop, one: One::one()}
}
impl<A: Add<A, A> + Ord + Clone + One> Iterator<A> for Range<A> {
impl<A: Add<A, A> + Ord + Clone> Iterator<A> for Range<A> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.state < self.stop {
@ -1544,6 +1544,22 @@ impl<A: Add<A, A> + Ord + Clone + One> Iterator<A> for Range<A> {
}
}
impl<A: Sub<A, A> + Integer + Ord + Clone> DoubleEndedIterator<A> for Range<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
if self.stop > self.state {
// Integer doesn't technically define this rule, but we're going to assume that every
// Integer is reachable from every other one by adding or subtracting enough Ones. This
// seems like a reasonable-enough rule that every Integer should conform to, even if it
// can't be statically checked.
self.stop = self.stop - self.one;
Some(self.stop.clone())
} else {
None
}
}
}
impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
#[inline]
fn next(&mut self) -> Option<A> {
@ -2121,4 +2137,17 @@ mod tests {
check_randacc_iter(xs.iter().cycle().take_(27), 27);
check_randacc_iter(empty.iter().cycle(), 0);
}
#[test]
fn test_double_ended_range() {
assert_eq!(range(11i, 14).invert().collect::<~[int]>(), ~[13i, 12, 11]);
for _ in range(10i, 0).invert() {
fail!("unreachable");
}
assert_eq!(range(11u, 14).invert().collect::<~[uint]>(), ~[13u, 12, 11]);
for _ in range(10u, 0).invert() {
fail!("unreachable");
}
}
}

View File

@ -278,18 +278,22 @@ impl One for f64 {
#[cfg(not(test))]
impl Add<f64,f64> for f64 {
#[inline]
fn add(&self, other: &f64) -> f64 { *self + *other }
}
#[cfg(not(test))]
impl Sub<f64,f64> for f64 {
#[inline]
fn sub(&self, other: &f64) -> f64 { *self - *other }
}
#[cfg(not(test))]
impl Mul<f64,f64> for f64 {
#[inline]
fn mul(&self, other: &f64) -> f64 { *self * *other }
}
#[cfg(not(test))]
impl Div<f64,f64> for f64 {
#[inline]
fn div(&self, other: &f64) -> f64 { *self / *other }
}
#[cfg(not(test))]

View File

@ -124,14 +124,6 @@ pub fn range_step_inclusive(start: $T, last: $T, step: $T, it: &fn($T) -> bool)
range_step_core(start, last, step, Closed, it)
}
#[inline]
/// Iterate over the range (`hi`..`lo`]
pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool {
if hi == min_value { return true; }
range_step_inclusive(hi-1, lo, -1 as $T, it)
}
impl Num for $T {}
#[cfg(not(test))]
@ -889,10 +881,6 @@ mod tests {
fn test_ranges() {
let mut l = ~[];
do range_rev(14,11) |i| {
l.push(i);
true
};
do range_step(20,26,2) |i| {
l.push(i);
true
@ -917,8 +905,7 @@ mod tests {
l.push(i);
true
};
assert_eq!(l, ~[13,12,11,
20,22,24,
assert_eq!(l, ~[20,22,24,
36,34,32,
max_value-2,
max_value-3,max_value-1,
@ -926,9 +913,6 @@ mod tests {
min_value+3,min_value+1]);
// None of the `fail`s should execute.
do range_rev(0,10) |_i| {
fail!(~"unreachable");
};
do range_step(10,0,1) |_i| {
fail!(~"unreachable");
};

View File

@ -422,9 +422,9 @@ pub fn float_to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Float+Round+
// Some constants for from_str_bytes_common's input validation,
// they define minimum radix values for which the character is a valid digit.
priv static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
priv static DIGIT_I_RADIX: uint = ('i' as uint) - ('a' as uint) + 11u;
priv static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
static DIGIT_I_RADIX: uint = ('i' as uint) - ('a' as uint) + 11u;
static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
/**
* Parses a byte slice as a number. This is meant to

View File

@ -125,13 +125,6 @@ pub fn range_step_inclusive(start: $T, last: $T, step: $T_SIGNED, it: &fn($T) ->
range_step_core(start, last, step, Closed, it)
}
#[inline]
/// Iterate over the range (`hi`..`lo`]
pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool {
if hi == min_value { return true; }
range_step_inclusive(hi-1, lo, -1 as $T_SIGNED, it)
}
impl Num for $T {}
#[cfg(not(test))]
@ -654,10 +647,6 @@ mod tests {
pub fn test_ranges() {
let mut l = ~[];
do range_rev(14,11) |i| {
l.push(i);
true
};
do range_step(20,26,2) |i| {
l.push(i);
true
@ -683,8 +672,7 @@ mod tests {
true
};
assert_eq!(l, ~[13,12,11,
20,22,24,
assert_eq!(l, ~[20,22,24,
36,34,32,
max_value-2,
max_value-3,max_value-1,
@ -692,9 +680,6 @@ mod tests {
min_value+3,min_value+1]);
// None of the `fail`s should execute.
do range_rev(0,0) |_i| {
fail!("unreachable");
};
do range_step(10,0,1) |_i| {
fail!("unreachable");
};

View File

@ -610,15 +610,32 @@ impl<R: Rng> RngUtil for R {
}
/// Create a random number generator with a default algorithm and seed.
///
/// It returns the cryptographically-safest `Rng` algorithm currently
/// available in Rust. If you require a specifically seeded `Rng` for
/// consistency over time you should pick one algorithm and create the
/// `Rng` yourself.
pub fn rng() -> IsaacRng {
IsaacRng::new()
}
/// Create a weak random number generator with a default algorithm and seed.
///
/// It returns the fatest `Rng` algorithm currently available in Rust without
/// consideration for cryptography or security. If you require a specifically
/// seeded `Rng` for consistency over time you should pick one algorithm and
/// create the `Rng` yourself.
pub fn weak_rng() -> XorShiftRng {
XorShiftRng::new()
}
static RAND_SIZE_LEN: u32 = 8;
static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
/// A random number generator that uses the [ISAAC
/// algorithm](http://en.wikipedia.org/wiki/ISAAC_%28cipher%29).
///
/// The ISAAC algorithm is suitable for cryptographic purposes.
pub struct IsaacRng {
priv cnt: u32,
priv rsl: [u32, .. RAND_SIZE],
@ -794,8 +811,11 @@ impl Rng for IsaacRng {
}
/// An [Xorshift random number
/// generator](http://en.wikipedia.org/wiki/Xorshift). Not suitable for
/// cryptographic purposes.
/// generator](http://en.wikipedia.org/wiki/Xorshift).
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
priv x: u32,
priv y: u32,

View File

@ -508,7 +508,11 @@ impl<T> Peekable<T> for Port<T> {
}
}
impl<T> Select for Port<T> {
// XXX: Kind of gross. A Port<T> should be selectable so you can make an array
// of them, but a &Port<T> should also be selectable so you can select2 on it
// alongside a PortOne<U> without passing the port by value in recv_ready.
impl<'self, T> Select for &'self Port<T> {
#[inline]
fn optimistic_check(&mut self) -> bool {
do self.next.with_mut_ref |pone| { pone.optimistic_check() }
@ -526,12 +530,29 @@ impl<T> Select for Port<T> {
}
}
impl<T> SelectPort<(T, Port<T>)> for Port<T> {
fn recv_ready(self) -> Option<(T, Port<T>)> {
impl<T> Select for Port<T> {
#[inline]
fn optimistic_check(&mut self) -> bool {
(&*self).optimistic_check()
}
#[inline]
fn block_on(&mut self, sched: &mut Scheduler, task: BlockedTask) -> bool {
(&*self).block_on(sched, task)
}
#[inline]
fn unblock_from(&mut self) -> bool {
(&*self).unblock_from()
}
}
impl<'self, T> SelectPort<T> for &'self Port<T> {
fn recv_ready(self) -> Option<T> {
match self.next.take().recv_ready() {
Some(StreamPayload { val, next }) => {
self.next.put_back(next);
Some((val, self))
Some(val)
}
None => None
}

View File

@ -590,7 +590,8 @@ impl Death {
#[inline]
pub fn assert_may_sleep(&self) {
if self.wont_sleep != 0 {
rtabort!("illegal atomic-sleep: can't deschedule inside atomically()");
rtabort!("illegal atomic-sleep: attempt to reschedule while \
using an Exclusive or LittleLock");
}
}
}

View File

@ -199,9 +199,7 @@ mod test {
// get it back out
util::swap(port.get_mut_ref(), &mut ports[index]);
// NB. Not recv(), because optimistic_check randomly fails.
let (data, new_port) = port.take_unwrap().recv_ready().unwrap();
assert!(data == 31337);
port = Some(new_port);
assert!(port.get_ref().recv_ready().unwrap() == 31337);
}
}
}

View File

@ -632,7 +632,6 @@ fn spawn_process_os(prog: &str, args: &[~str],
use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp};
use libc::funcs::bsd44::getdtablesize;
use int;
mod rustrt {
use libc::c_void;
@ -665,10 +664,9 @@ fn spawn_process_os(prog: &str, args: &[~str],
fail!("failure in dup3(err_fd, 2): %s", os::last_os_error());
}
// close all other fds
do int::range_rev(getdtablesize() as int, 3) |fd| {
for fd in range(3, getdtablesize()).invert() {
close(fd as c_int);
true
};
}
do with_dirp(dir) |dirp| {
if !dirp.is_null() && chdir(dirp) == -1 {
@ -763,14 +761,14 @@ fn with_dirp<T>(d: Option<&Path>,
}
#[cfg(windows)]
priv fn free_handle(handle: *()) {
fn free_handle(handle: *()) {
unsafe {
libc::funcs::extra::kernel32::CloseHandle(cast::transmute(handle));
}
}
#[cfg(unix)]
priv fn free_handle(_handle: *()) {
fn free_handle(_handle: *()) {
// unix has no process handle object, just a pid
}
@ -825,7 +823,7 @@ pub fn process_output(prog: &str, args: &[~str]) -> ProcessOutput {
* operate on a none-existant process or, even worse, on a newer process
* with the same id.
*/
priv fn waitpid(pid: pid_t) -> int {
fn waitpid(pid: pid_t) -> int {
return waitpid_os(pid);
#[cfg(windows)]

View File

@ -738,7 +738,7 @@ pub fn count_bytes<'b>(s: &'b str, start: uint, n: uint) -> uint {
}
// https://tools.ietf.org/html/rfc3629
priv static UTF8_CHAR_WIDTH: [u8, ..256] = [
static UTF8_CHAR_WIDTH: [u8, ..256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
@ -781,15 +781,15 @@ macro_rules! utf8_acc_cont_byte(
)
// UTF-8 tags and ranges
priv static TAG_CONT_U8: u8 = 128u8;
priv static TAG_CONT: uint = 128u;
priv static MAX_ONE_B: uint = 128u;
priv static TAG_TWO_B: uint = 192u;
priv static MAX_TWO_B: uint = 2048u;
priv static TAG_THREE_B: uint = 224u;
priv static MAX_THREE_B: uint = 65536u;
priv static TAG_FOUR_B: uint = 240u;
priv static MAX_UNICODE: uint = 1114112u;
static TAG_CONT_U8: u8 = 128u8;
static TAG_CONT: uint = 128u;
static MAX_ONE_B: uint = 128u;
static TAG_TWO_B: uint = 192u;
static MAX_TWO_B: uint = 2048u;
static TAG_THREE_B: uint = 224u;
static MAX_THREE_B: uint = 65536u;
static TAG_FOUR_B: uint = 240u;
static MAX_UNICODE: uint = 1114112u;
/// Unsafe operations
pub mod raw {

View File

@ -274,7 +274,7 @@ pub fn to_ascii_lower(string: &str) -> ~str {
}
#[inline]
priv fn map_bytes(string: &str, map: &'static [u8]) -> ~str {
fn map_bytes(string: &str, map: &'static [u8]) -> ~str {
let len = string.len();
let mut result = str::with_capacity(len);
unsafe {
@ -298,7 +298,7 @@ pub fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
|(byte_a, byte_b)| ASCII_LOWER_MAP[*byte_a] == ASCII_LOWER_MAP[*byte_b])
}
priv static ASCII_LOWER_MAP: &'static [u8] = &[
static ASCII_LOWER_MAP: &'static [u8] = &[
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
@ -333,7 +333,7 @@ priv static ASCII_LOWER_MAP: &'static [u8] = &[
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
];
priv static ASCII_UPPER_MAP: &'static [u8] = &[
static ASCII_UPPER_MAP: &'static [u8] = &[
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,

View File

@ -271,8 +271,8 @@ impl<T> TrieNode<T> {
impl<T> TrieNode<T> {
fn each<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
for idx in range(0u, self.children.len()) {
match self.children[idx] {
for elt in self.children.iter() {
match *elt {
Internal(ref x) => if !x.each(|i,t| f(i,t)) { return false },
External(k, ref v) => if !f(&k, v) { return false },
Nothing => ()
@ -282,13 +282,14 @@ impl<T> TrieNode<T> {
}
fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
do uint::range_rev(self.children.len(), 0) |idx| {
match self.children[idx] {
Internal(ref x) => x.each_reverse(|i,t| f(i,t)),
External(k, ref v) => f(&k, v),
Nothing => true
for elt in self.children.rev_iter() {
match *elt {
Internal(ref x) => if !x.each_reverse(|i,t| f(i,t)) { return false },
External(k, ref v) => if !f(&k, v) { return false },
Nothing => ()
}
}
true
}
fn mutate_values<'a>(&'a mut self, f: &fn(&uint, &mut T) -> bool) -> bool {
@ -539,10 +540,9 @@ mod test_map {
fn test_each_break() {
let mut m = TrieMap::new();
do uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
for x in range(uint::max_value - 10000, uint::max_value).invert() {
m.insert(x, x / 2);
true
};
}
let mut n = uint::max_value - 10000;
do m.each |k, v| {
@ -580,10 +580,9 @@ mod test_map {
fn test_each_reverse_break() {
let mut m = TrieMap::new();
do uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
for x in range(uint::max_value - 10000, uint::max_value).invert() {
m.insert(x, x / 2);
true
};
}
let mut n = uint::max_value - 1;
do m.each_reverse |k, v| {
@ -634,10 +633,9 @@ mod test_map {
let last = uint::max_value;
let mut map = TrieMap::new();
do uint::range_rev(last, first) |x| {
for x in range(first, last).invert() {
map.insert(x, x / 2);
true
};
}
let mut i = 0;
for (k, &v) in map.iter() {

View File

@ -1602,8 +1602,8 @@ impl<T:Clone> OwnedCopyableVector<T> for ~[T] {
let new_len = self.len() + rhs.len();
self.reserve(new_len);
for i in range(0u, rhs.len()) {
self.push(unsafe { raw::get(rhs, i) })
for elt in rhs.iter() {
self.push((*elt).clone())
}
}

View File

@ -64,6 +64,7 @@ pub enum ObsoleteSyntax {
ObsoleteMutWithMultipleBindings,
ObsoleteExternVisibility,
ObsoleteUnsafeExternFn,
ObsoletePrivVisibility,
}
impl to_bytes::IterBytes for ObsoleteSyntax {
@ -253,6 +254,10 @@ impl ParserObsoleteMethods for Parser {
"external functions are always unsafe; remove the `unsafe` \
keyword"
),
ObsoletePrivVisibility => (
"`priv` not necessary",
"an item without a visibility qualifier is private by default"
),
};
self.report(sp, kind, kind_str, desc);

View File

@ -85,7 +85,7 @@ use parse::obsolete::{ObsoleteConstItem, ObsoleteFixedLengthVectorType};
use parse::obsolete::{ObsoleteNamedExternModule, ObsoleteMultipleLocalDecl};
use parse::obsolete::{ObsoleteMutWithMultipleBindings};
use parse::obsolete::{ObsoleteExternVisibility, ObsoleteUnsafeExternFn};
use parse::obsolete::{ParserObsoleteMethods};
use parse::obsolete::{ParserObsoleteMethods, ObsoletePrivVisibility};
use parse::token::{can_begin_expr, get_ident_interner, ident_to_str, is_ident};
use parse::token::{is_ident_or_path};
use parse::token::{is_plain_ident, INTERPOLATED, keywords, special_idents};
@ -814,7 +814,7 @@ impl Parser {
let attrs = p.parse_outer_attributes();
let lo = p.span.lo;
let vis = p.parse_visibility();
let vis = p.parse_non_priv_visibility();
let pur = p.parse_fn_purity();
// NB: at the moment, trait methods are public by default; this
// could change.
@ -3608,7 +3608,7 @@ impl Parser {
let attrs = self.parse_outer_attributes();
let lo = self.span.lo;
let visa = self.parse_visibility();
let visa = self.parse_non_priv_visibility();
let pur = self.parse_fn_purity();
let ident = self.parse_ident();
let generics = self.parse_generics();
@ -3871,6 +3871,18 @@ impl Parser {
else { inherited }
}
// parse visibility, but emits an obsolete error if it's private
fn parse_non_priv_visibility(&self) -> visibility {
match self.parse_visibility() {
public => public,
inherited => inherited,
private => {
self.obsolete(*self.last_span, ObsoletePrivVisibility);
inherited
}
}
}
fn parse_staticness(&self) -> bool {
if self.eat_keyword(keywords::Static) {
self.obsolete(*self.last_span, ObsoleteStaticMethod);
@ -4063,7 +4075,7 @@ impl Parser {
// parse a function declaration from a foreign module
fn parse_item_foreign_fn(&self, attrs: ~[Attribute]) -> @foreign_item {
let lo = self.span.lo;
let vis = self.parse_visibility();
let vis = self.parse_non_priv_visibility();
// Parse obsolete purity.
let purity = self.parse_fn_purity();
@ -4443,7 +4455,7 @@ impl Parser {
maybe_whole!(iovi self, nt_item);
let lo = self.span.lo;
let visibility = self.parse_visibility();
let visibility = self.parse_non_priv_visibility();
// must be a view item:
if self.eat_keyword(keywords::Use) {
@ -4575,7 +4587,7 @@ impl Parser {
maybe_whole!(iovi self, nt_item);
let lo = self.span.lo;
let visibility = self.parse_visibility();
let visibility = self.parse_non_priv_visibility();
if (self.is_keyword(keywords::Const) || self.is_keyword(keywords::Static)) {
// FOREIGN CONST ITEM

View File

@ -17,7 +17,7 @@ pub mod kitties {
}
impl cat {
priv fn nap(&self) {}
fn nap(&self) {}
}
pub fn cat(in_x : uint, in_y : int) -> cat {

View File

@ -0,0 +1,31 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[crate_type = "lib"];
// used by the rpass test
pub struct Struct;
pub enum Unit {
Unit,
Argument(Struct)
}
// used by the cfail test
pub struct StructWithFields {
foo: int,
}
pub enum EnumWithVariants {
EnumVariant,
EnumVariantArg(int)
}

View File

@ -53,24 +53,21 @@ fn descending<M: MutableMap<uint, uint>>(map: &mut M, n_keys: uint) {
io::println(" Descending integers:");
do timed("insert") {
do uint::range_rev(n_keys, 0) |i| {
for i in range(0, n_keys).invert() {
map.insert(i, i + 1);
true
};
}
}
do timed("search") {
do uint::range_rev(n_keys, 0) |i| {
for i in range(0, n_keys).invert() {
assert_eq!(map.find(&i).unwrap(), &(i + 1));
true
};
}
}
do timed("remove") {
do uint::range_rev(n_keys, 0) |i| {
for i in range(0, n_keys) {
assert!(map.remove(&i));
true
};
}
}
}

View File

@ -16,7 +16,7 @@ mod my_mod {
MyStruct {priv_field: 4}
}
impl MyStruct {
priv fn happyfun(&self) {}
fn happyfun(&self) {}
}
}

View File

@ -12,8 +12,8 @@ use zoo::fly; //~ ERROR failed to resolve import
//~^ ERROR unresolved import: found `fly` in `zoo` but it is private
mod zoo {
priv type fly = ();
priv fn fly() {}
type fly = ();
fn fly() {}
}

View File

@ -12,7 +12,7 @@ use zoo::fly; //~ ERROR failed to resolve import
//~^ ERROR unresolved import: found `fly` in `zoo` but it is private
mod zoo {
priv fn fly() {}
fn fly() {}
}

View File

@ -14,7 +14,7 @@ mod a {
}
impl Foo {
priv fn foo(&self) {}
fn foo(&self) {}
}
}

View File

@ -9,7 +9,7 @@
// except according to those terms.
mod a {
priv fn f() {}
fn f() {}
}
fn main() {

View File

@ -18,7 +18,7 @@ mod kitties {
}
impl cat {
priv fn nap(&self) {}
fn nap(&self) {}
}
pub fn cat(in_x : uint, in_y : int) -> cat {

View File

@ -0,0 +1,21 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:xcrate_unit_struct.rs
// Make sure that when we have cross-crate unit structs we don't accidentally
// make values out of cross-crate structs that aren't unit.
extern mod xcrate_unit_struct;
fn main() {
let _ = xcrate_unit_struct::StructWithFields; //~ ERROR: unresolved name
let _ = xcrate_unit_struct::Struct;
}

Binary file not shown.

View File

@ -21,7 +21,7 @@ struct dog {
}
impl dog {
priv fn bark(&self) -> int {
fn bark(&self) -> int {
info!("Woof %u %d", *self.barks, *self.volume);
*self.barks += 1u;
if *self.barks % 3u == 0u {

View File

@ -20,11 +20,11 @@ fn int_range(lo: int, hi: int, it: &fn(int) -> bool) -> bool {
}
fn uint_range_rev(hi: uint, lo: uint, it: &fn(uint) -> bool) -> bool {
uint::range_rev(hi, lo, it)
range(lo, hi).invert().advance(it)
}
fn int_range_rev(hi: int, lo: int, it: &fn(int) -> bool) -> bool {
int::range_rev(hi, lo, it)
range(lo, hi).invert().advance(it)
}
fn int_range_step(a: int, b: int, step: int, it: &fn(int) -> bool) -> bool {

View File

@ -0,0 +1,35 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:xcrate_unit_struct.rs
// xfail-fast
extern mod xcrate_unit_struct;
use std::util;
static s1: xcrate_unit_struct::Struct = xcrate_unit_struct::Struct;
static s2: xcrate_unit_struct::Unit = xcrate_unit_struct::Unit;
static s3: xcrate_unit_struct::Unit =
xcrate_unit_struct::Argument(xcrate_unit_struct::Struct);
static s4: xcrate_unit_struct::Unit = xcrate_unit_struct::Argument(s1);
fn f1(_: xcrate_unit_struct::Struct) {}
fn f2(_: xcrate_unit_struct::Unit) {}
fn main() {
f1(xcrate_unit_struct::Struct);
f2(xcrate_unit_struct::Unit);
f2(xcrate_unit_struct::Argument(xcrate_unit_struct::Struct));
f1(s1);
f2(s2);
f2(s3);
f2(s4);
}