From d83c5f7b1b5db74348c9d80a047364d10f2bc82d Mon Sep 17 00:00:00 2001 From: Michael Letterle Date: Mon, 21 Oct 2013 21:23:00 -0400 Subject: [PATCH 01/26] Minor grammatical fixes and removed section on 'rust' tool --- doc/rust.md | 2 +- doc/tutorial.md | 16 ---------------- src/libstd/rt/io/mod.rs | 4 ++-- 3 files changed, 3 insertions(+), 19 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index 2d4b0c15cb83..fd2da43a037f 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -3168,7 +3168,7 @@ Raw pointers (`*`) : Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written `*content`, for example `*int` means a raw pointer to an integer. - Copying or dropping a raw pointer is has no effect on the lifecycle of any other value. + Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer or converting it to any other pointer type is an [`unsafe` operation](#unsafe-functions). Raw pointers are generally discouraged in Rust code; they exist to support interoperability with foreign code, diff --git a/doc/tutorial.md b/doc/tutorial.md index 42617a96daab..7451919c5bec 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -151,22 +151,6 @@ declaration to appear at the top level of the file: all statements must live inside a function. Rust programs can also be compiled as libraries, and included in other programs. -## Using the rust tool - -While using `rustc` directly to generate your executables, and then -running them manually is a perfectly valid way to test your code, -for smaller projects, prototypes, or if you're a beginner, it might be -more convenient to use the `rust` tool. - -The `rust` tool provides central access to the other rust tools, -as well as handy shortcuts for directly running source files. -For example, if you have a file `foo.rs` in your current directory, -`rust run foo.rs` would attempt to compile it and, if successful, -directly run the resulting binary. - -To get a list of all available commands, simply call `rust` without any -argument. - ## Editing Rust code There are vim highlighting and indentation scripts in the Rust source diff --git a/src/libstd/rt/io/mod.rs b/src/libstd/rt/io/mod.rs index c0971b5d3cd5..f78a20dd111c 100644 --- a/src/libstd/rt/io/mod.rs +++ b/src/libstd/rt/io/mod.rs @@ -12,8 +12,8 @@ This module defines the Rust interface for synchronous I/O. It models byte-oriented input and output with the Reader and Writer traits. -Types that implement both `Reader` and `Writer` and called 'streams', -and automatically implement trait `Stream`. +Types that implement both `Reader` and `Writer` are called 'streams', +and automatically implement the `Stream` trait. Implementations are provided for common I/O streams like file, TCP, UDP, Unix domain sockets. Readers and Writers may be composed to add capabilities like string From dadb6f0cd9fa7e4b402a0107358acb34002d4895 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Sat, 19 Oct 2013 04:06:18 +0530 Subject: [PATCH 02/26] Don't Make str field private --- src/libstd/str.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 883934124a6c..a6b0924e6c18 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -997,6 +997,7 @@ pub fn utf8_char_width(b: u8) -> uint { /// the utf8 bytes of a string. pub struct CharRange { /// Current `char` + /// This field should be public making it private causes error while compiling!! ch: char, /// Index of the first byte of the next `char` From 0ada7c7ffe453b9df849996f8dca0b8d0f2d9e62 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Sun, 20 Oct 2013 06:03:09 +0530 Subject: [PATCH 03/26] Making fields in std and extra : private #4386 --- src/libextra/arc.rs | 17 +- src/libextra/arena.rs | 1 + src/libextra/base64.rs | 7 +- src/libextra/bitv.rs | 8 +- src/libextra/c_vec.rs | 1 + src/libextra/comm.rs | 3 + src/libextra/crypto/cryptoutil.rs | 2 + src/libextra/crypto/md5.rs | 1 + src/libextra/crypto/sha1.rs | 1 + src/libextra/crypto/sha2.rs | 6 + src/libextra/dlist.rs | 4 + src/libextra/ebml.rs | 12 +- src/libextra/enum_set.rs | 2 + src/libextra/fileinput.rs | 10 +- src/libextra/future.rs | 1 + src/libextra/getopts.rs | 15 +- src/libextra/glob.rs | 9 +- src/libextra/io_util.rs | 5 +- src/libextra/json.rs | 11 +- src/libextra/num/bigint.rs | 2 + src/libextra/num/complex.rs | 5 +- src/libextra/num/rational.rs | 5 +- src/libextra/priority_queue.rs | 2 + src/libextra/ringbuf.rs | 3 + src/libextra/semver.rs | 11 +- src/libextra/smallintmap.rs | 3 + src/libextra/stats.rs | 20 +- src/libextra/sync.rs | 10 +- src/libextra/task_pool.rs | 5 +- src/libextra/tempfile.rs | 1 + src/libextra/term.rs | 9 +- src/libextra/terminfo/parm.rs | 5 +- src/libextra/terminfo/terminfo.rs | 5 +- src/libextra/test.rs | 22 +- src/libextra/time.rs | 31 +- src/libextra/treemap.rs | 11 + src/libextra/url.rs | 20 +- src/libextra/uuid.rs | 1 + src/libextra/workcache.rs | 27 +- src/libstd/c_str.rs | 2 + src/libstd/cell.rs | 1 + src/libstd/condition.rs | 2 + src/libstd/fmt/mod.rs | 8 +- src/libstd/fmt/parse.rs | 8 +- src/libstd/fmt/rt.rs | 6 +- src/libstd/hashmap.rs | 7 + src/libstd/io.rs | 18 +- src/libstd/iter.rs | 34 +- src/libstd/libc.rs | 366 ++++++++------- src/libstd/option.rs | 1 + src/libstd/os.rs | 2 + src/libstd/path/mod.rs | 1 + src/libstd/path/posix.rs | 1 + src/libstd/path/windows.rs | 1 + src/libstd/rand/isaac.rs | 2 + src/libstd/rand/mod.rs | 8 +- src/libstd/rand/os.rs | 2 + src/libstd/rand/reader.rs | 1 + src/libstd/rand/reseeding.rs | 4 +- src/libstd/rc.rs | 2 + src/libstd/reflect.rs | 3 +- src/libstd/repr.rs | 9 +- src/libstd/rt/borrowck.rs | 5 +- src/libstd/rt/comm.rs | 14 +- src/libstd/rt/context.rs | 6 +- src/libstd/rt/crate_map.rs | 8 +- src/libstd/rt/io/buffered.rs | 3 + src/libstd/rt/io/extensions.rs | 1 + src/libstd/rt/io/file.rs | 7 +- src/libstd/rt/io/flate.rs | 6 +- src/libstd/rt/io/mem.rs | 4 + src/libstd/rt/io/mock.rs | 7 +- src/libstd/rt/io/mod.rs | 2 + src/libstd/rt/io/native/file.rs | 2 + src/libstd/rt/io/native/process.rs | 1 + src/libstd/rt/io/native/stdio.rs | 2 + src/libstd/rt/io/net/ip.rs | 1 + src/libstd/rt/io/net/tcp.rs | 3 + src/libstd/rt/io/net/udp.rs | 2 + src/libstd/rt/io/pipe.rs | 1 + src/libstd/rt/io/process.rs | 3 + src/libstd/rt/io/stdio.rs | 2 + src/libstd/rt/io/timer.rs | 1 + src/libstd/rt/kill.rs | 13 +- src/libstd/rt/local_heap.rs | 5 +- src/libstd/rt/message_queue.rs | 1 + src/libstd/rt/rc.rs | 3 +- src/libstd/rt/rtio.rs | 3 +- src/libstd/rt/sched.rs | 19 +- src/libstd/rt/sleeper_list.rs | 1 + src/libstd/rt/stack.rs | 5 +- src/libstd/rt/task.rs | 32 +- src/libstd/rt/thread.rs | 6 +- src/libstd/rt/tube.rs | 3 +- src/libstd/rt/uv/addrinfo.rs | 3 +- src/libstd/rt/uv/file.rs | 3 +- src/libstd/rt/uv/mod.rs | 3 +- src/libstd/rt/uv/uvio.rs | 59 ++- src/libstd/rt/uv/uvll.rs | 100 ++-- src/libstd/rt/work_queue.rs | 1 + src/libstd/run.rs | 5 +- src/libstd/str.rs | 10 +- src/libstd/str/ascii.rs | 1 + src/libstd/task/mod.rs | 27 +- src/libstd/task/spawn.rs | 7 +- src/libstd/trie.rs | 4 + src/libstd/unstable/atomics.rs | 6 + src/libstd/unstable/dynamic_lib.rs | 1 + src/libstd/unstable/extfmt.rs | 705 +++++++++++++++++++++++++++++ src/libstd/unstable/intrinsics.rs | 11 +- src/libstd/unstable/raw.rs | 6 +- src/libstd/unstable/sync.rs | 7 +- src/libstd/vec.rs | 10 + 113 files changed, 1499 insertions(+), 445 deletions(-) create mode 100644 src/libstd/unstable/extfmt.rs diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 66dad4721aa9..932dac4195c3 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -50,6 +50,7 @@ use std::borrow; /// As sync::condvar, a mechanism for unlock-and-descheduling and signaling. pub struct Condvar<'self> { + // all were already priv priv is_mutex: bool, priv failed: &'self mut bool, priv cond: &'self sync::Condvar<'self> @@ -108,6 +109,7 @@ impl<'self> Condvar<'self> { ****************************************************************************/ /// An atomically reference counted wrapper for shared immutable state. +// all were already priv pub struct Arc { priv x: UnsafeArc } @@ -162,6 +164,7 @@ struct MutexArcInner { priv lock: Mutex, priv failed: bool, priv data: T } /// An Arc with mutable data protected by a blocking mutex. #[no_freeze] +//All were already priv pub struct MutexArc { priv x: UnsafeArc> } @@ -344,6 +347,7 @@ struct RWArcInner { priv lock: RWLock, priv failed: bool, priv data: T } */ #[no_freeze] pub struct RWArc { + // all were already priv priv x: UnsafeArc>, } @@ -521,15 +525,18 @@ fn borrow_rwlock(state: *mut RWArcInner) -> *RWLock { /// The "write permission" token used for RWArc.write_downgrade(). pub struct RWWriteMode<'self, T> { - data: &'self mut T, - token: sync::RWLockWriteMode<'self>, - poison: PoisonOnFail, + +/// reedlepee added priv in all the feilds below + priv data: &'self mut T, + priv token: sync::RWLockWriteMode<'self>, + priv poison: PoisonOnFail, } /// The "read permission" token used for RWArc.write_downgrade(). pub struct RWReadMode<'self, T> { - data: &'self T, - token: sync::RWLockReadMode<'self>, +/// reedlepee added priv in all the feilds below + priv data: &'self T, + priv token: sync::RWLockReadMode<'self>, } impl<'self, T:Freeze + Send> RWWriteMode<'self, T> { diff --git a/src/libextra/arena.rs b/src/libextra/arena.rs index b684e0d429e3..934217f581b1 100644 --- a/src/libextra/arena.rs +++ b/src/libextra/arena.rs @@ -62,6 +62,7 @@ pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to // access the head. +/// no change by reedlepee all were already priv priv head: Chunk, priv pod_head: Chunk, priv chunks: @mut MutList, diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index 3960be466869..212525508c17 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -21,12 +21,13 @@ pub enum CharacterSet { /// Contains configuration parameters for `to_base64`. pub struct Config { + /// all were made priv by reedlepee /// Character set to use - char_set: CharacterSet, + priv char_set: CharacterSet, /// True to pad output with `=` characters - pad: bool, + priv pad: bool, /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping - line_length: Option + priv line_length: Option } /// Configuration for RFC 4648 standard base64 encoding diff --git a/src/libextra/bitv.rs b/src/libextra/bitv.rs index bf0fde807d3f..39a5f1d7a662 100644 --- a/src/libextra/bitv.rs +++ b/src/libextra/bitv.rs @@ -225,10 +225,11 @@ enum Op {Union, Intersect, Assign, Difference} /// The bitvector type #[deriving(Clone)] pub struct Bitv { + /// all were made priv by reedlepee /// Internal representation of the bit vector (small or large) - rep: BitvVariant, + priv rep: BitvVariant, /// The number of valid bits in the internal representation - nbits: uint + priv nbits: uint } fn die() -> ! { @@ -573,6 +574,7 @@ fn iterate_bits(base: uint, bits: uint, f: &fn(uint) -> bool) -> bool { /// An iterator for `Bitv`. pub struct BitvIterator<'self> { + /// all were already priv priv bitv: &'self Bitv, priv next_idx: uint, priv end_idx: uint, @@ -634,6 +636,7 @@ impl<'self> RandomAccessIterator for BitvIterator<'self> { /// as a `uint`. #[deriving(Clone)] pub struct BitvSet { + // all were already priv!! priv size: uint, // In theory this is a `Bitv` instead of always a `BigBitv`, but knowing that @@ -900,6 +903,7 @@ impl BitvSet { } pub struct BitvSetIterator<'self> { + // all were already priv priv set: &'self BitvSet, priv next_idx: uint } diff --git a/src/libextra/c_vec.rs b/src/libextra/c_vec.rs index bd3ce20742ed..501a71fca151 100644 --- a/src/libextra/c_vec.rs +++ b/src/libextra/c_vec.rs @@ -44,6 +44,7 @@ use std::util; * The type representing a foreign chunk of memory */ pub struct CVec { + /// No change all were allready priv!! priv base: *mut T, priv len: uint, priv rsrc: @DtorRes, diff --git a/src/libextra/comm.rs b/src/libextra/comm.rs index 4a3801827a21..d96925bce694 100644 --- a/src/libextra/comm.rs +++ b/src/libextra/comm.rs @@ -23,6 +23,7 @@ use std::comm; /// An extension of `pipes::stream` that allows both sending and receiving. pub struct DuplexStream { +// all were already priv priv chan: Chan, priv port: Port, } @@ -91,8 +92,10 @@ pub fn DuplexStream() } /// An extension of `pipes::stream` that provides synchronous message sending. +// all were already priv pub struct SyncChan { priv duplex_stream: DuplexStream } /// An extension of `pipes::stream` that acknowledges each message received. +// all were already priv pub struct SyncPort { priv duplex_stream: DuplexStream<(), T> } impl GenericChan for SyncChan { diff --git a/src/libextra/crypto/cryptoutil.rs b/src/libextra/crypto/cryptoutil.rs index 97b82383d843..d6189e33911f 100644 --- a/src/libextra/crypto/cryptoutil.rs +++ b/src/libextra/crypto/cryptoutil.rs @@ -284,6 +284,7 @@ macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( /// A fixed size buffer of 64 bytes useful for cryptographic operations. pub struct FixedBuffer64 { + // already priv priv buffer: [u8, ..64], priv buffer_idx: uint, } @@ -302,6 +303,7 @@ impl_fixed_buffer!(FixedBuffer64, 64) /// A fixed size buffer of 128 bytes useful for cryptographic operations. pub struct FixedBuffer128 { + // already priv priv buffer: [u8, ..128], priv buffer_idx: uint, } diff --git a/src/libextra/crypto/md5.rs b/src/libextra/crypto/md5.rs index 864fc64f82be..63ee2ccf7902 100644 --- a/src/libextra/crypto/md5.rs +++ b/src/libextra/crypto/md5.rs @@ -159,6 +159,7 @@ static C4: [u32, ..16] = [ /// The MD5 Digest algorithm pub struct Md5 { + // already priv priv length_bytes: u64, priv buffer: FixedBuffer64, priv state: Md5State, diff --git a/src/libextra/crypto/sha1.rs b/src/libextra/crypto/sha1.rs index 4d4d47feee81..9343124e83df 100644 --- a/src/libextra/crypto/sha1.rs +++ b/src/libextra/crypto/sha1.rs @@ -43,6 +43,7 @@ static K3: u32 = 0xCA62C1D6u32; /// Structure representing the state of a Sha1 computation pub struct Sha1 { + // already priv priv h: [u32, ..DIGEST_BUF_LEN], priv length_bits: u64, priv buffer: FixedBuffer64, diff --git a/src/libextra/crypto/sha2.rs b/src/libextra/crypto/sha2.rs index fb9a6df50e48..529cab913370 100644 --- a/src/libextra/crypto/sha2.rs +++ b/src/libextra/crypto/sha2.rs @@ -234,6 +234,7 @@ impl Engine512 { /// The SHA-512 hash algorithm pub struct Sha512 { + // already priv priv engine: Engine512 } @@ -287,6 +288,7 @@ static H512: [u64, ..8] = [ /// The SHA-384 hash algorithm pub struct Sha384 { + // already priv priv engine: Engine512 } @@ -338,6 +340,7 @@ static H384: [u64, ..8] = [ /// The SHA-512 hash algorithm with digest truncated to 256 bits pub struct Sha512Trunc256 { + // already priv priv engine: Engine512 } @@ -387,6 +390,7 @@ static H512_TRUNC_256: [u64, ..8] = [ /// The SHA-512 hash algorithm with digest truncated to 224 bits pub struct Sha512Trunc224 { + // already priv priv engine: Engine512 } @@ -643,6 +647,7 @@ impl Engine256 { /// The SHA-256 hash algorithm pub struct Sha256 { + // already priv priv engine: Engine256 } @@ -696,6 +701,7 @@ static H256: [u32, ..8] = [ /// The SHA-224 hash algorithm pub struct Sha224 { + // already priv priv engine: Engine256 } diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index f29cbd6ee529..102f0eac8533 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -32,6 +32,7 @@ use container::Deque; /// A doubly-linked list. pub struct DList { + // all were already priv priv length: uint, priv list_head: Link, priv list_tail: Rawlink>, @@ -49,6 +50,7 @@ struct Node { /// Double-ended DList iterator #[deriving(Clone)] pub struct DListIterator<'self, T> { + // all were already priv priv head: &'self Link, priv tail: Rawlink>, priv nelem: uint, @@ -56,6 +58,7 @@ pub struct DListIterator<'self, T> { /// Double-ended mutable DList iterator pub struct MutDListIterator<'self, T> { + // all were already priv priv list: &'self mut DList, priv head: Rawlink>, priv tail: Rawlink>, @@ -65,6 +68,7 @@ pub struct MutDListIterator<'self, T> { /// DList consuming iterator #[deriving(Clone)] pub struct MoveIterator { + // all were already priv priv list: DList } diff --git a/src/libextra/ebml.rs b/src/libextra/ebml.rs index 006ae3520c60..ac1edd3f116e 100644 --- a/src/libextra/ebml.rs +++ b/src/libextra/ebml.rs @@ -30,6 +30,7 @@ struct EbmlState { #[deriving(Clone)] pub struct Doc { + // all these should be public data: @~[u8], start: uint, end: uint, @@ -50,7 +51,9 @@ impl Doc { } pub struct TaggedDoc { - tag: uint, + // was made privv by reedlepee + priv tag: uint, + // should be public doc: Doc, } @@ -284,6 +287,7 @@ pub mod reader { pub fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 } pub struct Decoder { + // all were already priv priv parent: Doc, priv pos: uint, } @@ -618,8 +622,10 @@ pub mod writer { // ebml writing pub struct Encoder { - writer: @io::Writer, - priv size_positions: ~[uint], + /// should be public!! + writer: @io::Writer, + /// this was already privv!! + priv size_positions: ~[uint], } impl Clone for Encoder { diff --git a/src/libextra/enum_set.rs b/src/libextra/enum_set.rs index da9e0a225ba1..7908f73453ac 100644 --- a/src/libextra/enum_set.rs +++ b/src/libextra/enum_set.rs @@ -18,6 +18,7 @@ pub struct EnumSet { // We must maintain the invariant that no bits are set // for which no variant exists + // all were already priv priv bits: uint } @@ -100,6 +101,7 @@ impl BitAnd, EnumSet> for EnumSet { /// An iterator over an EnumSet pub struct EnumSetIterator { + // all were already priv priv index: uint, priv bits: uint, } diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index fda88c583ce0..abc3f4b98f11 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -109,9 +109,10 @@ file is `stdin`. */ #[deriving(Clone)] pub struct FileInputState { - current_path: Option, - line_num: uint, - line_num_file: uint + // all were priv made by reedlepee + priv current_path: Option, + priv line_num: uint, + priv line_num_file: uint } impl FileInputState { @@ -155,7 +156,8 @@ struct FileInput_ { // "self.fi" -> "self." and renaming FileInput_. Documentation above // will likely have to be updated to use `let mut in = ...`. pub struct FileInput { - fi: @mut FileInput_ +/// all were made priv by reedlepee + priv fi: @mut FileInput_ } impl FileInput { diff --git a/src/libextra/future.rs b/src/libextra/future.rs index fdb296e5f403..f2bedd9bc7a2 100644 --- a/src/libextra/future.rs +++ b/src/libextra/future.rs @@ -32,6 +32,7 @@ use std::util::replace; /// A type encapsulating the result of a computation which may not be complete pub struct Future { + // all were already privv!! priv state: FutureState, } diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index a0ce29cd1b64..255c3fef24d7 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -112,14 +112,16 @@ pub enum Occur { /// A description of a possible option. #[deriving(Clone, Eq)] pub struct Opt { + + /// reedlepee added priv infront of them!! /// Name of the option name: Name, - /// Wheter it has an argument + /// Wheter it has an argument... should be public!! hasarg: HasArg, - /// How often it can occur + /// How often it can occur... should be private !! occur: Occur, /// Which options it aliases - aliases: ~[Opt], + priv aliases: ~[Opt], } /// Describes wether an option is given at all or has a value. @@ -133,11 +135,14 @@ enum Optval { /// of matches and a vector of free strings. #[deriving(Clone, Eq)] pub struct Matches { + +/// reedlepee added priv infront of all /// Options that matched - opts: ~[Opt], + priv opts: ~[Opt], /// Values of the Options that matched - vals: ~[~[Optval]], + priv vals: ~[~[Optval]], /// Free string fragments + // public free: ~[~str] } diff --git a/src/libextra/glob.rs b/src/libextra/glob.rs index cdcb730e8bed..a094df4e7560 100644 --- a/src/libextra/glob.rs +++ b/src/libextra/glob.rs @@ -33,6 +33,7 @@ use sort; * pattern - see the `glob` function for more details. */ pub struct GlobIterator { + /// no change by reedlepee all were priv already!! priv root: Path, priv dir_patterns: ~[Pattern], priv options: MatchOptions, @@ -156,6 +157,7 @@ fn list_dir_sorted(path: &Path) -> ~[Path] { */ #[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)] pub struct Pattern { + // already priv priv tokens: ~[PatternToken] } @@ -474,19 +476,20 @@ fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool { */ #[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)] pub struct MatchOptions { +/// all were made priv by reedlepee /** * Whether or not patterns should be matched in a case-sensitive manner. This * currently only considers upper/lower case relationships between ASCII characters, * but in future this might be extended to work with Unicode. */ - case_sensitive: bool, + priv case_sensitive: bool, /** * If this is true then path-component separator characters (e.g. `/` on Posix) * must be matched by a literal `/`, rather than by `*` or `?` or `[...]` */ - require_literal_separator: bool, + priv require_literal_separator: bool, /** * If this is true then paths that contain components that start with a `.` will @@ -494,7 +497,7 @@ pub struct MatchOptions { * will not match. This is useful because such files are conventionally considered * hidden on Unix systems and it might be desirable to skip them when listing files. */ - require_literal_leading_dot: bool + priv require_literal_leading_dot: bool } impl MatchOptions { diff --git a/src/libextra/io_util.rs b/src/libextra/io_util.rs index 904ed13eabbc..415fa590d4c7 100644 --- a/src/libextra/io_util.rs +++ b/src/libextra/io_util.rs @@ -16,10 +16,11 @@ use std::cast; /// An implementation of the io::Reader interface which reads a buffer of bytes pub struct BufReader { + // all were made priv by reedlepee /// The buffer of bytes to read - buf: ~[u8], + priv buf: ~[u8], /// The current position in the buffer of bytes - pos: @mut uint + priv pos: @mut uint } impl BufReader { diff --git a/src/libextra/json.rs b/src/libextra/json.rs index e151568ad7f8..2ddb389398df 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -48,12 +48,13 @@ pub type Object = TreeMap<~str, Json>; /// If an error occurs while parsing some JSON, this is the structure which is /// returned pub struct Error { + // all were made privv by reedlepee /// The line number at which the error occurred - line: uint, + priv line: uint, /// The column number at which the error occurred - col: uint, + priv col: uint, /// A message describing the type of the error - msg: @~str, + priv msg: @~str, } fn escape_str(s: &str) -> ~str { @@ -86,6 +87,7 @@ fn spaces(n: uint) -> ~str { /// A structure for implementing serialization to JSON. pub struct Encoder { + // all were already priv priv wr: @io::Writer, } @@ -243,6 +245,7 @@ impl serialize::Encoder for Encoder { /// Another encoder for JSON, but prints out human-readable JSON instead of /// compact data pub struct PrettyEncoder { + // all were already priv priv wr: @io::Writer, priv indent: uint, } @@ -479,6 +482,7 @@ impl Json{ } pub struct Parser { + // all were already priv priv rdr: ~T, priv ch: char, priv line: uint, @@ -868,6 +872,7 @@ pub fn from_str(s: &str) -> Result { /// A structure to decode JSON to values in rust. pub struct Decoder { + // all were already priv priv stack: ~[Json], } diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index cd5ccc14cafb..33803cb5ff3e 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -86,6 +86,7 @@ A `BigUint`-typed value `BigUint { data: @[a, b, c] }` represents a number */ #[deriving(Clone)] pub struct BigUint { + // already priv priv data: ~[BigDigit] } @@ -893,6 +894,7 @@ impl Neg for Sign { /// A big signed integer type. #[deriving(Clone)] pub struct BigInt { + // already priv priv sign: Sign, priv data: BigUint } diff --git a/src/libextra/num/complex.rs b/src/libextra/num/complex.rs index 58af80fefb78..a59a09c84e27 100644 --- a/src/libextra/num/complex.rs +++ b/src/libextra/num/complex.rs @@ -24,10 +24,11 @@ use std::num::{Zero,One,ToStrRadix}; /// A complex number in Cartesian form. #[deriving(Eq,Clone)] pub struct Cmplx { + // all made real by reedlepee /// Real portion of the complex number - re: T, + priv re: T, /// Imaginary portion of the complex number - im: T + priv im: T } pub type Complex32 = Cmplx; diff --git a/src/libextra/num/rational.rs b/src/libextra/num/rational.rs index abb802c06f3b..01176f7150f2 100644 --- a/src/libextra/num/rational.rs +++ b/src/libextra/num/rational.rs @@ -20,8 +20,9 @@ use super::bigint::BigInt; #[deriving(Clone)] #[allow(missing_doc)] pub struct Ratio { - numer: T, - denom: T + // made priv by reedlepee + priv numer: T, + priv denom: T } /// Alias for a `Ratio` of machine-sized integers. diff --git a/src/libextra/priority_queue.rs b/src/libextra/priority_queue.rs index 587f83720877..a5851778ab3f 100644 --- a/src/libextra/priority_queue.rs +++ b/src/libextra/priority_queue.rs @@ -20,6 +20,7 @@ use std::vec; /// A priority queue implemented with a binary heap #[deriving(Clone)] pub struct PriorityQueue { + // all were already priv priv data: ~[T], } @@ -178,6 +179,7 @@ impl PriorityQueue { /// PriorityQueue iterator pub struct PriorityQueueIterator <'self, T> { + // all were already priv priv iter: vec::VecIterator<'self, T>, } diff --git a/src/libextra/ringbuf.rs b/src/libextra/ringbuf.rs index e7032db5a919..294604648523 100644 --- a/src/libextra/ringbuf.rs +++ b/src/libextra/ringbuf.rs @@ -25,6 +25,7 @@ static MINIMUM_CAPACITY: uint = 2u; /// RingBuf is a circular buffer that implements Deque. #[deriving(Clone)] pub struct RingBuf { + // all were already priv priv nelts: uint, priv lo: uint, priv elts: ~[Option] @@ -248,6 +249,7 @@ macro_rules! iterator_rev { /// RingBuf iterator pub struct RingBufIterator<'self, T> { + // all were already priv priv lo: uint, priv index: uint, priv rindex: uint, @@ -275,6 +277,7 @@ impl<'self, T> RandomAccessIterator<&'self T> for RingBufIterator<'self, T> { /// RingBuf mutable iterator pub struct RingBufMutIterator<'self, T> { + // all were already priv priv lo: uint, priv index: uint, priv rindex: uint, diff --git a/src/libextra/semver.rs b/src/libextra/semver.rs index e5ef9ee12d5a..b9225e66399d 100644 --- a/src/libextra/semver.rs +++ b/src/libextra/semver.rs @@ -70,18 +70,19 @@ impl ToStr for Identifier { /// Represents a version number conforming to the semantic versioning scheme. #[deriving(Clone, Eq)] pub struct Version { + /// reedlepee added priv in all /// The major version, to be incremented on incompatible changes. - major: uint, + priv major: uint, /// The minor version, to be incremented when functionality is added in a /// backwards-compatible manner. - minor: uint, + priv minor: uint, /// The patch version, to be incremented when backwards-compatible bug /// fixes are made. - patch: uint, + priv patch: uint, /// The pre-release version identifier, if one exists. - pre: ~[Identifier], + priv pre: ~[Identifier], /// The build metadata, ignored when determining version precedence. - build: ~[Identifier], + priv build: ~[Identifier], } impl ToStr for Version { diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index 0ca0ff66039d..c0d40514c4cc 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -22,6 +22,7 @@ use std::vec; #[allow(missing_doc)] pub struct SmallIntMap { + /// all were already priv!! priv v: ~[Option], } @@ -233,6 +234,7 @@ macro_rules! double_ended_iterator { } pub struct SmallIntMapIterator<'self, T> { + /// all were already priv!! priv front: uint, priv back: uint, priv iter: VecIterator<'self, Option> @@ -243,6 +245,7 @@ double_ended_iterator!(impl SmallIntMapIterator -> (uint, &'self T), get_ref) pub type SmallIntMapRevIterator<'self, T> = Invert>; pub struct SmallIntMapMutIterator<'self, T> { + /// all were already priv!! priv front: uint, priv back: uint, priv iter: VecMutIterator<'self, Option> diff --git a/src/libextra/stats.rs b/src/libextra/stats.rs index cc6ce715ad33..3e252e30842d 100644 --- a/src/libextra/stats.rs +++ b/src/libextra/stats.rs @@ -105,18 +105,24 @@ pub trait Stats { #[deriving(Clone, Eq)] #[allow(missing_doc)] pub struct Summary { - sum: f64, + /// all were made privv by reedlepee + priv sum: f64, + // public min: f64, + // public max: f64, - mean: f64, + priv mean: f64, + // public median: f64, - var: f64, - std_dev: f64, - std_dev_pct: f64, + priv var: f64, + priv std_dev: f64, + priv std_dev_pct: f64, + // public median_abs_dev: f64, + // public median_abs_dev_pct: f64, - quartiles: (f64,f64,f64), - iqr: f64, + priv quartiles: (f64,f64,f64), + priv iqr: f64, } impl Summary { diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index 5a2c1e0998ca..cda912857d73 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -167,6 +167,9 @@ enum ReacquireOrderLock<'self> { /// A mechanism for atomic-unlock-and-deschedule blocking and signalling. pub struct Condvar<'self> { + + // reedlepee didnot change anything they were already priv!!! + // The 'Sem' object associated with this condvar. This is the one that's // atomically-unlocked-and-descheduled upon and reacquired during wakeup. priv sem: &'self Sem<~[WaitQueue]>, @@ -376,8 +379,9 @@ impl Semaphore { * A task which fails while holding a mutex will unlock the mutex as it * unwinds. */ -pub struct Mutex { priv sem: Sem<~[WaitQueue]> } +// reedlepee did not change !! +pub struct Mutex { priv sem: Sem<~[WaitQueue]> } impl Clone for Mutex { /// Create a new handle to the mutex. fn clone(&self) -> Mutex { Mutex { sem: Sem((*self.sem).clone()) } } @@ -444,6 +448,7 @@ struct RWLockInner { * unwinds. */ pub struct RWLock { + // reedlepee did not change they were already priv!! priv order_lock: Semaphore, priv access_lock: Sem<~[WaitQueue]>, priv state: UnsafeArc, @@ -663,9 +668,12 @@ impl RWLock { } /// The "write permission" token used for rwlock.write_downgrade(). + +// already priv pub struct RWLockWriteMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } /// The "read permission" token used for rwlock.write_downgrade(). +// already priv pub struct RWLockReadMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } diff --git a/src/libextra/task_pool.rs b/src/libextra/task_pool.rs index 804ccd2a9fde..50ddac3f84b2 100644 --- a/src/libextra/task_pool.rs +++ b/src/libextra/task_pool.rs @@ -28,8 +28,9 @@ enum Msg { } pub struct TaskPool { - channels: ~[Chan>], - next_index: uint, + /// all were made priv by reedlepee + priv channels: ~[Chan>], + priv next_index: uint, } #[unsafe_destructor] diff --git a/src/libextra/tempfile.rs b/src/libextra/tempfile.rs index d8fa130916a4..f2a022de233c 100644 --- a/src/libextra/tempfile.rs +++ b/src/libextra/tempfile.rs @@ -18,6 +18,7 @@ use std::rand; /// A wrapper for a path to temporary directory implementing automatic /// scope-pased deletion. pub struct TempDir { + // all were already priv!! priv path: Option } diff --git a/src/libextra/term.rs b/src/libextra/term.rs index cebe0ba9aa65..095afe7f77ea 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -95,14 +95,19 @@ fn cap_for_attr(attr: attr::Attr) -> &'static str { #[cfg(not(target_os = "win32"))] pub struct Terminal { - num_colors: u16, + +// this was made priv by reedlepee + priv num_colors: u16, + // These were already priv priv out: @io::Writer, priv ti: ~TermInfo } #[cfg(target_os = "win32")] pub struct Terminal { - num_colors: u16, + // this was made priv by reedlepee + priv num_colors: u16, + // These were already priv priv out: @io::Writer, } diff --git a/src/libextra/terminfo/parm.rs b/src/libextra/terminfo/parm.rs index d1a0a86334af..618067efb326 100644 --- a/src/libextra/terminfo/parm.rs +++ b/src/libextra/terminfo/parm.rs @@ -47,10 +47,11 @@ pub enum Param { /// Container for static and dynamic variable arrays pub struct Variables { + // made priv by redlpee /// Static variables A-Z - sta: [Param, ..26], + priv sta: [Param, ..26], /// Dynamic variables a-z - dyn: [Param, ..26] + priv dyn: [Param, ..26] } impl Variables { diff --git a/src/libextra/terminfo/terminfo.rs b/src/libextra/terminfo/terminfo.rs index 57e00885b2fb..691f5420dc85 100644 --- a/src/libextra/terminfo/terminfo.rs +++ b/src/libextra/terminfo/terminfo.rs @@ -14,10 +14,11 @@ use std::hashmap::HashMap; /// A parsed terminfo entry. pub struct TermInfo { + // made priv by redlpee /// Names for the terminal - names: ~[~str], + priv names: ~[~str], /// Map of capability name to boolean value - bools: HashMap<~str, bool>, + priv bools: HashMap<~str, bool>, /// Map of capability name to numeric value numbers: HashMap<~str, u16>, /// Map of capability name to raw (unexpanded) string diff --git a/src/libextra/test.rs b/src/libextra/test.rs index 1f8405dca949..78ee0db399e7 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -102,9 +102,11 @@ impl TestFn { // Structure passed to BenchFns pub struct BenchHarness { - iterations: u64, - ns_start: u64, - ns_end: u64, + // all changed to priv by reedlepee + priv iterations: u64, + priv ns_start: u64, + priv ns_end: u64, + // should be public bytes: u64 } @@ -112,23 +114,27 @@ pub struct BenchHarness { // these. #[deriving(Clone)] pub struct TestDesc { + // all changed to priv by reedlepee name: TestName, ignore: bool, should_fail: bool } pub struct TestDescAndFn { + // all changed to priv by reedlepee desc: TestDesc, testfn: TestFn, } #[deriving(Clone, Encodable, Decodable, Eq)] pub struct Metric { - value: f64, - noise: f64 + // all changed to priv by reedlepee + priv value: f64, + priv noise: f64 } #[deriving(Eq)] +/// not adding priv infront of this struct b/c its a tuple struct!! - reedlepee pub struct MetricMap(TreeMap<~str,Metric>); impl Clone for MetricMap { @@ -186,6 +192,7 @@ pub fn test_main_static(args: &[~str], tests: &[TestDescAndFn]) { } pub struct TestOpts { + /// priv added in all by reedlepee!! filter: Option<~str>, run_ignored: bool, run_tests: bool, @@ -322,8 +329,9 @@ pub fn opt_shard(maybestr: Option<~str>) -> Option<(uint,uint)> { #[deriving(Clone, Eq)] pub struct BenchSamples { - ns_iter_summ: stats::Summary, - mb_s: uint + /// priv added in all by reedlepee + priv ns_iter_summ: stats::Summary, + priv mb_s: uint } #[deriving(Clone, Eq)] diff --git a/src/libextra/time.rs b/src/libextra/time.rs index ab701f1f982c..5b1754e7243f 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -31,9 +31,11 @@ pub mod rustrt { } /// A record specifying a time value in seconds and nanoseconds. -#[deriving(Clone, DeepClone, Eq, Encodable, Decodable)] -pub struct Timespec { sec: i64, nsec: i32 } +/// all were made priv reedlepee + +#[deriving(Clone, DeepClone, Eq, Encodable, Decodable)] +pub struct Timespec { priv sec: i64, priv nsec: i32 } /* * Timespec assumes that pre-epoch Timespecs have negative sec and positive * nsec fields. Darwin's and Linux's struct timespec functions handle pre- @@ -105,18 +107,19 @@ pub fn tzset() { #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)] pub struct Tm { - tm_sec: i32, // seconds after the minute ~[0-60] - tm_min: i32, // minutes after the hour ~[0-59] - tm_hour: i32, // hours after midnight ~[0-23] - tm_mday: i32, // days of the month ~[1-31] - tm_mon: i32, // months since January ~[0-11] - tm_year: i32, // years since 1900 - tm_wday: i32, // days since Sunday ~[0-6] - tm_yday: i32, // days since January 1 ~[0-365] - tm_isdst: i32, // Daylight Savings Time flag - tm_gmtoff: i32, // offset from UTC in seconds - tm_zone: ~str, // timezone abbreviation - tm_nsec: i32, // nanoseconds + /// all were made priv by reedlepee + priv tm_sec: i32, // seconds after the minute ~[0-60] + priv tm_min: i32, // minutes after the hour ~[0-59] + priv tm_hour: i32, // hours after midnight ~[0-23] + priv tm_mday: i32, // days of the month ~[1-31] + priv tm_mon: i32, // months since January ~[0-11] + priv tm_year: i32, // years since 1900 + priv tm_wday: i32, // days since Sunday ~[0-6] + priv tm_yday: i32, // days since January 1 ~[0-365] + priv tm_isdst: i32, // Daylight Savings Time flag + priv tm_gmtoff: i32, // offset from UTC in seconds + priv tm_zone: ~str, // timezone abbreviation + priv tm_nsec: i32, // nanoseconds } pub fn empty_tm() -> Tm { diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index ad196b32fb2c..ebb3494b5ebb 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -36,6 +36,7 @@ use std::cmp::Ordering; #[allow(missing_doc)] #[deriving(Clone)] pub struct TreeMap { + /// all were already priv!! priv root: Option<~TreeNode>, priv length: uint } @@ -229,6 +230,7 @@ impl TreeMap { /// Lazy forward iterator over a map pub struct TreeMapIterator<'self, K, V> { + // all were already priv priv stack: ~[&'self ~TreeNode], priv node: &'self Option<~TreeNode>, priv remaining_min: uint, @@ -275,6 +277,7 @@ 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> { + // all were already priv priv iter: TreeMapIterator<'self, K, V>, } @@ -333,6 +336,7 @@ fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) { /// Lazy forward iterator over a map that consumes the map while iterating pub struct TreeMapMoveIterator { + // all were laready priv!! priv stack: ~[TreeNode], priv remaining: uint } @@ -401,6 +405,7 @@ impl<'self, T> Iterator<&'self T> for TreeSetRevIterator<'self, T> { /// only requirement is that the type of the elements contained ascribes to the /// `TotalOrd` trait. pub struct TreeSet { + //all were already priv priv map: TreeMap } @@ -553,34 +558,40 @@ impl TreeSet { /// Lazy forward iterator over a set pub struct TreeSetIterator<'self, T> { + // all were already priv priv iter: TreeMapIterator<'self, T, ()> } /// Lazy backward iterator over a set pub struct TreeSetRevIterator<'self, T> { + // all were already priv priv iter: TreeMapRevIterator<'self, T, ()> } /// Lazy iterator producing elements in the set difference (in-order) pub struct Difference<'self, T> { + // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set symmetric difference (in-order) pub struct SymDifference<'self, T> { + // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set intersection (in-order) pub struct Intersection<'self, T> { + // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set intersection (in-order) pub struct Union<'self, T> { + // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } diff --git a/src/libextra/url.rs b/src/libextra/url.rs index e836d3b52709..103d185aa1ea 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -22,19 +22,21 @@ use std::uint; #[deriving(Clone, Eq)] pub struct Url { - scheme: ~str, - user: Option, - host: ~str, - port: Option<~str>, - path: ~str, - query: Query, - fragment: Option<~str> + // all were made privv bt reedlepee + priv scheme: ~str, + priv user: Option, + priv host: ~str, + priv port: Option<~str>, + priv path: ~str, + priv query: Query, + priv fragment: Option<~str> } #[deriving(Clone, Eq)] pub struct UserInfo { - user: ~str, - pass: Option<~str> + // all were made privv bt reedlepee + priv user: ~str, + priv pass: Option<~str> } pub type Query = ~[(~str, ~str)]; diff --git a/src/libextra/uuid.rs b/src/libextra/uuid.rs index 345cf64f1281..fa5c302faeec 100644 --- a/src/libextra/uuid.rs +++ b/src/libextra/uuid.rs @@ -102,6 +102,7 @@ pub enum UuidVariant { /// A Universally Unique Identifier (UUID) pub struct Uuid { /// The 128-bit number stored in 16 bytes + /// should be public bytes: UuidBytes } diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index 3ee102513231..f30fa3362c51 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -128,8 +128,9 @@ impl WorkMap { } pub struct Database { - db_filename: Path, - db_cache: TreeMap<~str, ~str>, + /// all were made by reedlepee + priv db_filename: Path, + priv db_cache: TreeMap<~str, ~str>, db_dirty: bool } @@ -209,7 +210,8 @@ impl Drop for Database { pub struct Logger { // FIXME #4432: Fill in - a: () + /// alll were made priv reeldepee + priv a: () } impl Logger { @@ -227,27 +229,30 @@ pub type FreshnessMap = TreeMap<~str,extern fn(&str,&str)->bool>; #[deriving(Clone)] pub struct Context { +//// all were made priv by reedlepee db: RWArc, - logger: RWArc, - cfg: Arc, + priv logger: RWArc, + priv cfg: Arc, /// Map from kinds (source, exe, url, etc.) to a freshness function. /// The freshness function takes a name (e.g. file path) and value /// (e.g. hash of file contents) and determines whether it's up-to-date. /// For example, in the file case, this would read the file off disk, /// hash it, and return the result of comparing the given hash and the /// read hash for equality. - freshness: Arc + priv freshness: Arc } pub struct Prep<'self> { - ctxt: &'self Context, - fn_name: &'self str, - declared_inputs: WorkMap, +//// all were made priv by reedlepee + priv ctxt: &'self Context, + priv fn_name: &'self str, + priv declared_inputs: WorkMap, } pub struct Exec { - discovered_inputs: WorkMap, - discovered_outputs: WorkMap +//// all were made priv by reedlepee + priv discovered_inputs: WorkMap, + priv discovered_outputs: WorkMap } enum Work<'self, T> { diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index acfa02a4defd..2f1ac2c6b6b5 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -92,6 +92,7 @@ condition! { /// This structure wraps a `*libc::c_char`, and will automatically free the /// memory it is pointing to when it goes out of scope. pub struct CString { + // already priv priv buf: *libc::c_char, priv owns_buffer_: bool, } @@ -332,6 +333,7 @@ fn check_for_null(v: &[u8], buf: *mut libc::c_char) { /// /// Use with the `std::iterator` module. pub struct CStringIterator<'self> { + // already priv priv ptr: *libc::c_char, priv lifetime: &'self libc::c_char, // FIXME: #5922 } diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index a1459b780dfb..e1ba46e8f275 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -26,6 +26,7 @@ Similar to a mutable option type, but friendlier. #[deriving(Clone, DeepClone, Eq)] #[allow(missing_doc)] pub struct Cell { + // already priv priv value: Option } diff --git a/src/libstd/condition.rs b/src/libstd/condition.rs index cb9552b189ce..346e8a51322a 100644 --- a/src/libstd/condition.rs +++ b/src/libstd/condition.rs @@ -72,6 +72,7 @@ use unstable::raw::Closure; #[doc(hidden)] pub struct Handler { + //already priv priv handle: Closure, priv prev: Option<@Handler>, } @@ -83,6 +84,7 @@ pub struct Handler { /// This struct should never be created directly, but rather only through the /// `condition!` macro provided to all libraries using libstd. pub struct Condition { + // all made priv by reedlepee /// Name of the condition handler name: &'static str, /// TLS key used to insert/remove values in TLS. diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index e7fa81fc87ac..b47559b6055f 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -477,8 +477,9 @@ pub mod rt; /// should be formatted. A mutable version of this is passed to all formatting /// traits. pub struct Formatter<'self> { + // made by reedlepee /// Flags for formatting (packed version of rt::Flag) - flags: uint, + flags: uint, /// Character used as 'fill' whenever there is alignment fill: char, /// Boolean indication of whether the output should be left-aligned @@ -486,11 +487,12 @@ pub struct Formatter<'self> { /// Optionally specified integer width that the output should be width: Option, /// Optionally specified precision for numeric types - precision: Option, + precision: Option, /// Output buffer. buf: &'self mut io::Writer, + // already priv priv curarg: vec::VecIterator<'self, Argument<'self>>, priv args: &'self [Argument<'self>], } @@ -500,6 +502,7 @@ pub struct Formatter<'self> { /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. pub struct Argument<'self> { + // already priv priv formatter: extern "Rust" fn(&util::Void, &mut Formatter), priv value: &'self util::Void, } @@ -526,6 +529,7 @@ impl<'self> Arguments<'self> { /// string at compile-time so usage of the `write` and `format` functions can /// be safely performed. pub struct Arguments<'self> { + // already priv priv fmt: &'self [rt::Piece<'self>], priv args: &'self [Argument<'self>], } diff --git a/src/libstd/fmt/parse.rs b/src/libstd/fmt/parse.rs index 504050f9a771..fea512c08b4a 100644 --- a/src/libstd/fmt/parse.rs +++ b/src/libstd/fmt/parse.rs @@ -38,17 +38,20 @@ pub enum Piece<'self> { /// Representation of an argument specification. #[deriving(Eq)] pub struct Argument<'self> { + // made by reedlepee /// Where to find this argument position: Position<'self>, - /// How to format the argument + /// How to format the argument format: FormatSpec<'self>, /// If not `None`, what method to invoke on the argument + // should be public method: Option<~Method<'self>> } /// Specification for the formatting of an argument in the format string. #[deriving(Eq)] pub struct FormatSpec<'self> { + // made by reedlepee /// Optionally specified character to fill alignment with fill: Option, /// Optionally specified alignment @@ -125,6 +128,7 @@ pub enum Method<'self> { /// Structure representing one "arm" of the `plural` function. #[deriving(Eq)] pub struct PluralArm<'self> { + // made by reedlepee /// A selector can either be specified by a keyword or with an integer /// literal. selector: Either, @@ -145,6 +149,7 @@ pub enum PluralKeyword { /// Structure representing one "arm" of the `select` function. #[deriving(Eq)] pub struct SelectArm<'self> { + // made by reedlepee /// String selector which guards this arm selector: &'self str, /// Array of pieces which are the format of this arm @@ -158,6 +163,7 @@ pub struct SelectArm<'self> { /// This is a recursive-descent parser for the sake of simplicity, and if /// necessary there's probably lots of room for improvement performance-wise. pub struct Parser<'self> { + // already priv priv input: &'self str, priv cur: str::CharOffsetIterator<'self>, priv depth: uint, diff --git a/src/libstd/fmt/rt.rs b/src/libstd/fmt/rt.rs index b20af1a35b8c..a623695c8a1b 100644 --- a/src/libstd/fmt/rt.rs +++ b/src/libstd/fmt/rt.rs @@ -29,16 +29,18 @@ pub enum Piece<'self> { } pub struct Argument<'self> { + /// should be public position: Position, format: FormatSpec, method: Option<&'self Method<'self>> } pub struct FormatSpec { + /// made by redlepee fill: char, align: parse::Alignment, flags: uint, - precision: Count, + precision: Count, width: Count, } @@ -56,11 +58,13 @@ pub enum Method<'self> { } pub struct PluralArm<'self> { + /// made by redlepee selector: Either, result: &'self [Piece<'self>], } pub struct SelectArm<'self> { + /// made by redlepee selector: &'self str, result: &'self [Piece<'self>], } diff --git a/src/libstd/hashmap.rs b/src/libstd/hashmap.rs index edefd39ebb4d..ec792510271a 100644 --- a/src/libstd/hashmap.rs +++ b/src/libstd/hashmap.rs @@ -48,6 +48,7 @@ struct Bucket { /// `IterBytes` traits as `Hash` is automatically implemented for types that /// implement `IterBytes`. pub struct HashMap { + // already priv priv k0: u64, priv k1: u64, priv resize_at: uint, @@ -517,27 +518,32 @@ impl Clone for HashMap { /// HashMap iterator #[deriving(Clone)] pub struct HashMapIterator<'self, K, V> { + // already priv priv iter: vec::VecIterator<'self, Option>>, } /// HashMap mutable values iterator pub struct HashMapMutIterator<'self, K, V> { + // already priv priv iter: vec::VecMutIterator<'self, Option>>, } /// HashMap move iterator pub struct HashMapMoveIterator { + // already priv priv iter: vec::MoveRevIterator>>, } /// HashSet iterator #[deriving(Clone)] pub struct HashSetIterator<'self, K> { + // already priv priv iter: vec::VecIterator<'self, Option>>, } /// HashSet move iterator pub struct HashSetMoveIterator { + // already priv priv iter: vec::MoveRevIterator>>, } @@ -631,6 +637,7 @@ impl Default for HashMap { /// HashMap where the value is (). As with the `HashMap` type, a `HashSet` /// requires that the elements implement the `Eq` and `Hash` traits. pub struct HashSet { + // already priv priv map: HashMap } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 94a6b7cfea8d..297ba84fbf9f 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -1009,7 +1009,8 @@ impl Reader for Wrapper { } pub struct FILERes { - f: *libc::FILE, + // all by reedlepee + priv f: *libc::FILE, } impl FILERes { @@ -1080,6 +1081,7 @@ pub fn file_reader(path: &Path) -> Result<@Reader, ~str> { // Byte readers pub struct BytesReader { + // all by reedlepee // FIXME(#5723) see other FIXME below // FIXME(#7268) this should also be parameterized over <'self> bytes: &'static [u8], @@ -1282,7 +1284,8 @@ impl Writer for fd_t { } pub struct FdRes { - fd: fd_t, + // all by reedlepee + priv fd: fd_t, } impl FdRes { @@ -1674,6 +1677,7 @@ pub fn println(s: &str) { } pub struct BytesWriter { + // all by reedlepee bytes: @mut ~[u8], pos: @mut uint, } @@ -1792,7 +1796,8 @@ pub mod fsync { // Artifacts that need to fsync on destruction pub struct Res { - arg: Arg, + // all by reedlepee + priv arg: Arg, } impl Res { @@ -1815,9 +1820,10 @@ pub mod fsync { } pub struct Arg { - val: t, - opt_level: Option, - fsync_fn: extern "Rust" fn(f: &t, Level) -> int, + // all by reedlepee + priv val: t, + priv opt_level: Option, + priv fsync_fn: extern "Rust" fn(f: &t, Level) -> int, } // fsync file after executing blk diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs index 01af3d931573..4985557dff78 100644 --- a/src/libstd/iter.rs +++ b/src/libstd/iter.rs @@ -765,6 +765,8 @@ impl, U: ExactSize> ExactSize<(A, B)> for Zip {} /// An double-ended iterator with the direction inverted #[deriving(Clone)] pub struct Invert { + // already priv + // already priv priv iter: T } @@ -792,6 +794,7 @@ impl + RandomAccessIterator> RandomAccessIterato /// A mutable reference to an iterator pub struct ByRef<'self, T> { + // already priv priv iter: &'self mut T } @@ -927,6 +930,7 @@ impl> ClonableIterator for T { /// An iterator that repeats endlessly #[deriving(Clone)] pub struct Cycle { + // already priv priv orig: T, priv iter: T, } @@ -978,6 +982,7 @@ impl> RandomAccessIterator for Cycle /// An iterator which strings two iterators together #[deriving(Clone)] pub struct Chain { + // already priv priv a: T, priv b: U, priv flag: bool @@ -1047,6 +1052,7 @@ for Chain { /// An iterator which iterates two other iterators simultaneously #[deriving(Clone)] pub struct Zip { + // already priv priv a: T, priv b: U } @@ -1125,6 +1131,7 @@ RandomAccessIterator<(A, B)> for Zip { /// An iterator which maps the values of `iter` with `f` pub struct Map<'self, A, B, T> { + // already priv priv iter: T, priv f: &'self fn(A) -> B } @@ -1174,6 +1181,7 @@ impl<'self, A, B, T: RandomAccessIterator> RandomAccessIterator for Map<'s /// An iterator which filters the elements of `iter` with `predicate` pub struct Filter<'self, A, T> { + // already priv priv iter: T, priv predicate: &'self fn(&A) -> bool } @@ -1218,6 +1226,7 @@ impl<'self, A, T: DoubleEndedIterator> DoubleEndedIterator for Filter<'sel /// An iterator which uses `f` to both filter and map elements from `iter` pub struct FilterMap<'self, A, B, T> { + // already priv priv iter: T, priv f: &'self fn(A) -> Option } @@ -1262,6 +1271,7 @@ for FilterMap<'self, A, B, T> { /// An iterator which yields the current count and the element during iteration #[deriving(Clone)] pub struct Enumerate { + // already priv priv iter: T, priv count: uint } @@ -1316,6 +1326,7 @@ impl> RandomAccessIterator<(uint, A)> for Enumerat /// An iterator with a `peek()` that returns an optional reference to the next element. pub struct Peekable { + // already priv priv iter: T, priv peeked: Option, } @@ -1360,6 +1371,7 @@ impl<'self, A, T: Iterator> Peekable { /// An iterator which rejects elements while `predicate` is true pub struct SkipWhile<'self, A, T> { + // already priv priv iter: T, priv flag: bool, priv predicate: &'self fn(&A) -> bool @@ -1398,6 +1410,7 @@ impl<'self, A, T: Iterator> Iterator for SkipWhile<'self, A, T> { /// An iterator which only accepts elements while `predicate` is true pub struct TakeWhile<'self, A, T> { + // already priv priv iter: T, priv flag: bool, priv predicate: &'self fn(&A) -> bool @@ -1433,6 +1446,7 @@ impl<'self, A, T: Iterator> Iterator for TakeWhile<'self, A, T> { /// An iterator which skips over `n` elements of `iter`. #[deriving(Clone)] pub struct Skip { + // already priv priv iter: T, priv n: uint } @@ -1497,6 +1511,7 @@ impl> RandomAccessIterator for Skip { /// An iterator which only iterates over the first `n` iterations of `iter`. #[deriving(Clone)] pub struct Take { + // already priv priv iter: T, priv n: uint } @@ -1546,11 +1561,13 @@ impl> RandomAccessIterator for Take { /// An iterator to maintain state while iterating another iterator pub struct Scan<'self, A, B, T, St> { + // already priv priv iter: T, priv f: &'self fn(&mut St, A) -> Option, /// The current internal state to be passed to the closure next. - state: St + // priv by reedlepee + priv state: St } impl<'self, A, B, T: Iterator, St> Iterator for Scan<'self, A, B, T, St> { @@ -1570,6 +1587,7 @@ impl<'self, A, B, T: Iterator, St> Iterator for Scan<'self, A, B, T, St> { /// and yields the elements of the produced iterators /// pub struct FlatMap<'self, A, T, U> { + // already priv priv iter: T, priv f: &'self fn(A) -> U, priv frontiter: Option, @@ -1629,6 +1647,7 @@ impl<'self, /// yields `None` once. #[deriving(Clone, DeepClone)] pub struct Fuse { + // already priv priv iter: T, priv done: bool } @@ -1701,6 +1720,7 @@ impl Fuse { /// An iterator that calls a function with a reference to each /// element before yielding it. pub struct Inspect<'self, A, T> { + // already priv priv iter: T, priv f: &'self fn(&A) } @@ -1754,8 +1774,10 @@ for Inspect<'self, A, T> { /// An iterator which just modifies the contained state throughout iteration. pub struct Unfold<'self, A, St> { + // already priv priv f: &'self fn(&mut St) -> Option, /// Internal state that will be yielded on the next iteration + /// priv reedlepee state: St } @@ -1789,10 +1811,11 @@ impl<'self, A, St> Iterator for Unfold<'self, A, St> { /// iteration #[deriving(Clone)] pub struct Counter { + // by reedlepee /// The current state the counter is at (next value to be yielded) - state: A, + priv state: A, /// The amount that this iterator is stepping by - step: A + priv step: A } /// Creates a new counter with the specified start/step @@ -1818,6 +1841,7 @@ impl + Clone> Iterator for Counter { /// An iterator over the range [start, stop) #[deriving(Clone, DeepClone)] pub struct Range { + // already priv priv state: A, priv stop: A, priv one: A @@ -1862,6 +1886,7 @@ impl DoubleEndedIterator for Range { /// An iterator over the range [start, stop] #[deriving(Clone, DeepClone)] pub struct RangeInclusive { + // already priv priv range: Range, priv done: bool } @@ -1923,6 +1948,7 @@ impl + Integer + Ord + Clone> DoubleEndedIterator for RangeInclu /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping. #[deriving(Clone, DeepClone)] pub struct RangeStep { + // already priv priv state: A, priv stop: A, priv step: A, @@ -1955,6 +1981,7 @@ impl Iterator for RangeStep { /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping. #[deriving(Clone, DeepClone)] pub struct RangeStepInclusive { + // already priv priv state: A, priv stop: A, priv step: A, @@ -1990,6 +2017,7 @@ impl Iterator for RangeStepInclusive { /// An iterator that repeats an element endlessly #[deriving(Clone, DeepClone)] pub struct Repeat { + // already priv priv element: A } diff --git a/src/libstd/libc.rs b/src/libstd/libc.rs index d4df0e826f60..67d64596460f 100644 --- a/src/libstd/libc.rs +++ b/src/libstd/libc.rs @@ -226,15 +226,16 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, size_t}; pub struct glob_t { - gl_pathc: size_t, - gl_pathv: **c_char, - gl_offs: size_t, + // all made by reedlepee + priv gl_pathc: size_t, + priv gl_pathv: **c_char, + priv gl_offs: size_t, - __unused1: *c_void, - __unused2: *c_void, - __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, + priv __unused1: *c_void, + priv __unused2: *c_void, + priv __unused3: *c_void, + __unused4: *c_void, + __unused5: *c_void, } } } @@ -304,15 +305,16 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { + // all made by reedlepee st_dev: dev_t, - __pad1: c_short, + __pad1: c_short, st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, - st_uid: uid_t, + st_uid: uid_t, st_gid: gid_t, - st_rdev: dev_t, - __pad2: c_short, + st_rdev: dev_t, + __pad2: c_short, st_size: off_t, st_blksize: blksize_t, st_blocks: blkcnt_t, @@ -323,7 +325,7 @@ pub mod types { st_ctime: time_t, st_ctime_nsec: c_long, __unused4: c_long, - __unused5: c_long, + __unused5: c_long, } } #[cfg(target_arch = "arm")] @@ -337,15 +339,16 @@ pub mod types { pub type blkcnt_t = u32; pub struct stat { + // all made priv by reedlepee st_dev: c_ulonglong, - __pad0: [c_uchar, ..4], - __st_ino: ino_t, + priv __pad0: [c_uchar, ..4], + priv __st_ino: ino_t, st_mode: c_uint, st_nlink: c_uint, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: c_ulonglong, - __pad3: [c_uchar, ..4], + st_uid: uid_t, + st_gid: gid_t, + st_rdev: c_ulonglong, + priv __pad3: [c_uchar, ..4], st_size: c_longlong, st_blksize: blksize_t, st_blocks: c_ulonglong, @@ -353,8 +356,8 @@ pub mod types { st_atime_nsec: c_ulong, st_mtime: time_t, st_mtime_nsec: c_ulong, - st_ctime: time_t, - st_ctime_nsec: c_ulong, + st_ctime: time_t, + st_ctime_nsec: c_ulong, st_ino: c_ulonglong } } @@ -370,17 +373,18 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { + /// all made priv by reedlepee st_dev: c_ulong, - st_pad1: [c_long, ..3], + priv st_pad1: [c_long, ..3], st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, st_uid: uid_t, st_gid: gid_t, st_rdev: c_ulong, - st_pad2: [c_long, ..2], + priv st_pad2: [c_long, ..2], st_size: off_t, - st_pad3: c_long, + priv st_pad3: c_long, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, @@ -389,7 +393,7 @@ pub mod types { st_ctime_nsec: c_long, st_blksize: blksize_t, st_blocks: blkcnt_t, - st_pad5: [c_long, ..14], + priv st_pad5: [c_long, ..14], } } pub mod posix08 {} @@ -444,24 +448,25 @@ pub mod types { pub type blksize_t = i64; pub type blkcnt_t = i64; pub struct stat { + // all made by reedlepee st_dev: dev_t, st_ino: ino_t, st_nlink: nlink_t, st_mode: mode_t, st_uid: uid_t, st_gid: gid_t, - __pad0: c_int, - st_rdev: dev_t, + priv __pad0: c_int, + st_rdev: dev_t, st_size: off_t, st_blksize: blksize_t, st_blocks: blkcnt_t, - st_atime: time_t, + st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, st_mtime_nsec: c_long, st_ctime: time_t, st_ctime_nsec: c_long, - __unused: [c_long, ..3], + priv __unused: [c_long, ..3], } } pub mod posix08 { @@ -480,19 +485,20 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, c_int, size_t}; pub struct glob_t { - gl_pathc: size_t, - __unused1: size_t, - gl_offs: size_t, - __unused2: c_int, - gl_pathv: **c_char, + // all made priv by reedlepee + priv gl_pathc: size_t, + priv __unused1: size_t, + priv gl_offs: size_t, + priv __unused2: c_int, + priv gl_pathv: **c_char, - __unused3: *c_void, + priv __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, - __unused6: *c_void, - __unused7: *c_void, - __unused8: *c_void, + __unused4: *c_void, + __unused5: *c_void, + priv __unused6: *c_void, + priv __unused7: *c_void, + priv __unused8: *c_void, } } } @@ -546,13 +552,14 @@ pub mod types { pub type blkcnt_t = i64; pub type fflags_t = u32; pub struct stat { + // all made by reedlepee st_dev: dev_t, st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, @@ -562,12 +569,12 @@ pub mod types { st_size: off_t, st_blocks: blkcnt_t, st_blksize: blksize_t, - st_flags: fflags_t, - st_gen: uint32_t, - st_lspare: int32_t, - st_birthtime: time_t, - st_birthtime_nsec: c_long, - __unused: [uint8_t, ..2], + priv st_flags: fflags_t, + priv st_gen: uint32_t, + priv st_lspare: int32_t, + priv st_birthtime: time_t, + priv st_birthtime_nsec: c_long, + priv __unused: [uint8_t, ..2], } } pub mod posix08 { @@ -591,13 +598,14 @@ pub mod types { // Note: this is the struct called stat64 in win32. Not stat, // nor stati64. pub struct stat { + // all made privv by reedlepee st_dev: dev_t, st_ino: ino_t, st_mode: mode_t, st_nlink: c_short, - st_uid: c_short, + st_uid: c_short, st_gid: c_short, - st_rdev: dev_t, + st_rdev: dev_t, st_size: int64, st_atime: time64_t, st_mtime: time64_t, @@ -697,47 +705,49 @@ pub mod types { pub type int64 = i64; pub struct STARTUPINFO { - cb: DWORD, - lpReserved: LPTSTR, - lpDesktop: LPTSTR, - lpTitle: LPTSTR, - dwX: DWORD, - dwY: DWORD, - dwXSize: DWORD, - dwYSize: DWORD, - dwXCountChars: DWORD, - dwYCountCharts: DWORD, - dwFillAttribute: DWORD, - dwFlags: DWORD, - wShowWindow: WORD, - cbReserved2: WORD, - lpReserved2: LPBYTE, - hStdInput: HANDLE, - hStdOutput: HANDLE, - hStdError: HANDLE + // all made by reedlepee + priv cb: DWORD, + priv lpReserved: LPTSTR, + priv lpDesktop: LPTSTR, + priv lpTitle: LPTSTR, + priv dwX: DWORD, + priv dwY: DWORD, + priv dwXSize: DWORD, + priv dwYSize: DWORD, + priv dwXCountChars: DWORD, + priv dwYCountCharts: DWORD, + priv dwFillAttribute: DWORD, + priv dwFlags: DWORD, + priv wShowWindow: WORD, + priv cbReserved2: WORD, + priv lpReserved2: LPBYTE, + priv hStdInput: HANDLE, + priv hStdOutput: HANDLE, + priv hStdError: HANDLE } pub type LPSTARTUPINFO = *mut STARTUPINFO; - pub struct PROCESS_INFORMATION { - hProcess: HANDLE, - hThread: HANDLE, - dwProcessId: DWORD, - dwThreadId: DWORD + // all made by reedlepee + priv hProcess: HANDLE, + priv hThread: HANDLE, + priv dwProcessId: DWORD, + priv dwThreadId: DWORD } pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub struct SYSTEM_INFO { - wProcessorArchitecture: WORD, - wReserved: WORD, - dwPageSize: DWORD, - lpMinimumApplicationAddress: LPVOID, - lpMaximumApplicationAddress: LPVOID, - dwActiveProcessorMask: DWORD, - dwNumberOfProcessors: DWORD, - dwProcessorType: DWORD, - dwAllocationGranularity: DWORD, - wProcessorLevel: WORD, - wProcessorRevision: WORD + // all made by reedlepee + priv wProcessorArchitecture: WORD, + priv wReserved: WORD, + priv dwPageSize: DWORD, + priv lpMinimumApplicationAddress: LPVOID, + priv lpMaximumApplicationAddress: LPVOID, + priv dwActiveProcessorMask: DWORD, + priv dwNumberOfProcessors: DWORD, + priv dwProcessorType: DWORD, + priv dwAllocationGranularity: DWORD, + priv wProcessorLevel: WORD, + priv wProcessorRevision: WORD } pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; @@ -760,13 +770,14 @@ pub mod types { } pub struct MEMORY_BASIC_INFORMATION { - BaseAddress: LPVOID, - AllocationBase: LPVOID, - AllocationProtect: DWORD, - RegionSize: SIZE_T, - State: DWORD, - Protect: DWORD, - Type: DWORD + // all made by reedlepee + priv BaseAddress: LPVOID, + priv AllocationBase: LPVOID, + priv AllocationProtect: DWORD, + priv RegionSize: SIZE_T, + priv State: DWORD, + priv Protect: DWORD, + priv Type: DWORD } pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; } @@ -863,47 +874,50 @@ pub mod types { pub type int64 = i64; pub struct STARTUPINFO { - cb: DWORD, - lpReserved: LPTSTR, - lpDesktop: LPTSTR, - lpTitle: LPTSTR, - dwX: DWORD, - dwY: DWORD, - dwXSize: DWORD, - dwYSize: DWORD, - dwXCountChars: DWORD, - dwYCountCharts: DWORD, - dwFillAttribute: DWORD, - dwFlags: DWORD, - wShowWindow: WORD, - cbReserved2: WORD, - lpReserved2: LPBYTE, - hStdInput: HANDLE, - hStdOutput: HANDLE, - hStdError: HANDLE + // all made by reedlepee + priv cb: DWORD, + priv lpReserved: LPTSTR, + priv lpDesktop: LPTSTR, + priv lpTitle: LPTSTR, + priv dwX: DWORD, + priv dwY: DWORD, + priv dwXSize: DWORD, + priv dwYSize: DWORD, + priv dwXCountChars: DWORD, + priv dwYCountCharts: DWORD, + priv dwFillAttribute: DWORD, + priv dwFlags: DWORD, + priv wShowWindow: WORD, + priv cbReserved2: WORD, + priv lpReserved2: LPBYTE, + priv hStdInput: HANDLE, + priv hStdOutput: HANDLE, + priv hStdError: HANDLE } pub type LPSTARTUPINFO = *mut STARTUPINFO; pub struct PROCESS_INFORMATION { - hProcess: HANDLE, - hThread: HANDLE, - dwProcessId: DWORD, - dwThreadId: DWORD + // all made by reedlepee + priv hProcess: HANDLE, + priv hThread: HANDLE, + priv dwProcessId: DWORD, + priv dwThreadId: DWORD } pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub struct SYSTEM_INFO { - wProcessorArchitecture: WORD, - wReserved: WORD, - dwPageSize: DWORD, - lpMinimumApplicationAddress: LPVOID, - lpMaximumApplicationAddress: LPVOID, - dwActiveProcessorMask: DWORD, - dwNumberOfProcessors: DWORD, - dwProcessorType: DWORD, - dwAllocationGranularity: DWORD, - wProcessorLevel: WORD, - wProcessorRevision: WORD + // all made by reedlepee + priv wProcessorArchitecture: WORD, + priv wReserved: WORD, + priv dwPageSize: DWORD, + priv lpMinimumApplicationAddress: LPVOID, + priv lpMaximumApplicationAddress: LPVOID, + priv dwActiveProcessorMask: DWORD, + priv dwNumberOfProcessors: DWORD, + priv dwProcessorType: DWORD, + priv dwAllocationGranularity: DWORD, + priv wProcessorLevel: WORD, + priv wProcessorRevision: WORD } pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; @@ -926,13 +940,14 @@ pub mod types { } pub struct MEMORY_BASIC_INFORMATION { - BaseAddress: LPVOID, - AllocationBase: LPVOID, - AllocationProtect: DWORD, - RegionSize: SIZE_T, - State: DWORD, - Protect: DWORD, - Type: DWORD + // all made by reedlepee + priv BaseAddress: LPVOID, + priv AllocationBase: LPVOID, + priv AllocationProtect: DWORD, + priv RegionSize: SIZE_T, + priv State: DWORD, + priv Protect: DWORD, + priv Type: DWORD } pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; } @@ -946,19 +961,20 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, c_int, size_t}; pub struct glob_t { - gl_pathc: size_t, - __unused1: c_int, - gl_offs: size_t, - __unused2: c_int, - gl_pathv: **c_char, + // all made by reedlepee + priv gl_pathc: size_t, + priv __unused1: c_int, + priv gl_offs: size_t, + priv __unused2: c_int, + priv gl_pathv: **c_char, - __unused3: *c_void, + priv __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, - __unused6: *c_void, - __unused7: *c_void, - __unused8: *c_void, + __unused4: *c_void, + __unused5: *c_void, + priv __unused6: *c_void, + priv __unused7: *c_void, + priv __unused8: *c_void, } } } @@ -1011,28 +1027,29 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { + // all made by reedlepee st_dev: dev_t, st_mode: mode_t, st_nlink: nlink_t, st_ino: ino_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, st_mtime_nsec: c_long, st_ctime: time_t, st_ctime_nsec: c_long, - st_birthtime: time_t, - st_birthtime_nsec: c_long, + priv st_birthtime: time_t, + priv st_birthtime_nsec: c_long, st_size: off_t, st_blocks: blkcnt_t, st_blksize: blksize_t, - st_flags: uint32_t, - st_gen: uint32_t, - st_lspare: int32_t, - st_qspare: [int64_t, ..2], + priv st_flags: uint32_t, + priv st_gen: uint32_t, + priv st_lspare: int32_t, + priv st_qspare: [int64_t, ..2], } } pub mod posix08 { @@ -1092,28 +1109,29 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { - st_dev: dev_t, - st_mode: mode_t, - st_nlink: nlink_t, - st_ino: ino_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, - st_atime: time_t, - st_atime_nsec: c_long, - st_mtime: time_t, - st_mtime_nsec: c_long, - st_ctime: time_t, - st_ctime_nsec: c_long, - st_birthtime: time_t, - st_birthtime_nsec: c_long, - st_size: off_t, - st_blocks: blkcnt_t, - st_blksize: blksize_t, - st_flags: uint32_t, - st_gen: uint32_t, - st_lspare: int32_t, - st_qspare: [int64_t, ..2], + // all made by reedlepee + st_dev: dev_t, + st_mode: mode_t, + st_nlink: nlink_t, + st_ino: ino_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, + st_atime: time_t, + st_atime_nsec: c_long, + st_mtime: time_t, + st_mtime_nsec: c_long, + st_ctime: time_t, + st_ctime_nsec: c_long, + priv st_birthtime: time_t, + priv st_birthtime_nsec: c_long, + st_size: off_t, + st_blocks: blkcnt_t, + st_blksize: blksize_t, + priv st_flags: uint32_t, + priv st_gen: uint32_t, + priv st_lspare: int32_t, + priv st_qspare: [int64_t, ..2], } } pub mod posix08 { diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 732dbe64d015..95e61eca38ca 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -454,6 +454,7 @@ impl Option { /// An iterator that yields either one or zero elements #[deriving(Clone, DeepClone)] pub struct OptionIterator { + // already priv priv opt: Option } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index ba2b42c9b9c8..16035327da62 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -412,6 +412,7 @@ pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int { } pub struct Pipe { + // made priv by reedlepee input: c_int, out: c_int } @@ -1380,6 +1381,7 @@ pub fn page_size() -> uint { } pub struct MemoryMap { + // made priv by reedlepee data: *mut u8, len: size_t, kind: MemoryMapKind diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index f71f67a30db8..113641ffe3e9 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -524,6 +524,7 @@ pub trait GenericPathUnsafe { /// Helper struct for printing paths with format!() pub struct Display<'self, P> { + /// already priv priv path: &'self P, priv filename: bool } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 87821105d37e..207b23ab5e8f 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -42,6 +42,7 @@ pub type RevStrComponentIter<'self> = Map<'self, &'self [u8], Option<&'self str> /// Represents a POSIX file path #[deriving(Clone, DeepClone)] pub struct Path { + /// already priv priv repr: ~[u8], // assumed to never be empty or contain NULs priv sepidx: Option // index of the final separator in repr } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 0de2bd4c742b..230b03c6554f 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -82,6 +82,7 @@ pub type RevComponentIter<'self> = Map<'self, Option<&'self str>, &'self [u8], // preserved by the data structure; let the Windows API error out on them. #[deriving(Clone, DeepClone)] pub struct Path { + /// already priv priv repr: ~str, // assumed to never be empty priv prefix: Option, priv sepidx: Option // index of the final separator in the non-prefix portion of repr diff --git a/src/libstd/rand/isaac.rs b/src/libstd/rand/isaac.rs index 0068b60cfa51..8c25a2f7971e 100644 --- a/src/libstd/rand/isaac.rs +++ b/src/libstd/rand/isaac.rs @@ -23,6 +23,7 @@ static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN; /// /// The ISAAC algorithm is suitable for cryptographic purposes. pub struct IsaacRng { + /// already priv priv cnt: u32, priv rsl: [u32, .. RAND_SIZE], priv mem: [u32, .. RAND_SIZE], @@ -218,6 +219,7 @@ static RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN; /// /// The ISAAC algorithm is suitable for cryptographic purposes. pub struct Isaac64Rng { + /// already priv priv cnt: uint, priv rsl: [u64, .. RAND_SIZE_64], priv mem: [u64, .. RAND_SIZE_64], diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index f5c60417bacb..1397a32632fe 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -82,10 +82,11 @@ pub trait Rand { /// A value with a particular weight compared to other values pub struct Weighted { + /// made priv by reedlepee /// The numerical weight of this item - weight: uint, + priv weight: uint, /// The actual item which is being weighted - item: T, + priv item: T, } /// A random number generator @@ -537,11 +538,13 @@ pub fn rng() -> StdRng { /// The standard RNG. This is designed to be efficient on the current /// platform. #[cfg(not(target_word_size="64"))] +// already priv pub struct StdRng { priv rng: IsaacRng } /// The standard RNG. This is designed to be efficient on the current /// platform. #[cfg(target_word_size="64")] +// already priv pub struct StdRng { priv rng: Isaac64Rng } impl StdRng { @@ -603,6 +606,7 @@ pub fn weak_rng() -> XorShiftRng { /// 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 { + // already priv priv x: u32, priv y: u32, priv z: u32, diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 4c8cf06c55e8..a240c8bb873c 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -36,6 +36,7 @@ type HCRYPTPROV = c_long; /// This does not block. #[cfg(unix)] pub struct OSRng { + // already priv priv inner: ReaderRng } /// A random number generator that retrieves randomness straight from @@ -45,6 +46,7 @@ pub struct OSRng { /// This does not block. #[cfg(windows)] pub struct OSRng { + // already priv priv hcryptprov: HCRYPTPROV } diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index f1e67da815e1..ca2284f69bb4 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -33,6 +33,7 @@ use rand::Rng; /// } /// ``` pub struct ReaderRng { + // already priv priv reader: R } diff --git a/src/libstd/rand/reseeding.rs b/src/libstd/rand/reseeding.rs index 3b4919392fc2..65e10f6f01f8 100644 --- a/src/libstd/rand/reseeding.rs +++ b/src/libstd/rand/reseeding.rs @@ -21,11 +21,13 @@ static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng { + // already priv priv rng: R, priv generation_threshold: uint, priv bytes_generated: uint, /// Controls the behaviour when reseeding the RNG. - reseeder: Rsdr + // made by reedlepee + priv reseeder: Rsdr } impl> ReseedingRng { diff --git a/src/libstd/rc.rs b/src/libstd/rc.rs index 41e834cf37c3..388683dc029d 100644 --- a/src/libstd/rc.rs +++ b/src/libstd/rc.rs @@ -35,6 +35,7 @@ struct RcBox { #[unsafe_no_drop_flag] #[no_send] pub struct Rc { + // already priv priv ptr: *mut RcBox } @@ -167,6 +168,7 @@ struct RcMutBox { #[no_freeze] #[unsafe_no_drop_flag] pub struct RcMut { + // already priv priv ptr: *mut RcMutBox, } diff --git a/src/libstd/reflect.rs b/src/libstd/reflect.rs index 1cd767277167..9e13d20e9710 100644 --- a/src/libstd/reflect.rs +++ b/src/libstd/reflect.rs @@ -41,7 +41,8 @@ pub fn align(size: uint, align: uint) -> uint { /// Adaptor to wrap around visitors implementing MovePtr. pub struct MovePtrAdaptor { - inner: V + // all by reedlepee + priv inner: V } pub fn MovePtrAdaptor(v: V) -> MovePtrAdaptor { MovePtrAdaptor { inner: v } diff --git a/src/libstd/repr.rs b/src/libstd/repr.rs index 4feb1ca19104..0a8d2374218b 100644 --- a/src/libstd/repr.rs +++ b/src/libstd/repr.rs @@ -98,10 +98,11 @@ enum VariantState { } pub struct ReprVisitor<'self> { - ptr: *c_void, - ptr_stk: ~[*c_void], - var_stk: ~[VariantState], - writer: &'self mut io::Writer + // made priv by reedlpee + priv ptr: *c_void, + priv ptr_stk: ~[*c_void], + priv var_stk: ~[VariantState], + priv writer: &'self mut io::Writer } pub fn ReprVisitor<'a>(ptr: *c_void, diff --git a/src/libstd/rt/borrowck.rs b/src/libstd/rt/borrowck.rs index 3c2000c522c4..182515e12bee 100644 --- a/src/libstd/rt/borrowck.rs +++ b/src/libstd/rt/borrowck.rs @@ -29,9 +29,10 @@ static ALL_BITS: uint = FROZEN_BIT | MUT_BIT; #[deriving(Eq)] pub struct BorrowRecord { - box: *mut raw::Box<()>, + // all made byt reedlepee + priv box: *mut raw::Box<()>, file: *c_char, - line: size_t + priv line: size_t } fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> { diff --git a/src/libstd/rt/comm.rs b/src/libstd/rt/comm.rs index 4eae8bdc9a82..b74ae01fa301 100644 --- a/src/libstd/rt/comm.rs +++ b/src/libstd/rt/comm.rs @@ -48,14 +48,16 @@ struct Packet { // A one-shot channel. pub struct ChanOne { - void_packet: *mut Void, - suppress_finalize: bool + // all made priv by reeldepee + priv void_packet: *mut Void, + priv suppress_finalize: bool } /// A one-shot port. pub struct PortOne { - void_packet: *mut Void, - suppress_finalize: bool + // all made priv by reeldepee + priv void_packet: *mut Void, + priv suppress_finalize: bool } pub fn oneshot() -> (PortOne, ChanOne) { @@ -443,12 +445,14 @@ type StreamPortOne = PortOne>; /// A channel with unbounded size. pub struct Chan { + // all made priv by reeldepee // FIXME #5372. Using Cell because we don't take &mut self next: Cell> } /// An port with unbounded size. pub struct Port { + // all made priv by reeldepee // FIXME #5372. Using Cell because we don't take &mut self next: Cell> } @@ -577,6 +581,7 @@ impl<'self, T> SelectPortInner for &'self Port { impl<'self, T> SelectPort for &'self Port { } pub struct SharedChan { + // already priv // Just like Chan, but a shared AtomicOption instead of Cell priv next: UnsafeArc>> } @@ -630,6 +635,7 @@ impl Clone for SharedChan { } pub struct SharedPort { + // already priv // The next port on which we will receive the next port on which we will receive T priv next_link: UnsafeArc>>> } diff --git a/src/libstd/rt/context.rs b/src/libstd/rt/context.rs index 7f7545ca230f..9508c757c9dd 100644 --- a/src/libstd/rt/context.rs +++ b/src/libstd/rt/context.rs @@ -25,11 +25,11 @@ pub static RED_ZONE: uint = 20 * 1024; // then misalign the regs again. pub struct Context { /// The context entry point, saved here for later destruction - start: Option<~~fn()>, + priv start: Option<~~fn()>, /// Hold the registers while the task or scheduler is suspended - regs: ~Registers, + priv regs: ~Registers, /// Lower bound and upper bound for the stack - stack_bounds: Option<(uint, uint)>, + priv stack_bounds: Option<(uint, uint)>, } impl Context { diff --git a/src/libstd/rt/crate_map.rs b/src/libstd/rt/crate_map.rs index d33e1af90f8d..54a1c2406d0b 100644 --- a/src/libstd/rt/crate_map.rs +++ b/src/libstd/rt/crate_map.rs @@ -21,14 +21,16 @@ use vec::ImmutableVector; extern {} pub struct ModEntry<'self> { + // made priv by reedlepee name: &'self str, log_level: *mut u32 } pub struct CrateMap<'self> { - version: i32, - entries: &'self [ModEntry<'self>], - children: &'self [&'self CrateMap<'self>] + // made priv by reedlepee + priv version: i32, + priv entries: &'self [ModEntry<'self>], + priv children: &'self [&'self CrateMap<'self>] } #[cfg(not(windows))] diff --git a/src/libstd/rt/io/buffered.rs b/src/libstd/rt/io/buffered.rs index 9dcb35c806f7..a33892736b09 100644 --- a/src/libstd/rt/io/buffered.rs +++ b/src/libstd/rt/io/buffered.rs @@ -64,6 +64,7 @@ static DEFAULT_CAPACITY: uint = 64 * 1024; /// Wraps a Reader and buffers input from it pub struct BufferedReader { + // all already priv priv inner: R, priv buf: ~[u8], priv pos: uint, @@ -175,6 +176,7 @@ impl Decorator for BufferedReader { /// /// Note that `BufferedWriter` will NOT flush its buffer when dropped. pub struct BufferedWriter { + // all already priv priv inner: W, priv buf: ~[u8], priv pos: uint @@ -250,6 +252,7 @@ impl Reader for InternalBufferedWriter { /// /// Note that `BufferedStream` will NOT flush its output buffer when dropped. pub struct BufferedStream { + // all already priv priv inner: BufferedReader> } diff --git a/src/libstd/rt/io/extensions.rs b/src/libstd/rt/io/extensions.rs index 99634b532b08..5a3524195c74 100644 --- a/src/libstd/rt/io/extensions.rs +++ b/src/libstd/rt/io/extensions.rs @@ -368,6 +368,7 @@ impl ReaderUtil for T { /// each call to its `.next()` method. /// Yields `None` if the condition is handled. pub struct ByteIterator { + // all already priv priv reader: T, } diff --git a/src/libstd/rt/io/file.rs b/src/libstd/rt/io/file.rs index a5d593d2454d..9d633ec1c65a 100644 --- a/src/libstd/rt/io/file.rs +++ b/src/libstd/rt/io/file.rs @@ -298,6 +298,7 @@ pub fn readdir(path: &P) -> Option<~[Path]> { /// Constrained version of `FileStream` that only exposes read-specific operations. /// /// Can be retreived via `FileInfo.open_reader()`. +/// all already priv pub struct FileReader { priv stream: FileStream } /// a `std::rt::io::Reader` trait impl for file I/O. @@ -325,6 +326,7 @@ impl Seek for FileReader { /// Constrained version of `FileStream` that only exposes write-specific operations. /// /// Can be retreived via `FileInfo.open_writer()`. +// already priv pub struct FileWriter { priv stream: FileStream } /// a `std::rt::io::Writer` trait impl for file I/O. @@ -362,8 +364,9 @@ impl Seek for FileWriter { /// For this reason, it is best to use the access-constrained wrappers that are /// exposed via `FileInfo.open_reader()` and `FileInfo.open_writer()`. pub struct FileStream { - fd: ~RtioFileStream, - last_nread: int, + // all made by reedlepee + priv fd: ~RtioFileStream, + priv last_nread: int, } /// a `std::rt::io::Reader` trait impl for file I/O. diff --git a/src/libstd/rt/io/flate.rs b/src/libstd/rt/io/flate.rs index 7c72ce6ba891..9c49f2afb1ed 100644 --- a/src/libstd/rt/io/flate.rs +++ b/src/libstd/rt/io/flate.rs @@ -17,7 +17,8 @@ use super::*; /// A Writer decorator that compresses using the 'deflate' scheme pub struct DeflateWriter { - inner_writer: W + // all made by reedlepee + priv inner_writer: W } impl DeflateWriter { @@ -56,7 +57,8 @@ impl Decorator for DeflateWriter { /// A Reader decorator that decompresses using the 'deflate' scheme pub struct InflateReader { - inner_reader: R + // all made by reedlepee + priv inner_reader: R } impl InflateReader { diff --git a/src/libstd/rt/io/mem.rs b/src/libstd/rt/io/mem.rs index 5f6b4398c22f..85bd46ebaf43 100644 --- a/src/libstd/rt/io/mem.rs +++ b/src/libstd/rt/io/mem.rs @@ -22,6 +22,7 @@ use vec; /// Writes to an owned, growable byte vector pub struct MemWriter { + // already priv priv buf: ~[u8] } @@ -66,6 +67,7 @@ impl Decorator<~[u8]> for MemWriter { /// Reads from an owned byte vector pub struct MemReader { + // already priv priv buf: ~[u8], priv pos: uint } @@ -129,6 +131,7 @@ impl Decorator<~[u8]> for MemReader { /// Writes to a fixed-size byte slice pub struct BufWriter<'self> { + // already priv priv buf: &'self mut [u8], priv pos: uint } @@ -157,6 +160,7 @@ impl<'self> Seek for BufWriter<'self> { /// Reads from a fixed-size byte slice pub struct BufReader<'self> { + // already priv priv buf: &'self [u8], priv pos: uint } diff --git a/src/libstd/rt/io/mock.rs b/src/libstd/rt/io/mock.rs index c46e1372c641..30775ec90ba0 100644 --- a/src/libstd/rt/io/mock.rs +++ b/src/libstd/rt/io/mock.rs @@ -12,8 +12,9 @@ use option::{Option, None}; use rt::io::{Reader, Writer}; pub struct MockReader { + // all made by reedlepee read: ~fn(buf: &mut [u8]) -> Option, - eof: ~fn() -> bool + priv eof: ~fn() -> bool } impl MockReader { @@ -31,8 +32,8 @@ impl Reader for MockReader { } pub struct MockWriter { - write: ~fn(buf: &[u8]), - flush: ~fn() + priv write: ~fn(buf: &[u8]), + priv flush: ~fn() } impl MockWriter { diff --git a/src/libstd/rt/io/mod.rs b/src/libstd/rt/io/mod.rs index c0971b5d3cd5..d9951741ab25 100644 --- a/src/libstd/rt/io/mod.rs +++ b/src/libstd/rt/io/mod.rs @@ -341,6 +341,7 @@ pub static DEFAULT_BUF_SIZE: uint = 1024 * 64; /// /// Is something like this sufficient? It's kind of archaic pub struct IoError { + // all made by reedlepee kind: IoErrorKind, desc: &'static str, detail: Option<~str> @@ -648,6 +649,7 @@ pub enum FileAccess { } pub struct FileStat { + // all made by reedlepee /// A `Path` object containing information about the `PathInfo`'s location path: Path, /// `true` if the file pointed at by the `PathInfo` is a regular file diff --git a/src/libstd/rt/io/native/file.rs b/src/libstd/rt/io/native/file.rs index d68209811817..cce2e851452b 100644 --- a/src/libstd/rt/io/native/file.rs +++ b/src/libstd/rt/io/native/file.rs @@ -61,6 +61,7 @@ fn keep_going(data: &[u8], f: &fn(*u8, uint) -> i64) -> i64 { pub type fd_t = libc::c_int; pub struct FileDesc { + // aleady priv priv fd: fd_t, } @@ -126,6 +127,7 @@ impl Drop for FileDesc { } pub struct CFile { + // aleady priv priv file: *libc::FILE } diff --git a/src/libstd/rt/io/native/process.rs b/src/libstd/rt/io/native/process.rs index 91fff6d92630..73ce330cd49c 100644 --- a/src/libstd/rt/io/native/process.rs +++ b/src/libstd/rt/io/native/process.rs @@ -25,6 +25,7 @@ use super::file; * for the process to terminate. */ pub struct Process { + // aleady priv /// The unique id of the process (this should never be negative). priv pid: pid_t, diff --git a/src/libstd/rt/io/native/stdio.rs b/src/libstd/rt/io/native/stdio.rs index 5661725d77ba..41c25e0841ab 100644 --- a/src/libstd/rt/io/native/stdio.rs +++ b/src/libstd/rt/io/native/stdio.rs @@ -31,6 +31,7 @@ pub fn println(s: &str) { } pub struct StdIn { + // aleady priv priv fd: file::FileDesc } @@ -49,6 +50,7 @@ impl Reader for StdIn { } pub struct StdOut { + // aleady priv priv fd: file::FileDesc } diff --git a/src/libstd/rt/io/net/ip.rs b/src/libstd/rt/io/net/ip.rs index f72d2e1f19bd..945014867e2c 100644 --- a/src/libstd/rt/io/net/ip.rs +++ b/src/libstd/rt/io/net/ip.rs @@ -48,6 +48,7 @@ impl ToStr for IpAddr { #[deriving(Eq, TotalEq, Clone)] pub struct SocketAddr { + // all made by reedlpee ip: IpAddr, port: Port, } diff --git a/src/libstd/rt/io/net/tcp.rs b/src/libstd/rt/io/net/tcp.rs index f29e17cfc2f3..0ed5861e2961 100644 --- a/src/libstd/rt/io/net/tcp.rs +++ b/src/libstd/rt/io/net/tcp.rs @@ -21,6 +21,7 @@ use rt::rtio::{IoFactory, IoFactoryObject, use rt::local::Local; pub struct TcpStream { + // aleady priv priv obj: ~RtioTcpStreamObject } @@ -99,6 +100,7 @@ impl Writer for TcpStream { } pub struct TcpListener { + // aleady priv priv obj: ~RtioTcpListenerObject } @@ -142,6 +144,7 @@ impl Listener for TcpListener { } pub struct TcpAcceptor { + // aleady priv priv obj: ~RtioTcpAcceptorObject } diff --git a/src/libstd/rt/io/net/udp.rs b/src/libstd/rt/io/net/udp.rs index 27faae0838b1..5c63dd5352e6 100644 --- a/src/libstd/rt/io/net/udp.rs +++ b/src/libstd/rt/io/net/udp.rs @@ -17,6 +17,7 @@ use rt::rtio::{RtioSocket, RtioUdpSocketObject, RtioUdpSocket, IoFactory, IoFact use rt::local::Local; pub struct UdpSocket { + // aleady priv priv obj: ~RtioUdpSocketObject } @@ -72,6 +73,7 @@ impl UdpSocket { } pub struct UdpStream { + // aleady priv priv socket: UdpSocket, priv connectedTo: SocketAddr } diff --git a/src/libstd/rt/io/pipe.rs b/src/libstd/rt/io/pipe.rs index d2cd531ed266..a89419fa41f1 100644 --- a/src/libstd/rt/io/pipe.rs +++ b/src/libstd/rt/io/pipe.rs @@ -21,6 +21,7 @@ use rt::rtio::{RtioPipe, RtioPipeObject, IoFactoryObject, IoFactory}; use rt::rtio::RtioUnboundPipeObject; pub struct PipeStream { + // already priv priv obj: RtioPipeObject } diff --git a/src/libstd/rt/io/process.rs b/src/libstd/rt/io/process.rs index 5f2453852ee7..e6029e0ff9c1 100644 --- a/src/libstd/rt/io/process.rs +++ b/src/libstd/rt/io/process.rs @@ -26,13 +26,16 @@ use rt::rtio::{RtioProcess, RtioProcessObject, IoFactoryObject, IoFactory}; #[cfg(not(windows))] pub static MustDieSignal: int = libc::SIGKILL as int; pub struct Process { + // already priv priv handle: ~RtioProcessObject, + // made by reedlepee io: ~[Option], } /// This configuration describes how a new process should be spawned. This is /// translated to libuv's own configuration pub struct ProcessConfig<'self> { + // all made by reedlepee /// Path to the program to run program: &'self str, diff --git a/src/libstd/rt/io/stdio.rs b/src/libstd/rt/io/stdio.rs index e6dd9a480998..9f540dd0a812 100644 --- a/src/libstd/rt/io/stdio.rs +++ b/src/libstd/rt/io/stdio.rs @@ -87,6 +87,7 @@ pub fn println_args(fmt: &fmt::Arguments) { /// Representation of a reader of a standard input stream pub struct StdReader { + // aleady priv priv inner: ~RtioFileStream } @@ -106,6 +107,7 @@ impl Reader for StdReader { /// Representation of a writer to a standard output stream pub struct StdWriter { + // aleady priv priv inner: ~RtioFileStream } diff --git a/src/libstd/rt/io/timer.rs b/src/libstd/rt/io/timer.rs index b41d7541a607..cb35fdf5883f 100644 --- a/src/libstd/rt/io/timer.rs +++ b/src/libstd/rt/io/timer.rs @@ -16,6 +16,7 @@ use rt::rtio::{IoFactory, IoFactoryObject, use rt::local::Local; pub struct Timer { + // aleady priv priv obj: ~RtioTimerObject } diff --git a/src/libstd/rt/kill.rs b/src/libstd/rt/kill.rs index 8029e3f64317..603e6627ee46 100644 --- a/src/libstd/rt/kill.rs +++ b/src/libstd/rt/kill.rs @@ -215,21 +215,22 @@ pub struct KillHandle(UnsafeArc); /// Per-task state related to task death, killing, failure, etc. pub struct Death { + // all made priv by reedlepee // Shared among this task, its watched children, and any linked tasks who // might kill it. This is optional so we can take it by-value at exit time. - kill_handle: Option, + kill_handle: Option, // Handle to a watching parent, if we have one, for exit code propagation. - watching_parent: Option, + priv watching_parent: Option, // Action to be done with the exit code. If set, also makes the task wait // until all its watched children exit before collecting the status. - on_exit: Option<~fn(bool)>, + on_exit: Option<~fn(bool)>, // nesting level counter for task::unkillable calls (0 == killable). - unkillable: int, + priv unkillable: int, // nesting level counter for unstable::atomically calls (0 == can deschedule). - wont_sleep: int, + priv wont_sleep: int, // A "spare" handle to the kill flag inside the kill handle. Used during // blocking/waking as an optimization to avoid two xadds on the refcount. - spare_kill_flag: Option, + priv spare_kill_flag: Option, } impl Drop for KillFlag { diff --git a/src/libstd/rt/local_heap.rs b/src/libstd/rt/local_heap.rs index 262da9f3b8e5..0f28880871d5 100644 --- a/src/libstd/rt/local_heap.rs +++ b/src/libstd/rt/local_heap.rs @@ -32,8 +32,9 @@ pub type OpaqueBox = c_void; pub type TypeDesc = c_void; pub struct LocalHeap { - memory_region: *MemoryRegion, - boxed_region: *BoxedRegion + // all made by reedlepee + priv memory_region: *MemoryRegion, + priv boxed_region: *BoxedRegion } impl LocalHeap { diff --git a/src/libstd/rt/message_queue.rs b/src/libstd/rt/message_queue.rs index 99b5156b3195..1864ebdad336 100644 --- a/src/libstd/rt/message_queue.rs +++ b/src/libstd/rt/message_queue.rs @@ -20,6 +20,7 @@ use unstable::sync::{UnsafeArc, LittleLock}; use clone::Clone; pub struct MessageQueue { + // already priv priv state: UnsafeArc> } diff --git a/src/libstd/rt/rc.rs b/src/libstd/rt/rc.rs index 2ba00c3a2fba..3e641196cb4a 100644 --- a/src/libstd/rt/rc.rs +++ b/src/libstd/rt/rc.rs @@ -24,7 +24,8 @@ use libc::c_void; use cast; pub struct RC { - p: *c_void // ~(uint, T) + // all made priv by reedlepe + priv p: *c_void // ~(uint, T) } impl RC { diff --git a/src/libstd/rt/rtio.rs b/src/libstd/rt/rtio.rs index ca521c792dc7..485239d307f5 100644 --- a/src/libstd/rt/rtio.rs +++ b/src/libstd/rt/rtio.rs @@ -61,12 +61,13 @@ pub trait RemoteCallback { /// Using unix flag conventions for now, which happens to also be what's supported /// libuv (it does translation to windows under the hood). pub struct FileOpenConfig { + // all made by reedlepe /// Path to file to be opened path: Path, /// Flags for file access mode (as per open(2)) flags: int, /// File creation mode, ignored unless O_CREAT is passed as part of flags - mode: int + priv mode: int } pub trait IoFactory { diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index 336d2518e437..82c56d7d9a30 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -40,13 +40,15 @@ use vec::{OwnedVector}; /// in too much allocation and too many events. pub struct Scheduler { /// There are N work queues, one per scheduler. - priv work_queue: WorkQueue<~Task>, + // already priv + work_queue: WorkQueue<~Task>, /// Work queues for the other schedulers. These are created by /// cloning the core work queues. work_queues: ~[WorkQueue<~Task>], /// The queue of incoming messages from other schedulers. /// These are enqueued by SchedHandles after which a remote callback /// is triggered to handle the message. + // already priv priv message_queue: MessageQueue, /// A shared list of sleeping schedulers. We'll use this to wake /// up schedulers when pushing work onto the work queue. @@ -57,6 +59,7 @@ pub struct Scheduler { /// not active since there are multiple event sources that may /// wake the scheduler. It just prevents the scheduler from pushing /// multiple handles onto the sleeper list. + // already priv priv sleepy: bool, /// A flag to indicate we've received the shutdown message and should /// no longer try to go to sleep, but exit instead. @@ -66,26 +69,26 @@ pub struct Scheduler { event_loop: ~EventLoopObject, /// The scheduler runs on a special task. When it is not running /// it is stored here instead of the work queue. - sched_task: Option<~Task>, + priv sched_task: Option<~Task>, /// An action performed after a context switch on behalf of the /// code running before the context switch - cleanup_job: Option, + priv cleanup_job: Option, /// Should this scheduler run any task, or only pinned tasks? run_anything: bool, /// If the scheduler shouldn't run some tasks, a friend to send /// them to. - friend_handle: Option, + priv friend_handle: Option, /// A fast XorShift rng for scheduler use rng: XorShiftRng, /// A toggleable idle callback - idle_callback: Option<~PausibleIdleCallback>, + priv idle_callback: Option<~PausibleIdleCallback>, /// A countdown that starts at a random value and is decremented /// every time a yield check is performed. When it hits 0 a task /// will yield. - yield_check_count: uint, + priv yield_check_count: uint, /// A flag to tell the scheduler loop it needs to do some stealing /// in order to introduce randomness as part of a yield - steal_for_yield: bool + priv steal_for_yield: bool } /// An indication of how hard to work on a given operation, the difference @@ -793,8 +796,10 @@ pub enum SchedMessage { } pub struct SchedHandle { + //already priv priv remote: ~RemoteCallbackObject, priv queue: MessageQueue, + // made by reedlepee sched_id: uint } diff --git a/src/libstd/rt/sleeper_list.rs b/src/libstd/rt/sleeper_list.rs index f4fdf15cda62..5135ed76005a 100644 --- a/src/libstd/rt/sleeper_list.rs +++ b/src/libstd/rt/sleeper_list.rs @@ -20,6 +20,7 @@ use rt::sched::SchedHandle; use clone::Clone; pub struct SleeperList { + // already priv priv state: UnsafeArc } diff --git a/src/libstd/rt/stack.rs b/src/libstd/rt/stack.rs index fddee5882b9a..7bffc93c6934 100644 --- a/src/libstd/rt/stack.rs +++ b/src/libstd/rt/stack.rs @@ -15,8 +15,9 @@ use ops::Drop; use libc::{c_uint, uintptr_t}; pub struct StackSegment { - buf: ~[u8], - valgrind_id: c_uint + // all made by reedlepee + priv buf: ~[u8], + priv valgrind_id: c_uint } impl StackSegment { diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index a6f9e11e40e9..6e0b96c221e6 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -43,20 +43,22 @@ use send_str::SendStr; // the type-specific state. pub struct Task { - heap: LocalHeap, - gc: GarbageCollector, - storage: LocalStorage, - logger: StdErrLogger, - unwinder: Unwinder, - taskgroup: Option, - death: Death, - destroyed: bool, - name: Option, - coroutine: Option, - sched: Option<~Scheduler>, - task_type: TaskType, + //all priv made br reedlepe + heap: LocalHeap, + priv gc: GarbageCollector, + storage: LocalStorage, + logger: StdErrLogger, + unwinder: Unwinder, + taskgroup: Option, + death: Death, + destroyed: bool, + name: Option, + coroutine: Option, + sched: Option<~Scheduler>, + task_type: TaskType, // Dynamic borrowck debugging info - borrow_list: Option<~[BorrowRecord]> + // should be public + borrow_list: Option<~[BorrowRecord]> } pub enum TaskType { @@ -69,7 +71,8 @@ pub struct Coroutine { /// The segment of stack on which the task is currently running or /// if the task is blocked, on which the task will resume /// execution. - current_stack_segment: StackSegment, + //all priv made br reedlepe + priv current_stack_segment: StackSegment, /// Always valid if the task is alive and not running. saved_context: Context } @@ -84,6 +87,7 @@ pub struct GarbageCollector; pub struct LocalStorage(Option); pub struct Unwinder { + //all priv made br reedlepe unwinding: bool, } diff --git a/src/libstd/rt/thread.rs b/src/libstd/rt/thread.rs index e774b81da350..949d73ecc4fc 100644 --- a/src/libstd/rt/thread.rs +++ b/src/libstd/rt/thread.rs @@ -18,9 +18,9 @@ use uint; type raw_thread = libc::c_void; pub struct Thread { - main: ~fn(), - raw_thread: *raw_thread, - joined: bool, + priv main: ~fn(), + priv raw_thread: *raw_thread, + priv joined: bool } impl Thread { diff --git a/src/libstd/rt/tube.rs b/src/libstd/rt/tube.rs index b8e535e4c7df..869f23baf325 100644 --- a/src/libstd/rt/tube.rs +++ b/src/libstd/rt/tube.rs @@ -28,7 +28,8 @@ struct TubeState { } pub struct Tube { - p: RC> + //all priv made br reedlepe + priv p: RC> } impl Tube { diff --git a/src/libstd/rt/uv/addrinfo.rs b/src/libstd/rt/uv/addrinfo.rs index 83a7e64b1397..8fa8fbdc4a10 100644 --- a/src/libstd/rt/uv/addrinfo.rs +++ b/src/libstd/rt/uv/addrinfo.rs @@ -25,7 +25,8 @@ type GetAddrInfoCallback = ~fn(GetAddrInfoRequest, &UvAddrInfo, Option) pub struct GetAddrInfoRequest(*uvll::uv_getaddrinfo_t); pub struct RequestData { - getaddrinfo_cb: Option, + // all made by reedlepee + priv getaddrinfo_cb: Option, } impl GetAddrInfoRequest { diff --git a/src/libstd/rt/uv/file.rs b/src/libstd/rt/uv/file.rs index 3a6d858df791..5e20f5fad88c 100644 --- a/src/libstd/rt/uv/file.rs +++ b/src/libstd/rt/uv/file.rs @@ -25,7 +25,8 @@ pub struct FsRequest(*uvll::uv_fs_t); impl Request for FsRequest {} pub struct RequestData { - complete_cb: Option + // all made by reedlepee + priv complete_cb: Option } impl FsRequest { diff --git a/src/libstd/rt/uv/mod.rs b/src/libstd/rt/uv/mod.rs index 67926b35a621..4c547276a50c 100644 --- a/src/libstd/rt/uv/mod.rs +++ b/src/libstd/rt/uv/mod.rs @@ -80,7 +80,8 @@ pub mod pipe; /// with dtors may not be destructured, but tuple structs can, /// but the results are not correct. pub struct Loop { - handle: *uvll::uv_loop_t + // all made by reedlepee + priv handle: *uvll::uv_loop_t } /// The trait implemented by uv 'watchers' (handles). Watchers are diff --git a/src/libstd/rt/uv/uvio.rs b/src/libstd/rt/uv/uvio.rs index d5893d6d0141..5e441a5414b4 100644 --- a/src/libstd/rt/uv/uvio.rs +++ b/src/libstd/rt/uv/uvio.rs @@ -180,7 +180,8 @@ fn socket_name>(sk: SocketNameKind, // Obviously an Event Loop is always home. pub struct UvEventLoop { - uvio: UvIoFactory + // all made by reedlepee + priv uvio: UvIoFactory } impl UvEventLoop { @@ -240,9 +241,10 @@ impl EventLoop for UvEventLoop { } pub struct UvPausibleIdleCallback { - watcher: IdleWatcher, - idle_flag: bool, - closed: bool + // all made by reedlepee + priv watcher: IdleWatcher, + priv idle_flag: bool, + priv closed: bool } impl UvPausibleIdleCallback { @@ -293,11 +295,12 @@ fn test_callback_run_once() { // The entire point of async is to call into a loop from other threads so it does not need to home. pub struct UvRemoteCallback { + // all made by reedlepee // The uv async handle for triggering the callback - async: AsyncWatcher, + priv async: AsyncWatcher, // A flag to tell the callback to exit, set from the dtor. This is // almost never contested - only in rare races with the dtor. - exit_flag: Exclusive + priv exit_flag: Exclusive } impl UvRemoteCallback { @@ -801,8 +804,9 @@ impl IoFactory for UvIoFactory { } pub struct UvTcpListener { - watcher : TcpWatcher, - home: SchedHandle, + // all made by reedlepee + priv watcher : TcpWatcher, + priv home: SchedHandle, } impl HomingIO for UvTcpListener { @@ -863,8 +867,9 @@ impl RtioTcpListener for UvTcpListener { } pub struct UvTcpAcceptor { - listener: UvTcpListener, - incoming: Tube>, + // all made by reedlepee + priv listener: UvTcpListener, + priv incoming: Tube>, } impl HomingIO for UvTcpAcceptor { @@ -987,8 +992,9 @@ fn write_stream(mut watcher: StreamWatcher, } pub struct UvUnboundPipe { + // all made by reedlepee pipe: Pipe, - home: SchedHandle, + priv home: SchedHandle, } impl HomingIO for UvUnboundPipe { @@ -1017,6 +1023,7 @@ impl UvUnboundPipe { } pub struct UvPipeStream { + // already priv inner: ~UvUnboundPipe, } @@ -1040,8 +1047,9 @@ impl RtioPipe for UvPipeStream { } pub struct UvTcpStream { - watcher: TcpWatcher, - home: SchedHandle, + // all made by reedlepee + priv watcher: TcpWatcher, + priv home: SchedHandle, } impl HomingIO for UvTcpStream { @@ -1140,8 +1148,9 @@ impl RtioTcpStream for UvTcpStream { } pub struct UvUdpSocket { - watcher: UdpWatcher, - home: SchedHandle, + // all made by reedelpee + priv watcher: UdpWatcher, + priv home: SchedHandle, } impl HomingIO for UvUdpSocket { @@ -1350,8 +1359,9 @@ impl RtioUdpSocket for UvUdpSocket { } pub struct UvTimer { - watcher: timer::TimerWatcher, - home: SchedHandle, + // all made by reedelpee + priv watcher: timer::TimerWatcher, + priv home: SchedHandle, } impl HomingIO for UvTimer { @@ -1397,10 +1407,11 @@ impl RtioTimer for UvTimer { } pub struct UvFileStream { - loop_: Loop, - fd: c_int, - close_on_drop: bool, - home: SchedHandle + // all made by reedelpee + priv loop_: Loop, + priv fd: c_int, + priv close_on_drop: bool, + priv home: SchedHandle } impl HomingIO for UvFileStream { @@ -1530,13 +1541,15 @@ impl RtioFileStream for UvFileStream { } pub struct UvProcess { - process: process::Process, + // two made by reedelpee + priv process: process::Process, // Sadly, this structure must be created before we return it, so in that // brief interim the `home` is None. - home: Option, + priv home: Option, // All None until the process exits (exit_error may stay None) + // Rest were already priv priv exit_status: Option, priv term_signal: Option, priv exit_error: Option, diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs index a80d5cbc1fb4..98d4fd332772 100644 --- a/src/libstd/rt/uv/uvll.rs +++ b/src/libstd/rt/uv/uvll.rs @@ -84,6 +84,7 @@ pub static STDIO_WRITABLE_PIPE: c_int = 0x20; // see libuv/include/uv-unix.h #[cfg(unix)] pub struct uv_buf_t { + // all made by reedelpee base: *u8, len: libc::size_t, } @@ -91,26 +92,29 @@ pub struct uv_buf_t { // see libuv/include/uv-win.h #[cfg(windows)] pub struct uv_buf_t { + // all made by reedelpee len: u32, base: *u8, } pub struct uv_process_options_t { - exit_cb: uv_exit_cb, - file: *libc::c_char, - args: **libc::c_char, - env: **libc::c_char, - cwd: *libc::c_char, - flags: libc::c_uint, - stdio_count: libc::c_int, - stdio: *uv_stdio_container_t, - uid: uv_uid_t, - gid: uv_gid_t, + // all made by reedelpee + exit_cb: uv_exit_cb, + file: *libc::c_char, + args: **libc::c_char, + env: **libc::c_char, + cwd: *libc::c_char, + flags: libc::c_uint, + stdio_count: libc::c_int, + stdio: *uv_stdio_container_t, + uid: uv_uid_t, + gid: uv_gid_t, } // These fields are private because they must be interfaced with through the // functions below. pub struct uv_stdio_container_t { + // already priv priv flags: libc::c_int, priv stream: *uv_stream_t, } @@ -133,27 +137,29 @@ pub type uv_process_t = c_void; pub type uv_pipe_t = c_void; pub struct uv_timespec_t { + // all made by reedelpee tv_sec: libc::c_long, - tv_nsec: libc::c_long + priv tv_nsec: libc::c_long } pub struct uv_stat_t { - st_dev: libc::uint64_t, + // all made by reedelpee + priv st_dev: libc::uint64_t, st_mode: libc::uint64_t, - st_nlink: libc::uint64_t, - st_uid: libc::uint64_t, - st_gid: libc::uint64_t, - st_rdev: libc::uint64_t, - st_ino: libc::uint64_t, + priv st_nlink: libc::uint64_t, + priv st_uid: libc::uint64_t, + priv st_gid: libc::uint64_t, + priv st_rdev: libc::uint64_t, + priv st_ino: libc::uint64_t, st_size: libc::uint64_t, - st_blksize: libc::uint64_t, - st_blocks: libc::uint64_t, - st_flags: libc::uint64_t, - st_gen: libc::uint64_t, + priv st_blksize: libc::uint64_t, + priv st_blocks: libc::uint64_t, + priv st_flags: libc::uint64_t, + priv st_gen: libc::uint64_t, st_atim: uv_timespec_t, st_mtim: uv_timespec_t, st_ctim: uv_timespec_t, - st_birthtim: uv_timespec_t + priv st_birthtim: uv_timespec_t } impl uv_stat_t { @@ -231,39 +237,42 @@ pub type socklen_t = c_int; #[cfg(target_os = "android")] #[cfg(target_os = "linux")] pub struct addrinfo { - ai_flags: c_int, - ai_family: c_int, - ai_socktype: c_int, - ai_protocol: c_int, - ai_addrlen: socklen_t, - ai_addr: *sockaddr, - ai_canonname: *char, - ai_next: *addrinfo + // all made by reedelpee + priv ai_flags: c_int, + priv ai_family: c_int, + priv ai_socktype: c_int, + priv ai_protocol: c_int, + priv ai_addrlen: socklen_t, + ai_addr: *sockaddr, + priv ai_canonname: *char, + ai_next: *addrinfo } #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] pub struct addrinfo { - ai_flags: c_int, - ai_family: c_int, - ai_socktype: c_int, - ai_protocol: c_int, - ai_addrlen: socklen_t, - ai_canonname: *char, + // all made by reedelpee + priv ai_flags: c_int, + priv ai_family: c_int, + priv ai_socktype: c_int, + priv ai_protocol: c_int, + priv ai_addrlen: socklen_t, + priv ai_canonname: *char, ai_addr: *sockaddr, ai_next: *addrinfo } #[cfg(windows)] pub struct addrinfo { - ai_flags: c_int, - ai_family: c_int, - ai_socktype: c_int, - ai_protocol: c_int, - ai_addrlen: size_t, - ai_canonname: *char, + // all made by reedelpee + priv ai_flags: c_int, + priv ai_family: c_int, + priv ai_socktype: c_int, + priv ai_protocol: c_int, + priv ai_addrlen: size_t, + priv ai_canonname: *char, ai_addr: *sockaddr, - ai_next: *addrinfo + priv vai_next: *addrinfo } #[cfg(unix)] pub type uv_uid_t = libc::types::os::arch::posix88::uid_t; @@ -960,8 +969,9 @@ pub unsafe fn freeaddrinfo(ai: *addrinfo) { } pub struct uv_err_data { - err_name: ~str, - err_msg: ~str, + // all made by reedelpee + priv err_name: ~str, + priv err_msg: ~str, } extern { diff --git a/src/libstd/rt/work_queue.rs b/src/libstd/rt/work_queue.rs index 24792f3904e5..7700855d7b74 100644 --- a/src/libstd/rt/work_queue.rs +++ b/src/libstd/rt/work_queue.rs @@ -17,6 +17,7 @@ use kinds::Send; use clone::Clone; pub struct WorkQueue { + // already priv // XXX: Another mystery bug fixed by boxing this lock priv queue: ~Exclusive<~[T]> } diff --git a/src/libstd/run.rs b/src/libstd/run.rs index a40605863182..ccb8de818571 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -29,12 +29,13 @@ use task; * for the process to terminate. */ pub struct Process { + // already priv priv inner: process::Process, } /// Options that can be given when starting a Process. pub struct ProcessOptions<'self> { - + // All were made priv by reedlepee /** * If this is None then the new process will have the same initial * environment as the parent process. @@ -99,7 +100,7 @@ impl <'self> ProcessOptions<'self> { /// The output of a finished process. pub struct ProcessOutput { - + /// made priv by reedlepee /// The status (exit code) of the process. status: int, diff --git a/src/libstd/str.rs b/src/libstd/str.rs index a6b0924e6c18..bba3ad6a94ef 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -355,6 +355,7 @@ Section: Iterators /// Use with the `std::iterator` module. #[deriving(Clone)] pub struct CharIterator<'self> { + // already priv /// The slice remaining to be iterated priv string: &'self str, } @@ -400,6 +401,7 @@ impl<'self> DoubleEndedIterator for CharIterator<'self> { /// Use with the `std::iterator` module. #[deriving(Clone)] pub struct CharOffsetIterator<'self> { + // already priv /// The original string to be iterated priv string: &'self str, priv iter: CharIterator<'self>, @@ -458,6 +460,7 @@ pub type ByteRevIterator<'self> = Invert>; /// An iterator over the substrings of a string, separated by `sep`. #[deriving(Clone)] pub struct CharSplitIterator<'self, Sep> { + // already priv /// The slice remaining to be iterated priv string: &'self str, priv sep: Sep, @@ -475,6 +478,7 @@ pub type CharRSplitIterator<'self, Sep> = Invert>; /// splitting at most `count` times. #[deriving(Clone)] pub struct CharSplitNIterator<'self, Sep> { + // already priv priv iter: CharSplitIterator<'self, Sep>, /// The number of splits remaining priv count: uint, @@ -591,6 +595,7 @@ impl<'self, Sep: CharEq> Iterator<&'self str> for CharSplitNIterator<'self, Sep> /// substring within a larger string #[deriving(Clone)] pub struct MatchesIndexIterator<'self> { + // already priv priv haystack: &'self str, priv needle: &'self str, priv position: uint, @@ -600,6 +605,7 @@ pub struct MatchesIndexIterator<'self> { /// search string #[deriving(Clone)] pub struct StrSplitIterator<'self> { + // already priv priv it: MatchesIndexIterator<'self>, priv last_end: uint, priv finished: bool @@ -997,9 +1003,9 @@ pub fn utf8_char_width(b: u8) -> uint { /// the utf8 bytes of a string. pub struct CharRange { /// Current `char` - /// This field should be public making it private causes error while compiling!! + /// This field should be public making it private causes error while compiling!! ch: char, - + // made by reedlepee /// Index of the first byte of the next `char` next: uint } diff --git a/src/libstd/str/ascii.rs b/src/libstd/str/ascii.rs index ec2d75661775..35a33f017014 100644 --- a/src/libstd/str/ascii.rs +++ b/src/libstd/str/ascii.rs @@ -23,6 +23,7 @@ use option::{Some, None}; /// Datatype to hold one ascii character. It wraps a `u8`, with the highest bit always zero. #[deriving(Clone, Eq, Ord, TotalOrd, TotalEq)] +//already priv pub struct Ascii { priv chr: u8 } impl Ascii { diff --git a/src/libstd/task/mod.rs b/src/libstd/task/mod.rs index 970a62b676fc..55a881f48fad 100644 --- a/src/libstd/task/mod.rs +++ b/src/libstd/task/mod.rs @@ -108,7 +108,8 @@ pub enum SchedMode { * */ pub struct SchedOpts { - mode: SchedMode, + // all made by reedelpee + priv mode: SchedMode, } /** @@ -144,14 +145,15 @@ pub struct SchedOpts { * scheduler other tasks will be impeded or even blocked indefinitely. */ pub struct TaskOpts { - linked: bool, - supervised: bool, - watched: bool, - indestructible: bool, - notify_chan: Option>, - name: Option, - sched: SchedOpts, - stack_size: Option + // all made by reedelpee + priv linked: bool, + priv supervised: bool, + priv watched: bool, + priv indestructible: bool, + priv notify_chan: Option>, + name: Option, + sched: SchedOpts, + stack_size: Option } /** @@ -169,10 +171,11 @@ pub struct TaskOpts { // FIXME (#3724): Replace the 'consumed' bit with move mode on self pub struct TaskBuilder { + //all made priv by reedlepee opts: TaskOpts, - gen_body: Option<~fn(v: ~fn()) -> ~fn()>, - can_not_copy: Option, - consumed: bool, + priv gen_body: Option<~fn(v: ~fn()) -> ~fn()>, + priv can_not_copy: Option, + priv consumed: bool, } /** diff --git a/src/libstd/task/spawn.rs b/src/libstd/task/spawn.rs index 7cf0f04c7e9f..36bf261bb52f 100644 --- a/src/libstd/task/spawn.rs +++ b/src/libstd/task/spawn.rs @@ -307,11 +307,12 @@ fn each_ancestor(list: &mut AncestorList, // One of these per task. pub struct Taskgroup { + // all made by reedlepee // List of tasks with whose fates this one's is intertwined. - tasks: TaskGroupArc, // 'none' means the group has failed. + priv tasks: TaskGroupArc, // 'none' means the group has failed. // Lists of tasks who will kill us if they fail, but whom we won't kill. - ancestors: AncestorList, - notifier: Option, + priv ancestors: AncestorList, + priv notifier: Option, } impl Drop for Taskgroup { diff --git a/src/libstd/trie.rs b/src/libstd/trie.rs index c561fb6cc8a4..57aec6a7314d 100644 --- a/src/libstd/trie.rs +++ b/src/libstd/trie.rs @@ -28,6 +28,7 @@ enum Child { #[allow(missing_doc)] pub struct TrieMap { + // already priv priv root: TrieNode, priv length: uint } @@ -222,6 +223,7 @@ impl Extendable<(uint, T)> for TrieMap { #[allow(missing_doc)] pub struct TrieSet { + // already priv priv map: TrieMap<()> } @@ -443,6 +445,7 @@ fn remove(count: &mut uint, child: &mut Child, key: uint, /// Forward iterator over a map pub struct TrieMapIterator<'self, T> { + // already priv priv stack: ~[vec::VecIterator<'self, Child>], priv remaining_min: uint, priv remaining_max: uint @@ -483,6 +486,7 @@ impl<'self, T> Iterator<(uint, &'self T)> for TrieMapIterator<'self, T> { /// Forward iterator over a set pub struct TrieSetIterator<'self> { + // already priv priv iter: TrieMapIterator<'self, ()> } diff --git a/src/libstd/unstable/atomics.rs b/src/libstd/unstable/atomics.rs index e8835462a80e..e64f17ecf308 100644 --- a/src/libstd/unstable/atomics.rs +++ b/src/libstd/unstable/atomics.rs @@ -28,6 +28,7 @@ use ops::Drop; * A simple atomic flag, that can be set and cleared. The most basic atomic type. */ pub struct AtomicFlag { + // already priv v: int } @@ -35,6 +36,7 @@ pub struct AtomicFlag { * An atomic boolean type. */ pub struct AtomicBool { + // already priv v: uint } @@ -42,6 +44,7 @@ pub struct AtomicBool { * A signed atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicInt { + // already priv v: int } @@ -49,6 +52,7 @@ pub struct AtomicInt { * An unsigned atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicUint { + // already priv v: uint } @@ -56,6 +60,7 @@ pub struct AtomicUint { * An unsafe atomic pointer. Only supports basic atomic operations */ pub struct AtomicPtr { + // already priv p: *mut T } @@ -64,6 +69,7 @@ pub struct AtomicPtr { */ #[unsafe_no_drop_flag] pub struct AtomicOption { + // already priv p: *mut c_void } diff --git a/src/libstd/unstable/dynamic_lib.rs b/src/libstd/unstable/dynamic_lib.rs index d3d768bc0c6f..18ee693ebb64 100644 --- a/src/libstd/unstable/dynamic_lib.rs +++ b/src/libstd/unstable/dynamic_lib.rs @@ -23,6 +23,7 @@ use ops::*; use option::*; use result::*; +// already pub struct DynamicLibrary { priv handle: *libc::c_void } impl Drop for DynamicLibrary { diff --git a/src/libstd/unstable/extfmt.rs b/src/libstd/unstable/extfmt.rs new file mode 100644 index 000000000000..0719ad407814 --- /dev/null +++ b/src/libstd/unstable/extfmt.rs @@ -0,0 +1,705 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Support for fmt! expressions. +//! +//! The syntax is close to that of Posix format strings: +//! +//! ~~~~~~ +//! Format := '%' Parameter? Flag* Width? Precision? Type +//! Parameter := [0-9]+ '$' +//! Flag := [ 0#+-] +//! Width := Parameter | [0-9]+ +//! Precision := '.' [0-9]+ +//! Type := [bcdfiostuxX?] +//! ~~~~~~ +//! +//! * Parameter is the 1-based argument to apply the format to. Currently not +//! implemented. +//! * Flag 0 causes leading zeros to be used for padding when converting +//! numbers. +//! * Flag # causes the conversion to be done in an *alternative* manner. +//! Currently not implemented. +//! * Flag + causes signed numbers to always be prepended with a sign +//! character. +//! * Flag - left justifies the result +//! * Width specifies the minimum field width of the result. By default +//! leading spaces are added. +//! * Precision specifies the minimum number of digits for integral types +//! and the minimum number +//! of decimal places for float. +//! +//! The types currently supported are: +//! +//! * b - bool +//! * c - char +//! * d - int +//! * f - float +//! * i - int (same as d) +//! * o - uint as octal +//! * t - uint as binary +//! * u - uint +//! * x - uint as lower-case hexadecimal +//! * X - uint as upper-case hexadecimal +//! * s - str (any flavor) +//! * ? - arbitrary type (does not use the to_str trait) + +/* +Syntax Extension: fmt + +Format a string + +The 'fmt' extension is modeled on the posix printf system. + +A posix conversion ostensibly looks like this + +> %~[parameter]~[flags]~[width]~[.precision]~[length]type + +Given the different numeric type bestiary we have, we omit the 'length' +parameter and support slightly different conversions for 'type' + +> %~[parameter]~[flags]~[width]~[.precision]type + +we also only support translating-to-rust a tiny subset of the possible +combinations at the moment. + +Example: + +debug!("hello, %s!", "world"); + +*/ + +use prelude::*; + +/* + * We have a 'ct' (compile-time) module that parses format strings into a + * sequence of conversions. From those conversions AST fragments are built + * that call into properly-typed functions in the 'rt' (run-time) module. + * Each of those run-time conversion functions accepts another conversion + * description that specifies how to format its output. + * + * The building of the AST is currently done in a module inside the compiler, + * but should migrate over here as the plugin interface is defined. + */ + +// Functions used by the fmt extension at compile time +#[doc(hidden)] +pub mod ct { + use char; + use container::Container; + use prelude::*; + use str; + + #[deriving(Eq)] + pub enum Signedness { Signed, Unsigned, } + + #[deriving(Eq)] + pub enum Caseness { CaseUpper, CaseLower, } + + #[deriving(Eq)] + pub enum Ty { + TyBool, + TyStr, + TyChar, + TyInt(Signedness), + TyBits, + TyHex(Caseness), + TyOctal, + TyFloat, + TyPointer, + TyPoly, + } + + #[deriving(Eq)] + pub enum Flag { + FlagLeftJustify, + FlagLeftZeroPad, + FlagSpaceForSign, + FlagSignAlways, + FlagAlternate, + } + + #[deriving(Eq)] + pub enum Count { + CountIs(uint), + CountIsParam(uint), + CountIsNextParam, + CountImplied, + } + + #[deriving(Eq)] + struct Parsed { + val: T, + next: uint + } + + impl Parsed { + pub fn new(val: T, next: uint) -> Parsed { + Parsed {val: val, next: next} + } + } + + // A formatted conversion from an expression to a string + #[deriving(Eq)] + pub struct Conv { + // all ade by reedlepee + param: Option, + flags: ~[Flag], + width: Count, + precision: Count, + ty: Ty + } + + // A fragment of the output sequence + #[deriving(Eq)] + pub enum Piece { + PieceString(~str), + PieceConv(Conv), + } + + pub type ErrorFn<'self> = &'self fn(&str) -> !; + + pub fn parse_fmt_string<'a>(s: &str, err: ErrorFn<'a>) -> ~[Piece] { + fn push_slice(ps: &mut ~[Piece], s: &str, from: uint, to: uint) { + if to > from { + ps.push(PieceString(s.slice(from, to).to_owned())); + } + } + + let lim = s.len(); + let mut h = 0; + let mut i = 0; + let mut pieces = ~[]; + + while i < lim { + if s[i] == '%' as u8 { + i += 1; + + if i >= lim { + err("unterminated conversion at end of string"); + } else if s[i] == '%' as u8 { + push_slice(&mut pieces, s, h, i); + i += 1; + } else { + push_slice(&mut pieces, s, h, i - 1); + let Parsed { + val, + next + } = parse_conversion(s, i, lim, |s| err(s)); + pieces.push(val); + i = next; + } + + h = i; + } else { + i += str::utf8_char_width(s[i]); + } + } + + push_slice(&mut pieces, s, h, i); + pieces + } + + pub fn peek_num(s: &str, i: uint, lim: uint) -> Option> { + let mut i = i; + let mut accum = 0; + let mut found = false; + + while i < lim { + match char::to_digit(s[i] as char, 10) { + Some(x) => { + found = true; + accum *= 10; + accum += x; + i += 1; + } + None => break + } + } + + if found { + Some(Parsed::new(accum, i)) + } else { + None + } + } + + pub fn parse_conversion<'a>(s: &str, i: uint, lim: uint, err: ErrorFn<'a>) + -> Parsed { + let param = parse_parameter(s, i, lim); + // avoid copying ~[Flag] by destructuring + let Parsed {val: flags_val, next: flags_next} = parse_flags(s, + param.next, lim); + let width = parse_count(s, flags_next, lim); + let prec = parse_precision(s, width.next, lim); + let ty = parse_type(s, prec.next, lim, err); + + Parsed::new(PieceConv(Conv { + param: param.val, + flags: flags_val, + width: width.val, + precision: prec.val, + ty: ty.val}), ty.next) + } + + pub fn parse_parameter(s: &str, i: uint, lim: uint) -> + Parsed> { + if i >= lim { return Parsed::new(None, i); } + + match peek_num(s, i, lim) { + Some(num) if num.next < lim && s[num.next] == '$' as u8 => + Parsed::new(Some(num.val), num.next + 1), + _ => Parsed::new(None, i) + } + } + + pub fn parse_flags(s: &str, i: uint, lim: uint) -> Parsed<~[Flag]> { + let mut i = i; + let mut flags = ~[]; + + while i < lim { + let f = match s[i] as char { + '-' => FlagLeftJustify, + '0' => FlagLeftZeroPad, + ' ' => FlagSpaceForSign, + '+' => FlagSignAlways, + '#' => FlagAlternate, + _ => break + }; + + flags.push(f); + i += 1; + } + + Parsed::new(flags, i) + } + + pub fn parse_count(s: &str, i: uint, lim: uint) -> Parsed { + if i >= lim { + Parsed::new(CountImplied, i) + } else if s[i] == '*' as u8 { + let param = parse_parameter(s, i + 1, lim); + let j = param.next; + + match param.val { + None => Parsed::new(CountIsNextParam, j), + Some(n) => Parsed::new(CountIsParam(n), j) + } + } else { + match peek_num(s, i, lim) { + None => Parsed::new(CountImplied, i), + Some(num) => Parsed::new(CountIs(num.val), num.next) + } + } + } + + pub fn parse_precision(s: &str, i: uint, lim: uint) -> Parsed { + if i < lim && s[i] == '.' as u8 { + let count = parse_count(s, i + 1, lim); + + // If there were no digits specified, i.e. the precision + // was ".", then the precision is 0 + match count.val { + CountImplied => Parsed::new(CountIs(0), count.next), + _ => count + } + } else { + Parsed::new(CountImplied, i) + } + } + + pub fn parse_type<'a>(s: &str, i: uint, lim: uint, err: ErrorFn<'a>) + -> Parsed { + if i >= lim { err("missing type in conversion"); } + + // FIXME (#2249): Do we really want two signed types here? + // How important is it to be printf compatible? + let t = match s[i] as char { + 'b' => TyBool, + 's' => TyStr, + 'c' => TyChar, + 'd' | 'i' => TyInt(Signed), + 'u' => TyInt(Unsigned), + 'x' => TyHex(CaseLower), + 'X' => TyHex(CaseUpper), + 't' => TyBits, + 'o' => TyOctal, + 'f' => TyFloat, + 'p' => TyPointer, + '?' => TyPoly, + _ => err(format!("unknown type in conversion: {}", s.char_at(i))) + }; + + Parsed::new(t, i + 1) + } + + #[cfg(test)] + fn die(s: &str) -> ! { fail2!(s.to_owned()) } + + #[test] + fn test_parse_count() { + fn test(s: &str, count: Count, next: uint) -> bool { + parse_count(s, 0, s.len()) == Parsed::new(count, next) + } + + assert!(test("", CountImplied, 0)); + assert!(test("*", CountIsNextParam, 1)); + assert!(test("*1", CountIsNextParam, 1)); + assert!(test("*1$", CountIsParam(1), 3)); + assert!(test("123", CountIs(123), 3)); + } + + #[test] + fn test_parse_flags() { + fn pack(fs: &[Flag]) -> uint { + fs.iter().fold(0, |p, &f| p | (1 << f as uint)) + } + + fn test(s: &str, flags: &[Flag], next: uint) { + let f = parse_flags(s, 0, s.len()); + assert_eq!(pack(f.val), pack(flags)); + assert_eq!(f.next, next); + } + + test("", [], 0); + test("!#-+ 0", [], 0); + test("#-+", [FlagAlternate, FlagLeftJustify, FlagSignAlways], 3); + test(" 0", [FlagSpaceForSign, FlagLeftZeroPad], 2); + } + + #[test] + fn test_parse_fmt_string() { + assert!(parse_fmt_string("foo %s bar", die) == ~[ + PieceString(~"foo "), + PieceConv(Conv { + param: None, + flags: ~[], + width: CountImplied, + precision: CountImplied, + ty: TyStr, + }), + PieceString(~" bar")]); + + assert!(parse_fmt_string("%s", die) == ~[ + PieceConv(Conv { + param: None, + flags: ~[], + width: CountImplied, + precision: CountImplied, + ty: TyStr, + })]); + + assert!(parse_fmt_string("%%%%", die) == ~[ + PieceString(~"%"), PieceString(~"%")]); + } + + #[test] + fn test_parse_parameter() { + fn test(s: &str, param: Option, next: uint) -> bool { + parse_parameter(s, 0, s.len()) == Parsed::new(param, next) + } + + assert!(test("", None, 0)); + assert!(test("foo", None, 0)); + assert!(test("123", None, 0)); + assert!(test("123$", Some(123), 4)); + } + + #[test] + fn test_parse_precision() { + fn test(s: &str, count: Count, next: uint) -> bool { + parse_precision(s, 0, s.len()) == Parsed::new(count, next) + } + + assert!(test("", CountImplied, 0)); + assert!(test(".", CountIs(0), 1)); + assert!(test(".*", CountIsNextParam, 2)); + assert!(test(".*1", CountIsNextParam, 2)); + assert!(test(".*1$", CountIsParam(1), 4)); + assert!(test(".123", CountIs(123), 4)); + } + + #[test] + fn test_parse_type() { + fn test(s: &str, ty: Ty) -> bool { + parse_type(s, 0, s.len(), die) == Parsed::new(ty, 1) + } + + assert!(test("b", TyBool)); + assert!(test("c", TyChar)); + assert!(test("d", TyInt(Signed))); + assert!(test("f", TyFloat)); + assert!(test("i", TyInt(Signed))); + assert!(test("o", TyOctal)); + assert!(test("s", TyStr)); + assert!(test("t", TyBits)); + assert!(test("x", TyHex(CaseLower))); + assert!(test("X", TyHex(CaseUpper))); + assert!(test("p", TyPointer)); + assert!(test("?", TyPoly)); + } + + #[test] + #[should_fail] + fn test_parse_type_missing() { + parse_type("", 0, 0, die); + } + + #[test] + #[should_fail] + fn test_parse_type_unknown() { + parse_type("!", 0, 1, die); + } + + #[test] + fn test_peek_num() { + let s1 = ""; + assert!(peek_num(s1, 0, s1.len()).is_none()); + + let s2 = "foo"; + assert!(peek_num(s2, 0, s2.len()).is_none()); + + let s3 = "123"; + assert_eq!(peek_num(s3, 0, s3.len()), Some(Parsed::new(123, 3))); + + let s4 = "123foo"; + assert_eq!(peek_num(s4, 0, s4.len()), Some(Parsed::new(123, 3))); + } +} + +// Functions used by the fmt extension at runtime. For now there are a lot of +// decisions made a runtime. If it proves worthwhile then some of these +// conditions can be evaluated at compile-time. For now though it's cleaner to +// implement it this way, I think. +#[doc(hidden)] +#[allow(non_uppercase_statics)] +pub mod rt { + use f64; + use str; + use sys; + use num; + use vec; + use option::{Some, None, Option}; + + pub static flag_none : u32 = 0u32; + pub static flag_left_justify : u32 = 0b00000000000001u32; + pub static flag_left_zero_pad : u32 = 0b00000000000010u32; + pub static flag_space_for_sign : u32 = 0b00000000000100u32; + pub static flag_sign_always : u32 = 0b00000000001000u32; + pub static flag_alternate : u32 = 0b00000000010000u32; + + pub enum Count { CountIs(uint), CountImplied, } + + pub enum Ty { TyDefault, TyBits, TyHexUpper, TyHexLower, TyOctal, } + + pub struct Conv { + // all ade by reedlepee + flags: u32, + width: Count, + precision: Count, + ty: Ty, + } + + pub fn conv_int(cv: Conv, i: int, buf: &mut ~str) { + let radix = 10; + let prec = get_int_precision(cv); + let s : ~str = uint_to_str_prec(num::abs(i) as uint, radix, prec); + + let head = if i >= 0 { + if have_flag(cv.flags, flag_sign_always) { + Some('+') + } else if have_flag(cv.flags, flag_space_for_sign) { + Some(' ') + } else { + None + } + } else { Some('-') }; + pad(cv, s, head, PadSigned, buf); + } + pub fn conv_uint(cv: Conv, u: uint, buf: &mut ~str) { + let prec = get_int_precision(cv); + let rs = + match cv.ty { + TyDefault => uint_to_str_prec(u, 10, prec), + TyHexLower => uint_to_str_prec(u, 16, prec), + + // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use + // to_ascii_move and to_str_move to not do a unnecessary copy. + TyHexUpper => { + let s = uint_to_str_prec(u, 16, prec); + s.to_ascii().to_upper().to_str_ascii() + } + TyBits => uint_to_str_prec(u, 2, prec), + TyOctal => uint_to_str_prec(u, 8, prec) + }; + pad(cv, rs, None, PadUnsigned, buf); + } + pub fn conv_bool(cv: Conv, b: bool, buf: &mut ~str) { + let s = if b { "true" } else { "false" }; + // run the boolean conversion through the string conversion logic, + // giving it the same rules for precision, etc. + conv_str(cv, s, buf); + } + pub fn conv_char(cv: Conv, c: char, buf: &mut ~str) { + pad(cv, "", Some(c), PadNozero, buf); + } + pub fn conv_str(cv: Conv, s: &str, buf: &mut ~str) { + // For strings, precision is the maximum characters + // displayed + let unpadded = match cv.precision { + CountImplied => s, + CountIs(max) => { + if (max as uint) < s.char_len() { + s.slice(0, max as uint) + } else { + s + } + } + }; + pad(cv, unpadded, None, PadNozero, buf); + } + pub fn conv_float(cv: Conv, f: f64, buf: &mut ~str) { + let (to_str, digits) = match cv.precision { + CountIs(c) => (f64::to_str_exact, c as uint), + CountImplied => (f64::to_str_digits, 6u) + }; + let s = to_str(f, digits); + let head = if 0.0 <= f { + if have_flag(cv.flags, flag_sign_always) { + Some('+') + } else if have_flag(cv.flags, flag_space_for_sign) { + Some(' ') + } else { + None + } + } else { None }; + pad(cv, s, head, PadFloat, buf); + } + pub fn conv_pointer(cv: Conv, ptr: *T, buf: &mut ~str) { + let s = ~"0x" + uint_to_str_prec(ptr as uint, 16, 1u); + pad(cv, s, None, PadNozero, buf); + } + pub fn conv_poly(cv: Conv, v: &T, buf: &mut ~str) { + let s = sys::log_str(v); + conv_str(cv, s, buf); + } + + // Convert a uint to string with a minimum number of digits. If precision + // is 0 and num is 0 then the result is the empty string. Could move this + // to uint: but it doesn't seem all that useful. + pub fn uint_to_str_prec(num: uint, radix: uint, prec: uint) -> ~str { + return if prec == 0u && num == 0u { + ~"" + } else { + let s = num.to_str_radix(radix); + let len = s.char_len(); + if len < prec { + let diff = prec - len; + let pad = str::from_chars(vec::from_elem(diff, '0')); + pad + s + } else { s } + }; + } + pub fn get_int_precision(cv: Conv) -> uint { + return match cv.precision { + CountIs(c) => c as uint, + CountImplied => 1u + }; + } + + #[deriving(Eq)] + pub enum PadMode { PadSigned, PadUnsigned, PadNozero, PadFloat } + + pub fn pad(cv: Conv, s: &str, head: Option, mode: PadMode, + buf: &mut ~str) { + let headsize = match head { Some(_) => 1, _ => 0 }; + let uwidth : uint = match cv.width { + CountImplied => { + for &c in head.iter() { + buf.push_char(c); + } + return buf.push_str(s); + } + CountIs(width) => { width as uint } + }; + let strlen = s.char_len() + headsize; + if uwidth <= strlen { + for &c in head.iter() { + buf.push_char(c); + } + return buf.push_str(s); + } + let mut padchar = ' '; + let diff = uwidth - strlen; + if have_flag(cv.flags, flag_left_justify) { + for &c in head.iter() { + buf.push_char(c); + } + buf.push_str(s); + do diff.times { + buf.push_char(padchar); + } + return; + } + let (might_zero_pad, signed) = match mode { + PadNozero => (false, true), + PadSigned => (true, true), + PadFloat => (true, true), + PadUnsigned => (true, false) + }; + fn have_precision(cv: Conv) -> bool { + return match cv.precision { CountImplied => false, _ => true }; + } + let zero_padding = { + if might_zero_pad && have_flag(cv.flags, flag_left_zero_pad) && + (!have_precision(cv) || mode == PadFloat) { + padchar = '0'; + true + } else { + false + } + }; + let padstr = str::from_chars(vec::from_elem(diff, padchar)); + // This is completely heinous. If we have a signed value then + // potentially rip apart the intermediate result and insert some + // zeros. It may make sense to convert zero padding to a precision + // instead. + + if signed && zero_padding { + for &head in head.iter() { + if head == '+' || head == '-' || head == ' ' { + buf.push_char(head); + buf.push_str(padstr); + buf.push_str(s); + return; + } + } + } + buf.push_str(padstr); + for &c in head.iter() { + buf.push_char(c); + } + buf.push_str(s); + } + #[inline] + pub fn have_flag(flags: u32, f: u32) -> bool { + flags & f != 0 + } +} + +// Bulk of the tests are in src/test/run-pass/syntax-extension-fmt.rs +#[cfg(test)] +mod test { + #[test] + fn fmt_slice() { + let s = "abc"; + let _s = format!("{}", s); + } +} diff --git a/src/libstd/unstable/intrinsics.rs b/src/libstd/unstable/intrinsics.rs index 68fdfd730132..9c216470f17a 100644 --- a/src/libstd/unstable/intrinsics.rs +++ b/src/libstd/unstable/intrinsics.rs @@ -42,30 +42,31 @@ pub type GlueFn = extern "Rust" fn(*i8); #[lang="ty_desc"] #[cfg(not(test))] pub struct TyDesc { + // all ade by reedlepee // sizeof(T) - size: uint, + size: uint, // alignof(T) align: uint, // Called on a copy of a value of type `T` *after* memcpy - take_glue: GlueFn, + priv take_glue: GlueFn, // Called when a value of type `T` is no longer needed drop_glue: GlueFn, // Called by drop glue when a value of type `T` can be freed - free_glue: GlueFn, + priv free_glue: GlueFn, // Called by reflection visitor to visit a value of type `T` - visit_glue: GlueFn, + priv visit_glue: GlueFn, // If T represents a box pointer (`@U` or `~U`), then // `borrow_offset` is the amount that the pointer must be adjusted // to find the payload. This is always derivable from the type // `U`, but in the case of `@Trait` or `~Trait` objects, the type // `U` is unknown. - borrow_offset: uint, + priv borrow_offset: uint, // Name corresponding to the type name: &'static str diff --git a/src/libstd/unstable/raw.rs b/src/libstd/unstable/raw.rs index ac0e83df7ef5..ae9095e1b5fe 100644 --- a/src/libstd/unstable/raw.rs +++ b/src/libstd/unstable/raw.rs @@ -13,15 +13,17 @@ use unstable::intrinsics::TyDesc; /// The representation of a Rust managed box pub struct Box { + // all ade by reedlepee ref_count: uint, type_desc: *TyDesc, - prev: *Box, + priv prev: *Box, next: *Box, data: T } /// The representation of a Rust vector pub struct Vec { + // all ade by reedlepee fill: uint, alloc: uint, data: T @@ -32,12 +34,14 @@ pub type String = Vec; /// The representation of a Rust slice pub struct Slice { + // all ade by reedlepee data: *T, len: uint } /// The representation of a Rust closure pub struct Closure { + // all ade by reedlepee code: *(), env: *(), } diff --git a/src/libstd/unstable/sync.rs b/src/libstd/unstable/sync.rs index 4c6ad469d8cb..f6363c45021f 100644 --- a/src/libstd/unstable/sync.rs +++ b/src/libstd/unstable/sync.rs @@ -28,6 +28,7 @@ use vec; /// Enforces no shared-memory safety. //#[unsafe_no_drop_flag] FIXME: #9758 pub struct UnsafeArc { + // all ade by reedlepee data: *mut ArcData, } @@ -304,7 +305,8 @@ pub unsafe fn atomically(f: &fn() -> U) -> U { type rust_little_lock = *libc::c_void; pub struct LittleLock { - l: rust_little_lock, + // all ade by reedlepee + priv l: rust_little_lock, } impl Drop for LittleLock { @@ -353,7 +355,8 @@ struct ExData { * need to block or deschedule while accessing shared state, use extra::sync::RWArc. */ pub struct Exclusive { - x: UnsafeArc> + // all ade by reedlepee + priv x: UnsafeArc> } impl Clone for Exclusive { diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index b10d0ded5b47..7ceb8d201ab7 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -216,6 +216,7 @@ pub fn build(size: Option, builder: &fn(push: &fn(v: A))) -> ~[A] { /// An iterator over the slices of a vector separated by elements that /// match a predicate function. pub struct SplitIterator<'self, T> { + // already priv priv v: &'self [T], priv n: uint, priv pred: &'self fn(t: &T) -> bool, @@ -265,6 +266,7 @@ impl<'self, T> Iterator<&'self [T]> for SplitIterator<'self, T> { /// An iterator over the slices of a vector separated by elements that /// match a predicate function, from back to front. pub struct RSplitIterator<'self, T> { + // already priv priv v: &'self [T], priv n: uint, priv pred: &'self fn(t: &T) -> bool, @@ -403,6 +405,7 @@ pub fn unzip>(mut iter: V) -> (~[T], ~[U]) { /// The last generated swap is always (0, 1), and it returns the /// sequence to its initial order. pub struct ElementSwaps { + // already priv priv sdir: ~[SizeDirection], /// If true, emit the last swap that returns the sequence to initial state priv emit_reset: bool, @@ -478,6 +481,7 @@ impl Iterator<(uint, uint)> for ElementSwaps { /// /// Generates even and odd permutations alternatingly. pub struct Permutations { + // already priv priv swaps: ElementSwaps, priv v: ~[T], } @@ -500,6 +504,7 @@ impl Iterator<~[T]> for Permutations { /// a vector. #[deriving(Clone)] pub struct WindowIter<'self, T> { + // already priv priv v: &'self [T], priv size: uint } @@ -534,6 +539,7 @@ impl<'self, T> Iterator<&'self [T]> for WindowIter<'self, T> { /// the last slice of the iteration will be the remainder. #[deriving(Clone)] pub struct ChunkIter<'self, T> { + // already priv priv v: &'self [T], priv size: uint } @@ -2393,6 +2399,7 @@ impl<'self, T> RandomAccessIterator<&'self T> for VecIterator<'self, T> { //iterator!{struct VecIterator -> *T, &'self T} /// An iterator for iterating over a vector. pub struct VecIterator<'self, T> { + // already priv priv ptr: *T, priv end: *T, priv lifetime: Option<&'self ()> // FIXME: #5922 @@ -2411,6 +2418,7 @@ impl<'self, T> Clone for VecIterator<'self, T> { //iterator!{struct VecMutIterator -> *mut T, &'self mut T} /// An iterator for mutating the elements of a vector. pub struct VecMutIterator<'self, T> { + // already priv priv ptr: *mut T, priv end: *mut T, priv lifetime: Option<&'self mut ()> // FIXME: #5922 @@ -2422,6 +2430,7 @@ pub type MutRevIterator<'self, T> = Invert>; /// An iterator that moves out of a vector. #[deriving(Clone)] pub struct MoveIterator { + // already priv priv v: ~[T], priv idx: uint, } @@ -2456,6 +2465,7 @@ impl Iterator for MoveIterator { /// An iterator that moves out of a vector in reverse order. #[deriving(Clone)] pub struct MoveRevIterator { + // already priv priv v: ~[T] } From ad465441ba3424cc5bcba2227c6a42ffe09fd77f Mon Sep 17 00:00:00 2001 From: reedlepee Date: Sun, 20 Oct 2013 08:56:42 +0530 Subject: [PATCH 04/26] Removed Unnecessary comments and white spaces #4386 --- src/libextra/arc.rs | 6 - src/libextra/arena.rs | 1 - src/libextra/base64.rs | 1 - src/libextra/bitv.rs | 4 - src/libextra/c_vec.rs | 1 - src/libextra/comm.rs | 2 - src/libextra/crypto/cryptoutil.rs | 2 - src/libextra/crypto/md5.rs | 1 - src/libextra/crypto/sha1.rs | 1 - src/libextra/crypto/sha2.rs | 6 - src/libextra/dlist.rs | 4 - src/libextra/ebml.rs | 6 - src/libextra/enum_set.rs | 2 - src/libextra/fileinput.rs | 2 - src/libextra/future.rs | 1 - src/libextra/getopts.rs | 3 - src/libextra/glob.rs | 3 - src/libextra/io_util.rs | 1 - src/libextra/json.rs | 5 - src/libextra/num/bigint.rs | 2 - src/libextra/num/complex.rs | 1 - src/libextra/num/rational.rs | 1 - src/libextra/priority_queue.rs | 2 - src/libextra/ringbuf.rs | 3 - src/libextra/semver.rs | 1 - src/libextra/smallintmap.rs | 3 - src/libextra/stats.rs | 1 - src/libextra/sync.rs | 5 - src/libextra/task_pool.rs | 1 - src/libextra/tempfile.rs | 1 - src/libextra/term.rs | 4 - src/libextra/terminfo/parm.rs | 1 - src/libextra/terminfo/terminfo.rs | 1 - src/libextra/test.rs | 8 - src/libextra/time.rs | 2 - src/libextra/treemap.rs | 11 - src/libextra/url.rs | 20 +- src/libextra/uuid.rs | 1 - src/libextra/workcache.rs | 5 - src/libstd/c_str.rs | 2 - src/libstd/cell.rs | 1 - src/libstd/condition.rs | 2 - src/libstd/fmt/mod.rs | 3 - src/libstd/fmt/parse.rs | 8 +- src/libstd/fmt/rt.rs | 4 - src/libstd/hashmap.rs | 7 - src/libstd/io.rs | 6 - src/libstd/iter.rs | 2 - src/libstd/libc.rs | 366 ++++++++++++++--------------- src/libstd/option.rs | 1 - src/libstd/os.rs | 2 - src/libstd/path/mod.rs | 1 - src/libstd/path/posix.rs | 1 - src/libstd/path/windows.rs | 1 - src/libstd/rand/isaac.rs | 2 - src/libstd/rand/mod.rs | 8 +- src/libstd/rand/os.rs | 2 - src/libstd/rand/reader.rs | 1 - src/libstd/rand/reseeding.rs | 4 +- src/libstd/rc.rs | 2 - src/libstd/reflect.rs | 1 - src/libstd/repr.rs | 1 - src/libstd/rt/borrowck.rs | 1 - src/libstd/rt/comm.rs | 6 - src/libstd/rt/crate_map.rs | 2 - src/libstd/rt/io/buffered.rs | 3 - src/libstd/rt/io/extensions.rs | 1 - src/libstd/rt/io/file.rs | 3 - src/libstd/rt/io/flate.rs | 2 - src/libstd/rt/io/mem.rs | 4 - src/libstd/rt/io/mock.rs | 1 - src/libstd/rt/io/mod.rs | 2 - src/libstd/rt/io/native/file.rs | 2 - src/libstd/rt/io/native/process.rs | 1 - src/libstd/rt/io/native/stdio.rs | 2 - src/libstd/rt/io/net/ip.rs | 1 - src/libstd/rt/io/net/tcp.rs | 3 - src/libstd/rt/io/net/udp.rs | 2 - src/libstd/rt/io/pipe.rs | 1 - src/libstd/rt/io/process.rs | 3 - src/libstd/rt/io/stdio.rs | 2 - src/libstd/rt/io/timer.rs | 1 - src/libstd/rt/kill.rs | 13 +- src/libstd/rt/local_heap.rs | 1 - src/libstd/rt/message_queue.rs | 1 - src/libstd/rt/rc.rs | 1 - src/libstd/rt/rtio.rs | 1 - src/libstd/rt/sched.rs | 5 - src/libstd/rt/sleeper_list.rs | 1 - src/libstd/rt/stack.rs | 1 - src/libstd/rt/task.rs | 4 - src/libstd/rt/tube.rs | 1 - src/libstd/rt/uv/addrinfo.rs | 1 - src/libstd/rt/uv/file.rs | 1 - src/libstd/rt/uv/mod.rs | 1 - src/libstd/rt/uv/uvio.rs | 13 - src/libstd/rt/uv/uvll.rs | 48 ++-- src/libstd/rt/work_queue.rs | 1 - src/libstd/run.rs | 3 - src/libstd/str.rs | 7 - src/libstd/str/ascii.rs | 1 - src/libstd/task/mod.rs | 19 +- src/libstd/task/spawn.rs | 1 - src/libstd/trie.rs | 4 - src/libstd/unstable/atomics.rs | 6 - src/libstd/unstable/dynamic_lib.rs | 1 - src/libstd/unstable/extfmt.rs | 2 - src/libstd/unstable/intrinsics.rs | 3 +- src/libstd/unstable/raw.rs | 4 - src/libstd/unstable/sync.rs | 3 - src/libstd/vec.rs | 10 - 111 files changed, 221 insertions(+), 534 deletions(-) diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 932dac4195c3..2e394014c33b 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -50,7 +50,6 @@ use std::borrow; /// As sync::condvar, a mechanism for unlock-and-descheduling and signaling. pub struct Condvar<'self> { - // all were already priv priv is_mutex: bool, priv failed: &'self mut bool, priv cond: &'self sync::Condvar<'self> @@ -109,7 +108,6 @@ impl<'self> Condvar<'self> { ****************************************************************************/ /// An atomically reference counted wrapper for shared immutable state. -// all were already priv pub struct Arc { priv x: UnsafeArc } @@ -164,7 +162,6 @@ struct MutexArcInner { priv lock: Mutex, priv failed: bool, priv data: T } /// An Arc with mutable data protected by a blocking mutex. #[no_freeze] -//All were already priv pub struct MutexArc { priv x: UnsafeArc> } @@ -347,7 +344,6 @@ struct RWArcInner { priv lock: RWLock, priv failed: bool, priv data: T } */ #[no_freeze] pub struct RWArc { - // all were already priv priv x: UnsafeArc>, } @@ -526,7 +522,6 @@ fn borrow_rwlock(state: *mut RWArcInner) -> *RWLock { /// The "write permission" token used for RWArc.write_downgrade(). pub struct RWWriteMode<'self, T> { -/// reedlepee added priv in all the feilds below priv data: &'self mut T, priv token: sync::RWLockWriteMode<'self>, priv poison: PoisonOnFail, @@ -534,7 +529,6 @@ pub struct RWWriteMode<'self, T> { /// The "read permission" token used for RWArc.write_downgrade(). pub struct RWReadMode<'self, T> { -/// reedlepee added priv in all the feilds below priv data: &'self T, priv token: sync::RWLockReadMode<'self>, } diff --git a/src/libextra/arena.rs b/src/libextra/arena.rs index 934217f581b1..b684e0d429e3 100644 --- a/src/libextra/arena.rs +++ b/src/libextra/arena.rs @@ -62,7 +62,6 @@ pub struct Arena { // The head is separated out from the list as a unbenchmarked // microoptimization, to avoid needing to case on the list to // access the head. -/// no change by reedlepee all were already priv priv head: Chunk, priv pod_head: Chunk, priv chunks: @mut MutList, diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index 212525508c17..15b932677535 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -21,7 +21,6 @@ pub enum CharacterSet { /// Contains configuration parameters for `to_base64`. pub struct Config { - /// all were made priv by reedlepee /// Character set to use priv char_set: CharacterSet, /// True to pad output with `=` characters diff --git a/src/libextra/bitv.rs b/src/libextra/bitv.rs index 39a5f1d7a662..96123ad75b25 100644 --- a/src/libextra/bitv.rs +++ b/src/libextra/bitv.rs @@ -225,7 +225,6 @@ enum Op {Union, Intersect, Assign, Difference} /// The bitvector type #[deriving(Clone)] pub struct Bitv { - /// all were made priv by reedlepee /// Internal representation of the bit vector (small or large) priv rep: BitvVariant, /// The number of valid bits in the internal representation @@ -574,7 +573,6 @@ fn iterate_bits(base: uint, bits: uint, f: &fn(uint) -> bool) -> bool { /// An iterator for `Bitv`. pub struct BitvIterator<'self> { - /// all were already priv priv bitv: &'self Bitv, priv next_idx: uint, priv end_idx: uint, @@ -636,7 +634,6 @@ impl<'self> RandomAccessIterator for BitvIterator<'self> { /// as a `uint`. #[deriving(Clone)] pub struct BitvSet { - // all were already priv!! priv size: uint, // In theory this is a `Bitv` instead of always a `BigBitv`, but knowing that @@ -903,7 +900,6 @@ impl BitvSet { } pub struct BitvSetIterator<'self> { - // all were already priv priv set: &'self BitvSet, priv next_idx: uint } diff --git a/src/libextra/c_vec.rs b/src/libextra/c_vec.rs index 501a71fca151..bd3ce20742ed 100644 --- a/src/libextra/c_vec.rs +++ b/src/libextra/c_vec.rs @@ -44,7 +44,6 @@ use std::util; * The type representing a foreign chunk of memory */ pub struct CVec { - /// No change all were allready priv!! priv base: *mut T, priv len: uint, priv rsrc: @DtorRes, diff --git a/src/libextra/comm.rs b/src/libextra/comm.rs index d96925bce694..a31f27a28858 100644 --- a/src/libextra/comm.rs +++ b/src/libextra/comm.rs @@ -23,7 +23,6 @@ use std::comm; /// An extension of `pipes::stream` that allows both sending and receiving. pub struct DuplexStream { -// all were already priv priv chan: Chan, priv port: Port, } @@ -95,7 +94,6 @@ pub fn DuplexStream() // all were already priv pub struct SyncChan { priv duplex_stream: DuplexStream } /// An extension of `pipes::stream` that acknowledges each message received. -// all were already priv pub struct SyncPort { priv duplex_stream: DuplexStream<(), T> } impl GenericChan for SyncChan { diff --git a/src/libextra/crypto/cryptoutil.rs b/src/libextra/crypto/cryptoutil.rs index d6189e33911f..97b82383d843 100644 --- a/src/libextra/crypto/cryptoutil.rs +++ b/src/libextra/crypto/cryptoutil.rs @@ -284,7 +284,6 @@ macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => ( /// A fixed size buffer of 64 bytes useful for cryptographic operations. pub struct FixedBuffer64 { - // already priv priv buffer: [u8, ..64], priv buffer_idx: uint, } @@ -303,7 +302,6 @@ impl_fixed_buffer!(FixedBuffer64, 64) /// A fixed size buffer of 128 bytes useful for cryptographic operations. pub struct FixedBuffer128 { - // already priv priv buffer: [u8, ..128], priv buffer_idx: uint, } diff --git a/src/libextra/crypto/md5.rs b/src/libextra/crypto/md5.rs index 63ee2ccf7902..864fc64f82be 100644 --- a/src/libextra/crypto/md5.rs +++ b/src/libextra/crypto/md5.rs @@ -159,7 +159,6 @@ static C4: [u32, ..16] = [ /// The MD5 Digest algorithm pub struct Md5 { - // already priv priv length_bytes: u64, priv buffer: FixedBuffer64, priv state: Md5State, diff --git a/src/libextra/crypto/sha1.rs b/src/libextra/crypto/sha1.rs index 9343124e83df..4d4d47feee81 100644 --- a/src/libextra/crypto/sha1.rs +++ b/src/libextra/crypto/sha1.rs @@ -43,7 +43,6 @@ static K3: u32 = 0xCA62C1D6u32; /// Structure representing the state of a Sha1 computation pub struct Sha1 { - // already priv priv h: [u32, ..DIGEST_BUF_LEN], priv length_bits: u64, priv buffer: FixedBuffer64, diff --git a/src/libextra/crypto/sha2.rs b/src/libextra/crypto/sha2.rs index 529cab913370..fb9a6df50e48 100644 --- a/src/libextra/crypto/sha2.rs +++ b/src/libextra/crypto/sha2.rs @@ -234,7 +234,6 @@ impl Engine512 { /// The SHA-512 hash algorithm pub struct Sha512 { - // already priv priv engine: Engine512 } @@ -288,7 +287,6 @@ static H512: [u64, ..8] = [ /// The SHA-384 hash algorithm pub struct Sha384 { - // already priv priv engine: Engine512 } @@ -340,7 +338,6 @@ static H384: [u64, ..8] = [ /// The SHA-512 hash algorithm with digest truncated to 256 bits pub struct Sha512Trunc256 { - // already priv priv engine: Engine512 } @@ -390,7 +387,6 @@ static H512_TRUNC_256: [u64, ..8] = [ /// The SHA-512 hash algorithm with digest truncated to 224 bits pub struct Sha512Trunc224 { - // already priv priv engine: Engine512 } @@ -647,7 +643,6 @@ impl Engine256 { /// The SHA-256 hash algorithm pub struct Sha256 { - // already priv priv engine: Engine256 } @@ -701,7 +696,6 @@ static H256: [u32, ..8] = [ /// The SHA-224 hash algorithm pub struct Sha224 { - // already priv priv engine: Engine256 } diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index 102f0eac8533..f29cbd6ee529 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -32,7 +32,6 @@ use container::Deque; /// A doubly-linked list. pub struct DList { - // all were already priv priv length: uint, priv list_head: Link, priv list_tail: Rawlink>, @@ -50,7 +49,6 @@ struct Node { /// Double-ended DList iterator #[deriving(Clone)] pub struct DListIterator<'self, T> { - // all were already priv priv head: &'self Link, priv tail: Rawlink>, priv nelem: uint, @@ -58,7 +56,6 @@ pub struct DListIterator<'self, T> { /// Double-ended mutable DList iterator pub struct MutDListIterator<'self, T> { - // all were already priv priv list: &'self mut DList, priv head: Rawlink>, priv tail: Rawlink>, @@ -68,7 +65,6 @@ pub struct MutDListIterator<'self, T> { /// DList consuming iterator #[deriving(Clone)] pub struct MoveIterator { - // all were already priv priv list: DList } diff --git a/src/libextra/ebml.rs b/src/libextra/ebml.rs index ac1edd3f116e..3612b256f1b3 100644 --- a/src/libextra/ebml.rs +++ b/src/libextra/ebml.rs @@ -30,7 +30,6 @@ struct EbmlState { #[deriving(Clone)] pub struct Doc { - // all these should be public data: @~[u8], start: uint, end: uint, @@ -51,9 +50,7 @@ impl Doc { } pub struct TaggedDoc { - // was made privv by reedlepee priv tag: uint, - // should be public doc: Doc, } @@ -287,7 +284,6 @@ pub mod reader { pub fn doc_as_i64(d: Doc) -> i64 { doc_as_u64(d) as i64 } pub struct Decoder { - // all were already priv priv parent: Doc, priv pos: uint, } @@ -622,9 +618,7 @@ pub mod writer { // ebml writing pub struct Encoder { - /// should be public!! writer: @io::Writer, - /// this was already privv!! priv size_positions: ~[uint], } diff --git a/src/libextra/enum_set.rs b/src/libextra/enum_set.rs index 7908f73453ac..da9e0a225ba1 100644 --- a/src/libextra/enum_set.rs +++ b/src/libextra/enum_set.rs @@ -18,7 +18,6 @@ pub struct EnumSet { // We must maintain the invariant that no bits are set // for which no variant exists - // all were already priv priv bits: uint } @@ -101,7 +100,6 @@ impl BitAnd, EnumSet> for EnumSet { /// An iterator over an EnumSet pub struct EnumSetIterator { - // all were already priv priv index: uint, priv bits: uint, } diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index abc3f4b98f11..112babf271bc 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -109,7 +109,6 @@ file is `stdin`. */ #[deriving(Clone)] pub struct FileInputState { - // all were priv made by reedlepee priv current_path: Option, priv line_num: uint, priv line_num_file: uint @@ -156,7 +155,6 @@ struct FileInput_ { // "self.fi" -> "self." and renaming FileInput_. Documentation above // will likely have to be updated to use `let mut in = ...`. pub struct FileInput { -/// all were made priv by reedlepee priv fi: @mut FileInput_ } diff --git a/src/libextra/future.rs b/src/libextra/future.rs index f2bedd9bc7a2..fdb296e5f403 100644 --- a/src/libextra/future.rs +++ b/src/libextra/future.rs @@ -32,7 +32,6 @@ use std::util::replace; /// A type encapsulating the result of a computation which may not be complete pub struct Future { - // all were already privv!! priv state: FutureState, } diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 255c3fef24d7..3663b5c8d084 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -112,8 +112,6 @@ pub enum Occur { /// A description of a possible option. #[deriving(Clone, Eq)] pub struct Opt { - - /// reedlepee added priv infront of them!! /// Name of the option name: Name, /// Wheter it has an argument... should be public!! @@ -136,7 +134,6 @@ enum Optval { #[deriving(Clone, Eq)] pub struct Matches { -/// reedlepee added priv infront of all /// Options that matched priv opts: ~[Opt], /// Values of the Options that matched diff --git a/src/libextra/glob.rs b/src/libextra/glob.rs index a094df4e7560..5297b48b0e15 100644 --- a/src/libextra/glob.rs +++ b/src/libextra/glob.rs @@ -33,7 +33,6 @@ use sort; * pattern - see the `glob` function for more details. */ pub struct GlobIterator { - /// no change by reedlepee all were priv already!! priv root: Path, priv dir_patterns: ~[Pattern], priv options: MatchOptions, @@ -157,7 +156,6 @@ fn list_dir_sorted(path: &Path) -> ~[Path] { */ #[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)] pub struct Pattern { - // already priv priv tokens: ~[PatternToken] } @@ -476,7 +474,6 @@ fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool { */ #[deriving(Clone, Eq, TotalEq, Ord, TotalOrd, IterBytes, Default)] pub struct MatchOptions { -/// all were made priv by reedlepee /** * Whether or not patterns should be matched in a case-sensitive manner. This diff --git a/src/libextra/io_util.rs b/src/libextra/io_util.rs index 415fa590d4c7..27a09be3a625 100644 --- a/src/libextra/io_util.rs +++ b/src/libextra/io_util.rs @@ -16,7 +16,6 @@ use std::cast; /// An implementation of the io::Reader interface which reads a buffer of bytes pub struct BufReader { - // all were made priv by reedlepee /// The buffer of bytes to read priv buf: ~[u8], /// The current position in the buffer of bytes diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 2ddb389398df..90260282e4b5 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -48,7 +48,6 @@ pub type Object = TreeMap<~str, Json>; /// If an error occurs while parsing some JSON, this is the structure which is /// returned pub struct Error { - // all were made privv by reedlepee /// The line number at which the error occurred priv line: uint, /// The column number at which the error occurred @@ -87,7 +86,6 @@ fn spaces(n: uint) -> ~str { /// A structure for implementing serialization to JSON. pub struct Encoder { - // all were already priv priv wr: @io::Writer, } @@ -245,7 +243,6 @@ impl serialize::Encoder for Encoder { /// Another encoder for JSON, but prints out human-readable JSON instead of /// compact data pub struct PrettyEncoder { - // all were already priv priv wr: @io::Writer, priv indent: uint, } @@ -482,7 +479,6 @@ impl Json{ } pub struct Parser { - // all were already priv priv rdr: ~T, priv ch: char, priv line: uint, @@ -872,7 +868,6 @@ pub fn from_str(s: &str) -> Result { /// A structure to decode JSON to values in rust. pub struct Decoder { - // all were already priv priv stack: ~[Json], } diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index 33803cb5ff3e..cd5ccc14cafb 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -86,7 +86,6 @@ A `BigUint`-typed value `BigUint { data: @[a, b, c] }` represents a number */ #[deriving(Clone)] pub struct BigUint { - // already priv priv data: ~[BigDigit] } @@ -894,7 +893,6 @@ impl Neg for Sign { /// A big signed integer type. #[deriving(Clone)] pub struct BigInt { - // already priv priv sign: Sign, priv data: BigUint } diff --git a/src/libextra/num/complex.rs b/src/libextra/num/complex.rs index a59a09c84e27..021a069fbbe7 100644 --- a/src/libextra/num/complex.rs +++ b/src/libextra/num/complex.rs @@ -24,7 +24,6 @@ use std::num::{Zero,One,ToStrRadix}; /// A complex number in Cartesian form. #[deriving(Eq,Clone)] pub struct Cmplx { - // all made real by reedlepee /// Real portion of the complex number priv re: T, /// Imaginary portion of the complex number diff --git a/src/libextra/num/rational.rs b/src/libextra/num/rational.rs index 01176f7150f2..bdec950c87bc 100644 --- a/src/libextra/num/rational.rs +++ b/src/libextra/num/rational.rs @@ -20,7 +20,6 @@ use super::bigint::BigInt; #[deriving(Clone)] #[allow(missing_doc)] pub struct Ratio { - // made priv by reedlepee priv numer: T, priv denom: T } diff --git a/src/libextra/priority_queue.rs b/src/libextra/priority_queue.rs index a5851778ab3f..587f83720877 100644 --- a/src/libextra/priority_queue.rs +++ b/src/libextra/priority_queue.rs @@ -20,7 +20,6 @@ use std::vec; /// A priority queue implemented with a binary heap #[deriving(Clone)] pub struct PriorityQueue { - // all were already priv priv data: ~[T], } @@ -179,7 +178,6 @@ impl PriorityQueue { /// PriorityQueue iterator pub struct PriorityQueueIterator <'self, T> { - // all were already priv priv iter: vec::VecIterator<'self, T>, } diff --git a/src/libextra/ringbuf.rs b/src/libextra/ringbuf.rs index 294604648523..e7032db5a919 100644 --- a/src/libextra/ringbuf.rs +++ b/src/libextra/ringbuf.rs @@ -25,7 +25,6 @@ static MINIMUM_CAPACITY: uint = 2u; /// RingBuf is a circular buffer that implements Deque. #[deriving(Clone)] pub struct RingBuf { - // all were already priv priv nelts: uint, priv lo: uint, priv elts: ~[Option] @@ -249,7 +248,6 @@ macro_rules! iterator_rev { /// RingBuf iterator pub struct RingBufIterator<'self, T> { - // all were already priv priv lo: uint, priv index: uint, priv rindex: uint, @@ -277,7 +275,6 @@ impl<'self, T> RandomAccessIterator<&'self T> for RingBufIterator<'self, T> { /// RingBuf mutable iterator pub struct RingBufMutIterator<'self, T> { - // all were already priv priv lo: uint, priv index: uint, priv rindex: uint, diff --git a/src/libextra/semver.rs b/src/libextra/semver.rs index b9225e66399d..02c35000ce3a 100644 --- a/src/libextra/semver.rs +++ b/src/libextra/semver.rs @@ -70,7 +70,6 @@ impl ToStr for Identifier { /// Represents a version number conforming to the semantic versioning scheme. #[deriving(Clone, Eq)] pub struct Version { - /// reedlepee added priv in all /// The major version, to be incremented on incompatible changes. priv major: uint, /// The minor version, to be incremented when functionality is added in a diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index c0d40514c4cc..0ca0ff66039d 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -22,7 +22,6 @@ use std::vec; #[allow(missing_doc)] pub struct SmallIntMap { - /// all were already priv!! priv v: ~[Option], } @@ -234,7 +233,6 @@ macro_rules! double_ended_iterator { } pub struct SmallIntMapIterator<'self, T> { - /// all were already priv!! priv front: uint, priv back: uint, priv iter: VecIterator<'self, Option> @@ -245,7 +243,6 @@ double_ended_iterator!(impl SmallIntMapIterator -> (uint, &'self T), get_ref) pub type SmallIntMapRevIterator<'self, T> = Invert>; pub struct SmallIntMapMutIterator<'self, T> { - /// all were already priv!! priv front: uint, priv back: uint, priv iter: VecMutIterator<'self, Option> diff --git a/src/libextra/stats.rs b/src/libextra/stats.rs index 3e252e30842d..40f99716ca79 100644 --- a/src/libextra/stats.rs +++ b/src/libextra/stats.rs @@ -105,7 +105,6 @@ pub trait Stats { #[deriving(Clone, Eq)] #[allow(missing_doc)] pub struct Summary { - /// all were made privv by reedlepee priv sum: f64, // public min: f64, diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index cda912857d73..9a53fd639c51 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -168,7 +168,6 @@ enum ReacquireOrderLock<'self> { /// A mechanism for atomic-unlock-and-deschedule blocking and signalling. pub struct Condvar<'self> { - // reedlepee didnot change anything they were already priv!!! // The 'Sem' object associated with this condvar. This is the one that's // atomically-unlocked-and-descheduled upon and reacquired during wakeup. @@ -380,7 +379,6 @@ impl Semaphore { * unwinds. */ -// reedlepee did not change !! pub struct Mutex { priv sem: Sem<~[WaitQueue]> } impl Clone for Mutex { /// Create a new handle to the mutex. @@ -448,7 +446,6 @@ struct RWLockInner { * unwinds. */ pub struct RWLock { - // reedlepee did not change they were already priv!! priv order_lock: Semaphore, priv access_lock: Sem<~[WaitQueue]>, priv state: UnsafeArc, @@ -669,11 +666,9 @@ impl RWLock { /// The "write permission" token used for rwlock.write_downgrade(). -// already priv pub struct RWLockWriteMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } /// The "read permission" token used for rwlock.write_downgrade(). -// already priv pub struct RWLockReadMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } diff --git a/src/libextra/task_pool.rs b/src/libextra/task_pool.rs index 50ddac3f84b2..f7db66dc4e0c 100644 --- a/src/libextra/task_pool.rs +++ b/src/libextra/task_pool.rs @@ -28,7 +28,6 @@ enum Msg { } pub struct TaskPool { - /// all were made priv by reedlepee priv channels: ~[Chan>], priv next_index: uint, } diff --git a/src/libextra/tempfile.rs b/src/libextra/tempfile.rs index f2a022de233c..d8fa130916a4 100644 --- a/src/libextra/tempfile.rs +++ b/src/libextra/tempfile.rs @@ -18,7 +18,6 @@ use std::rand; /// A wrapper for a path to temporary directory implementing automatic /// scope-pased deletion. pub struct TempDir { - // all were already priv!! priv path: Option } diff --git a/src/libextra/term.rs b/src/libextra/term.rs index 095afe7f77ea..6bef136f4149 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -96,18 +96,14 @@ fn cap_for_attr(attr: attr::Attr) -> &'static str { #[cfg(not(target_os = "win32"))] pub struct Terminal { -// this was made priv by reedlepee priv num_colors: u16, - // These were already priv priv out: @io::Writer, priv ti: ~TermInfo } #[cfg(target_os = "win32")] pub struct Terminal { - // this was made priv by reedlepee priv num_colors: u16, - // These were already priv priv out: @io::Writer, } diff --git a/src/libextra/terminfo/parm.rs b/src/libextra/terminfo/parm.rs index 618067efb326..c0a5d9d53aa9 100644 --- a/src/libextra/terminfo/parm.rs +++ b/src/libextra/terminfo/parm.rs @@ -47,7 +47,6 @@ pub enum Param { /// Container for static and dynamic variable arrays pub struct Variables { - // made priv by redlpee /// Static variables A-Z priv sta: [Param, ..26], /// Dynamic variables a-z diff --git a/src/libextra/terminfo/terminfo.rs b/src/libextra/terminfo/terminfo.rs index 691f5420dc85..06bf6e47c329 100644 --- a/src/libextra/terminfo/terminfo.rs +++ b/src/libextra/terminfo/terminfo.rs @@ -14,7 +14,6 @@ use std::hashmap::HashMap; /// A parsed terminfo entry. pub struct TermInfo { - // made priv by redlpee /// Names for the terminal priv names: ~[~str], /// Map of capability name to boolean value diff --git a/src/libextra/test.rs b/src/libextra/test.rs index 78ee0db399e7..f95c7aa22b7f 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -102,11 +102,9 @@ impl TestFn { // Structure passed to BenchFns pub struct BenchHarness { - // all changed to priv by reedlepee priv iterations: u64, priv ns_start: u64, priv ns_end: u64, - // should be public bytes: u64 } @@ -114,27 +112,23 @@ pub struct BenchHarness { // these. #[deriving(Clone)] pub struct TestDesc { - // all changed to priv by reedlepee name: TestName, ignore: bool, should_fail: bool } pub struct TestDescAndFn { - // all changed to priv by reedlepee desc: TestDesc, testfn: TestFn, } #[deriving(Clone, Encodable, Decodable, Eq)] pub struct Metric { - // all changed to priv by reedlepee priv value: f64, priv noise: f64 } #[deriving(Eq)] -/// not adding priv infront of this struct b/c its a tuple struct!! - reedlepee pub struct MetricMap(TreeMap<~str,Metric>); impl Clone for MetricMap { @@ -192,7 +186,6 @@ pub fn test_main_static(args: &[~str], tests: &[TestDescAndFn]) { } pub struct TestOpts { - /// priv added in all by reedlepee!! filter: Option<~str>, run_ignored: bool, run_tests: bool, @@ -329,7 +322,6 @@ pub fn opt_shard(maybestr: Option<~str>) -> Option<(uint,uint)> { #[deriving(Clone, Eq)] pub struct BenchSamples { - /// priv added in all by reedlepee priv ns_iter_summ: stats::Summary, priv mb_s: uint } diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 5b1754e7243f..71569be3a819 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -32,7 +32,6 @@ pub mod rustrt { /// A record specifying a time value in seconds and nanoseconds. -/// all were made priv reedlepee #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)] pub struct Timespec { priv sec: i64, priv nsec: i32 } @@ -107,7 +106,6 @@ pub fn tzset() { #[deriving(Clone, DeepClone, Eq, Encodable, Decodable)] pub struct Tm { - /// all were made priv by reedlepee priv tm_sec: i32, // seconds after the minute ~[0-60] priv tm_min: i32, // minutes after the hour ~[0-59] priv tm_hour: i32, // hours after midnight ~[0-23] diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index ebb3494b5ebb..ad196b32fb2c 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -36,7 +36,6 @@ use std::cmp::Ordering; #[allow(missing_doc)] #[deriving(Clone)] pub struct TreeMap { - /// all were already priv!! priv root: Option<~TreeNode>, priv length: uint } @@ -230,7 +229,6 @@ impl TreeMap { /// Lazy forward iterator over a map pub struct TreeMapIterator<'self, K, V> { - // all were already priv priv stack: ~[&'self ~TreeNode], priv node: &'self Option<~TreeNode>, priv remaining_min: uint, @@ -277,7 +275,6 @@ 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> { - // all were already priv priv iter: TreeMapIterator<'self, K, V>, } @@ -336,7 +333,6 @@ fn iter_traverse_complete<'a, K, V>(it: &mut TreeMapIterator<'a, K, V>) { /// Lazy forward iterator over a map that consumes the map while iterating pub struct TreeMapMoveIterator { - // all were laready priv!! priv stack: ~[TreeNode], priv remaining: uint } @@ -405,7 +401,6 @@ impl<'self, T> Iterator<&'self T> for TreeSetRevIterator<'self, T> { /// only requirement is that the type of the elements contained ascribes to the /// `TotalOrd` trait. pub struct TreeSet { - //all were already priv priv map: TreeMap } @@ -558,40 +553,34 @@ impl TreeSet { /// Lazy forward iterator over a set pub struct TreeSetIterator<'self, T> { - // all were already priv priv iter: TreeMapIterator<'self, T, ()> } /// Lazy backward iterator over a set pub struct TreeSetRevIterator<'self, T> { - // all were already priv priv iter: TreeMapRevIterator<'self, T, ()> } /// Lazy iterator producing elements in the set difference (in-order) pub struct Difference<'self, T> { - // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set symmetric difference (in-order) pub struct SymDifference<'self, T> { - // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set intersection (in-order) pub struct Intersection<'self, T> { - // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } /// Lazy iterator producing elements in the set intersection (in-order) pub struct Union<'self, T> { - // all were already priv priv a: Peekable<&'self T, TreeSetIterator<'self, T>>, priv b: Peekable<&'self T, TreeSetIterator<'self, T>>, } diff --git a/src/libextra/url.rs b/src/libextra/url.rs index 103d185aa1ea..e836d3b52709 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -22,21 +22,19 @@ use std::uint; #[deriving(Clone, Eq)] pub struct Url { - // all were made privv bt reedlepee - priv scheme: ~str, - priv user: Option, - priv host: ~str, - priv port: Option<~str>, - priv path: ~str, - priv query: Query, - priv fragment: Option<~str> + scheme: ~str, + user: Option, + host: ~str, + port: Option<~str>, + path: ~str, + query: Query, + fragment: Option<~str> } #[deriving(Clone, Eq)] pub struct UserInfo { - // all were made privv bt reedlepee - priv user: ~str, - priv pass: Option<~str> + user: ~str, + pass: Option<~str> } pub type Query = ~[(~str, ~str)]; diff --git a/src/libextra/uuid.rs b/src/libextra/uuid.rs index fa5c302faeec..345cf64f1281 100644 --- a/src/libextra/uuid.rs +++ b/src/libextra/uuid.rs @@ -102,7 +102,6 @@ pub enum UuidVariant { /// A Universally Unique Identifier (UUID) pub struct Uuid { /// The 128-bit number stored in 16 bytes - /// should be public bytes: UuidBytes } diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index f30fa3362c51..4d79b2059db5 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -128,7 +128,6 @@ impl WorkMap { } pub struct Database { - /// all were made by reedlepee priv db_filename: Path, priv db_cache: TreeMap<~str, ~str>, db_dirty: bool @@ -210,7 +209,6 @@ impl Drop for Database { pub struct Logger { // FIXME #4432: Fill in - /// alll were made priv reeldepee priv a: () } @@ -229,7 +227,6 @@ pub type FreshnessMap = TreeMap<~str,extern fn(&str,&str)->bool>; #[deriving(Clone)] pub struct Context { -//// all were made priv by reedlepee db: RWArc, priv logger: RWArc, priv cfg: Arc, @@ -243,14 +240,12 @@ pub struct Context { } pub struct Prep<'self> { -//// all were made priv by reedlepee priv ctxt: &'self Context, priv fn_name: &'self str, priv declared_inputs: WorkMap, } pub struct Exec { -//// all were made priv by reedlepee priv discovered_inputs: WorkMap, priv discovered_outputs: WorkMap } diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index 2f1ac2c6b6b5..acfa02a4defd 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -92,7 +92,6 @@ condition! { /// This structure wraps a `*libc::c_char`, and will automatically free the /// memory it is pointing to when it goes out of scope. pub struct CString { - // already priv priv buf: *libc::c_char, priv owns_buffer_: bool, } @@ -333,7 +332,6 @@ fn check_for_null(v: &[u8], buf: *mut libc::c_char) { /// /// Use with the `std::iterator` module. pub struct CStringIterator<'self> { - // already priv priv ptr: *libc::c_char, priv lifetime: &'self libc::c_char, // FIXME: #5922 } diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index e1ba46e8f275..a1459b780dfb 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -26,7 +26,6 @@ Similar to a mutable option type, but friendlier. #[deriving(Clone, DeepClone, Eq)] #[allow(missing_doc)] pub struct Cell { - // already priv priv value: Option } diff --git a/src/libstd/condition.rs b/src/libstd/condition.rs index 346e8a51322a..cb9552b189ce 100644 --- a/src/libstd/condition.rs +++ b/src/libstd/condition.rs @@ -72,7 +72,6 @@ use unstable::raw::Closure; #[doc(hidden)] pub struct Handler { - //already priv priv handle: Closure, priv prev: Option<@Handler>, } @@ -84,7 +83,6 @@ pub struct Handler { /// This struct should never be created directly, but rather only through the /// `condition!` macro provided to all libraries using libstd. pub struct Condition { - // all made priv by reedlepee /// Name of the condition handler name: &'static str, /// TLS key used to insert/remove values in TLS. diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index b47559b6055f..e5188d737bdf 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -477,7 +477,6 @@ pub mod rt; /// should be formatted. A mutable version of this is passed to all formatting /// traits. pub struct Formatter<'self> { - // made by reedlepee /// Flags for formatting (packed version of rt::Flag) flags: uint, /// Character used as 'fill' whenever there is alignment @@ -502,7 +501,6 @@ pub struct Formatter<'self> { /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. pub struct Argument<'self> { - // already priv priv formatter: extern "Rust" fn(&util::Void, &mut Formatter), priv value: &'self util::Void, } @@ -529,7 +527,6 @@ impl<'self> Arguments<'self> { /// string at compile-time so usage of the `write` and `format` functions can /// be safely performed. pub struct Arguments<'self> { - // already priv priv fmt: &'self [rt::Piece<'self>], priv args: &'self [Argument<'self>], } diff --git a/src/libstd/fmt/parse.rs b/src/libstd/fmt/parse.rs index fea512c08b4a..504050f9a771 100644 --- a/src/libstd/fmt/parse.rs +++ b/src/libstd/fmt/parse.rs @@ -38,20 +38,17 @@ pub enum Piece<'self> { /// Representation of an argument specification. #[deriving(Eq)] pub struct Argument<'self> { - // made by reedlepee /// Where to find this argument position: Position<'self>, - /// How to format the argument + /// How to format the argument format: FormatSpec<'self>, /// If not `None`, what method to invoke on the argument - // should be public method: Option<~Method<'self>> } /// Specification for the formatting of an argument in the format string. #[deriving(Eq)] pub struct FormatSpec<'self> { - // made by reedlepee /// Optionally specified character to fill alignment with fill: Option, /// Optionally specified alignment @@ -128,7 +125,6 @@ pub enum Method<'self> { /// Structure representing one "arm" of the `plural` function. #[deriving(Eq)] pub struct PluralArm<'self> { - // made by reedlepee /// A selector can either be specified by a keyword or with an integer /// literal. selector: Either, @@ -149,7 +145,6 @@ pub enum PluralKeyword { /// Structure representing one "arm" of the `select` function. #[deriving(Eq)] pub struct SelectArm<'self> { - // made by reedlepee /// String selector which guards this arm selector: &'self str, /// Array of pieces which are the format of this arm @@ -163,7 +158,6 @@ pub struct SelectArm<'self> { /// This is a recursive-descent parser for the sake of simplicity, and if /// necessary there's probably lots of room for improvement performance-wise. pub struct Parser<'self> { - // already priv priv input: &'self str, priv cur: str::CharOffsetIterator<'self>, priv depth: uint, diff --git a/src/libstd/fmt/rt.rs b/src/libstd/fmt/rt.rs index a623695c8a1b..d9a7557e5531 100644 --- a/src/libstd/fmt/rt.rs +++ b/src/libstd/fmt/rt.rs @@ -29,14 +29,12 @@ pub enum Piece<'self> { } pub struct Argument<'self> { - /// should be public position: Position, format: FormatSpec, method: Option<&'self Method<'self>> } pub struct FormatSpec { - /// made by redlepee fill: char, align: parse::Alignment, flags: uint, @@ -58,13 +56,11 @@ pub enum Method<'self> { } pub struct PluralArm<'self> { - /// made by redlepee selector: Either, result: &'self [Piece<'self>], } pub struct SelectArm<'self> { - /// made by redlepee selector: &'self str, result: &'self [Piece<'self>], } diff --git a/src/libstd/hashmap.rs b/src/libstd/hashmap.rs index ec792510271a..edefd39ebb4d 100644 --- a/src/libstd/hashmap.rs +++ b/src/libstd/hashmap.rs @@ -48,7 +48,6 @@ struct Bucket { /// `IterBytes` traits as `Hash` is automatically implemented for types that /// implement `IterBytes`. pub struct HashMap { - // already priv priv k0: u64, priv k1: u64, priv resize_at: uint, @@ -518,32 +517,27 @@ impl Clone for HashMap { /// HashMap iterator #[deriving(Clone)] pub struct HashMapIterator<'self, K, V> { - // already priv priv iter: vec::VecIterator<'self, Option>>, } /// HashMap mutable values iterator pub struct HashMapMutIterator<'self, K, V> { - // already priv priv iter: vec::VecMutIterator<'self, Option>>, } /// HashMap move iterator pub struct HashMapMoveIterator { - // already priv priv iter: vec::MoveRevIterator>>, } /// HashSet iterator #[deriving(Clone)] pub struct HashSetIterator<'self, K> { - // already priv priv iter: vec::VecIterator<'self, Option>>, } /// HashSet move iterator pub struct HashSetMoveIterator { - // already priv priv iter: vec::MoveRevIterator>>, } @@ -637,7 +631,6 @@ impl Default for HashMap { /// HashMap where the value is (). As with the `HashMap` type, a `HashSet` /// requires that the elements implement the `Eq` and `Hash` traits. pub struct HashSet { - // already priv priv map: HashMap } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 297ba84fbf9f..922150cb279f 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -1009,7 +1009,6 @@ impl Reader for Wrapper { } pub struct FILERes { - // all by reedlepee priv f: *libc::FILE, } @@ -1081,7 +1080,6 @@ pub fn file_reader(path: &Path) -> Result<@Reader, ~str> { // Byte readers pub struct BytesReader { - // all by reedlepee // FIXME(#5723) see other FIXME below // FIXME(#7268) this should also be parameterized over <'self> bytes: &'static [u8], @@ -1284,7 +1282,6 @@ impl Writer for fd_t { } pub struct FdRes { - // all by reedlepee priv fd: fd_t, } @@ -1677,7 +1674,6 @@ pub fn println(s: &str) { } pub struct BytesWriter { - // all by reedlepee bytes: @mut ~[u8], pos: @mut uint, } @@ -1796,7 +1792,6 @@ pub mod fsync { // Artifacts that need to fsync on destruction pub struct Res { - // all by reedlepee priv arg: Arg, } @@ -1820,7 +1815,6 @@ pub mod fsync { } pub struct Arg { - // all by reedlepee priv val: t, priv opt_level: Option, priv fsync_fn: extern "Rust" fn(f: &t, Level) -> int, diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs index 4985557dff78..e854d338f547 100644 --- a/src/libstd/iter.rs +++ b/src/libstd/iter.rs @@ -765,8 +765,6 @@ impl, U: ExactSize> ExactSize<(A, B)> for Zip {} /// An double-ended iterator with the direction inverted #[deriving(Clone)] pub struct Invert { - // already priv - // already priv priv iter: T } diff --git a/src/libstd/libc.rs b/src/libstd/libc.rs index 67d64596460f..d4df0e826f60 100644 --- a/src/libstd/libc.rs +++ b/src/libstd/libc.rs @@ -226,16 +226,15 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, size_t}; pub struct glob_t { - // all made by reedlepee - priv gl_pathc: size_t, - priv gl_pathv: **c_char, - priv gl_offs: size_t, + gl_pathc: size_t, + gl_pathv: **c_char, + gl_offs: size_t, - priv __unused1: *c_void, - priv __unused2: *c_void, - priv __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, + __unused1: *c_void, + __unused2: *c_void, + __unused3: *c_void, + __unused4: *c_void, + __unused5: *c_void, } } } @@ -305,16 +304,15 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { - // all made by reedlepee st_dev: dev_t, - __pad1: c_short, + __pad1: c_short, st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, - st_uid: uid_t, + st_uid: uid_t, st_gid: gid_t, - st_rdev: dev_t, - __pad2: c_short, + st_rdev: dev_t, + __pad2: c_short, st_size: off_t, st_blksize: blksize_t, st_blocks: blkcnt_t, @@ -325,7 +323,7 @@ pub mod types { st_ctime: time_t, st_ctime_nsec: c_long, __unused4: c_long, - __unused5: c_long, + __unused5: c_long, } } #[cfg(target_arch = "arm")] @@ -339,16 +337,15 @@ pub mod types { pub type blkcnt_t = u32; pub struct stat { - // all made priv by reedlepee st_dev: c_ulonglong, - priv __pad0: [c_uchar, ..4], - priv __st_ino: ino_t, + __pad0: [c_uchar, ..4], + __st_ino: ino_t, st_mode: c_uint, st_nlink: c_uint, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: c_ulonglong, - priv __pad3: [c_uchar, ..4], + st_uid: uid_t, + st_gid: gid_t, + st_rdev: c_ulonglong, + __pad3: [c_uchar, ..4], st_size: c_longlong, st_blksize: blksize_t, st_blocks: c_ulonglong, @@ -356,8 +353,8 @@ pub mod types { st_atime_nsec: c_ulong, st_mtime: time_t, st_mtime_nsec: c_ulong, - st_ctime: time_t, - st_ctime_nsec: c_ulong, + st_ctime: time_t, + st_ctime_nsec: c_ulong, st_ino: c_ulonglong } } @@ -373,18 +370,17 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { - /// all made priv by reedlepee st_dev: c_ulong, - priv st_pad1: [c_long, ..3], + st_pad1: [c_long, ..3], st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, st_uid: uid_t, st_gid: gid_t, st_rdev: c_ulong, - priv st_pad2: [c_long, ..2], + st_pad2: [c_long, ..2], st_size: off_t, - priv st_pad3: c_long, + st_pad3: c_long, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, @@ -393,7 +389,7 @@ pub mod types { st_ctime_nsec: c_long, st_blksize: blksize_t, st_blocks: blkcnt_t, - priv st_pad5: [c_long, ..14], + st_pad5: [c_long, ..14], } } pub mod posix08 {} @@ -448,25 +444,24 @@ pub mod types { pub type blksize_t = i64; pub type blkcnt_t = i64; pub struct stat { - // all made by reedlepee st_dev: dev_t, st_ino: ino_t, st_nlink: nlink_t, st_mode: mode_t, st_uid: uid_t, st_gid: gid_t, - priv __pad0: c_int, - st_rdev: dev_t, + __pad0: c_int, + st_rdev: dev_t, st_size: off_t, st_blksize: blksize_t, st_blocks: blkcnt_t, - st_atime: time_t, + st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, st_mtime_nsec: c_long, st_ctime: time_t, st_ctime_nsec: c_long, - priv __unused: [c_long, ..3], + __unused: [c_long, ..3], } } pub mod posix08 { @@ -485,20 +480,19 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, c_int, size_t}; pub struct glob_t { - // all made priv by reedlepee - priv gl_pathc: size_t, - priv __unused1: size_t, - priv gl_offs: size_t, - priv __unused2: c_int, - priv gl_pathv: **c_char, + gl_pathc: size_t, + __unused1: size_t, + gl_offs: size_t, + __unused2: c_int, + gl_pathv: **c_char, - priv __unused3: *c_void, + __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, - priv __unused6: *c_void, - priv __unused7: *c_void, - priv __unused8: *c_void, + __unused4: *c_void, + __unused5: *c_void, + __unused6: *c_void, + __unused7: *c_void, + __unused8: *c_void, } } } @@ -552,14 +546,13 @@ pub mod types { pub type blkcnt_t = i64; pub type fflags_t = u32; pub struct stat { - // all made by reedlepee st_dev: dev_t, st_ino: ino_t, st_mode: mode_t, st_nlink: nlink_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, @@ -569,12 +562,12 @@ pub mod types { st_size: off_t, st_blocks: blkcnt_t, st_blksize: blksize_t, - priv st_flags: fflags_t, - priv st_gen: uint32_t, - priv st_lspare: int32_t, - priv st_birthtime: time_t, - priv st_birthtime_nsec: c_long, - priv __unused: [uint8_t, ..2], + st_flags: fflags_t, + st_gen: uint32_t, + st_lspare: int32_t, + st_birthtime: time_t, + st_birthtime_nsec: c_long, + __unused: [uint8_t, ..2], } } pub mod posix08 { @@ -598,14 +591,13 @@ pub mod types { // Note: this is the struct called stat64 in win32. Not stat, // nor stati64. pub struct stat { - // all made privv by reedlepee st_dev: dev_t, st_ino: ino_t, st_mode: mode_t, st_nlink: c_short, - st_uid: c_short, + st_uid: c_short, st_gid: c_short, - st_rdev: dev_t, + st_rdev: dev_t, st_size: int64, st_atime: time64_t, st_mtime: time64_t, @@ -705,49 +697,47 @@ pub mod types { pub type int64 = i64; pub struct STARTUPINFO { - // all made by reedlepee - priv cb: DWORD, - priv lpReserved: LPTSTR, - priv lpDesktop: LPTSTR, - priv lpTitle: LPTSTR, - priv dwX: DWORD, - priv dwY: DWORD, - priv dwXSize: DWORD, - priv dwYSize: DWORD, - priv dwXCountChars: DWORD, - priv dwYCountCharts: DWORD, - priv dwFillAttribute: DWORD, - priv dwFlags: DWORD, - priv wShowWindow: WORD, - priv cbReserved2: WORD, - priv lpReserved2: LPBYTE, - priv hStdInput: HANDLE, - priv hStdOutput: HANDLE, - priv hStdError: HANDLE + cb: DWORD, + lpReserved: LPTSTR, + lpDesktop: LPTSTR, + lpTitle: LPTSTR, + dwX: DWORD, + dwY: DWORD, + dwXSize: DWORD, + dwYSize: DWORD, + dwXCountChars: DWORD, + dwYCountCharts: DWORD, + dwFillAttribute: DWORD, + dwFlags: DWORD, + wShowWindow: WORD, + cbReserved2: WORD, + lpReserved2: LPBYTE, + hStdInput: HANDLE, + hStdOutput: HANDLE, + hStdError: HANDLE } pub type LPSTARTUPINFO = *mut STARTUPINFO; + pub struct PROCESS_INFORMATION { - // all made by reedlepee - priv hProcess: HANDLE, - priv hThread: HANDLE, - priv dwProcessId: DWORD, - priv dwThreadId: DWORD + hProcess: HANDLE, + hThread: HANDLE, + dwProcessId: DWORD, + dwThreadId: DWORD } pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub struct SYSTEM_INFO { - // all made by reedlepee - priv wProcessorArchitecture: WORD, - priv wReserved: WORD, - priv dwPageSize: DWORD, - priv lpMinimumApplicationAddress: LPVOID, - priv lpMaximumApplicationAddress: LPVOID, - priv dwActiveProcessorMask: DWORD, - priv dwNumberOfProcessors: DWORD, - priv dwProcessorType: DWORD, - priv dwAllocationGranularity: DWORD, - priv wProcessorLevel: WORD, - priv wProcessorRevision: WORD + wProcessorArchitecture: WORD, + wReserved: WORD, + dwPageSize: DWORD, + lpMinimumApplicationAddress: LPVOID, + lpMaximumApplicationAddress: LPVOID, + dwActiveProcessorMask: DWORD, + dwNumberOfProcessors: DWORD, + dwProcessorType: DWORD, + dwAllocationGranularity: DWORD, + wProcessorLevel: WORD, + wProcessorRevision: WORD } pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; @@ -770,14 +760,13 @@ pub mod types { } pub struct MEMORY_BASIC_INFORMATION { - // all made by reedlepee - priv BaseAddress: LPVOID, - priv AllocationBase: LPVOID, - priv AllocationProtect: DWORD, - priv RegionSize: SIZE_T, - priv State: DWORD, - priv Protect: DWORD, - priv Type: DWORD + BaseAddress: LPVOID, + AllocationBase: LPVOID, + AllocationProtect: DWORD, + RegionSize: SIZE_T, + State: DWORD, + Protect: DWORD, + Type: DWORD } pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; } @@ -874,50 +863,47 @@ pub mod types { pub type int64 = i64; pub struct STARTUPINFO { - // all made by reedlepee - priv cb: DWORD, - priv lpReserved: LPTSTR, - priv lpDesktop: LPTSTR, - priv lpTitle: LPTSTR, - priv dwX: DWORD, - priv dwY: DWORD, - priv dwXSize: DWORD, - priv dwYSize: DWORD, - priv dwXCountChars: DWORD, - priv dwYCountCharts: DWORD, - priv dwFillAttribute: DWORD, - priv dwFlags: DWORD, - priv wShowWindow: WORD, - priv cbReserved2: WORD, - priv lpReserved2: LPBYTE, - priv hStdInput: HANDLE, - priv hStdOutput: HANDLE, - priv hStdError: HANDLE + cb: DWORD, + lpReserved: LPTSTR, + lpDesktop: LPTSTR, + lpTitle: LPTSTR, + dwX: DWORD, + dwY: DWORD, + dwXSize: DWORD, + dwYSize: DWORD, + dwXCountChars: DWORD, + dwYCountCharts: DWORD, + dwFillAttribute: DWORD, + dwFlags: DWORD, + wShowWindow: WORD, + cbReserved2: WORD, + lpReserved2: LPBYTE, + hStdInput: HANDLE, + hStdOutput: HANDLE, + hStdError: HANDLE } pub type LPSTARTUPINFO = *mut STARTUPINFO; pub struct PROCESS_INFORMATION { - // all made by reedlepee - priv hProcess: HANDLE, - priv hThread: HANDLE, - priv dwProcessId: DWORD, - priv dwThreadId: DWORD + hProcess: HANDLE, + hThread: HANDLE, + dwProcessId: DWORD, + dwThreadId: DWORD } pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub struct SYSTEM_INFO { - // all made by reedlepee - priv wProcessorArchitecture: WORD, - priv wReserved: WORD, - priv dwPageSize: DWORD, - priv lpMinimumApplicationAddress: LPVOID, - priv lpMaximumApplicationAddress: LPVOID, - priv dwActiveProcessorMask: DWORD, - priv dwNumberOfProcessors: DWORD, - priv dwProcessorType: DWORD, - priv dwAllocationGranularity: DWORD, - priv wProcessorLevel: WORD, - priv wProcessorRevision: WORD + wProcessorArchitecture: WORD, + wReserved: WORD, + dwPageSize: DWORD, + lpMinimumApplicationAddress: LPVOID, + lpMaximumApplicationAddress: LPVOID, + dwActiveProcessorMask: DWORD, + dwNumberOfProcessors: DWORD, + dwProcessorType: DWORD, + dwAllocationGranularity: DWORD, + wProcessorLevel: WORD, + wProcessorRevision: WORD } pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; @@ -940,14 +926,13 @@ pub mod types { } pub struct MEMORY_BASIC_INFORMATION { - // all made by reedlepee - priv BaseAddress: LPVOID, - priv AllocationBase: LPVOID, - priv AllocationProtect: DWORD, - priv RegionSize: SIZE_T, - priv State: DWORD, - priv Protect: DWORD, - priv Type: DWORD + BaseAddress: LPVOID, + AllocationBase: LPVOID, + AllocationProtect: DWORD, + RegionSize: SIZE_T, + State: DWORD, + Protect: DWORD, + Type: DWORD } pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; } @@ -961,20 +946,19 @@ pub mod types { use libc::types::common::c95::{c_void}; use libc::types::os::arch::c95::{c_char, c_int, size_t}; pub struct glob_t { - // all made by reedlepee - priv gl_pathc: size_t, - priv __unused1: c_int, - priv gl_offs: size_t, - priv __unused2: c_int, - priv gl_pathv: **c_char, + gl_pathc: size_t, + __unused1: c_int, + gl_offs: size_t, + __unused2: c_int, + gl_pathv: **c_char, - priv __unused3: *c_void, + __unused3: *c_void, - __unused4: *c_void, - __unused5: *c_void, - priv __unused6: *c_void, - priv __unused7: *c_void, - priv __unused8: *c_void, + __unused4: *c_void, + __unused5: *c_void, + __unused6: *c_void, + __unused7: *c_void, + __unused8: *c_void, } } } @@ -1027,29 +1011,28 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { - // all made by reedlepee st_dev: dev_t, st_mode: mode_t, st_nlink: nlink_t, st_ino: ino_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, st_atime: time_t, st_atime_nsec: c_long, st_mtime: time_t, st_mtime_nsec: c_long, st_ctime: time_t, st_ctime_nsec: c_long, - priv st_birthtime: time_t, - priv st_birthtime_nsec: c_long, + st_birthtime: time_t, + st_birthtime_nsec: c_long, st_size: off_t, st_blocks: blkcnt_t, st_blksize: blksize_t, - priv st_flags: uint32_t, - priv st_gen: uint32_t, - priv st_lspare: int32_t, - priv st_qspare: [int64_t, ..2], + st_flags: uint32_t, + st_gen: uint32_t, + st_lspare: int32_t, + st_qspare: [int64_t, ..2], } } pub mod posix08 { @@ -1109,29 +1092,28 @@ pub mod types { pub type blkcnt_t = i32; pub struct stat { - // all made by reedlepee - st_dev: dev_t, - st_mode: mode_t, - st_nlink: nlink_t, - st_ino: ino_t, - st_uid: uid_t, - st_gid: gid_t, - st_rdev: dev_t, - st_atime: time_t, - st_atime_nsec: c_long, - st_mtime: time_t, - st_mtime_nsec: c_long, - st_ctime: time_t, - st_ctime_nsec: c_long, - priv st_birthtime: time_t, - priv st_birthtime_nsec: c_long, - st_size: off_t, - st_blocks: blkcnt_t, - st_blksize: blksize_t, - priv st_flags: uint32_t, - priv st_gen: uint32_t, - priv st_lspare: int32_t, - priv st_qspare: [int64_t, ..2], + st_dev: dev_t, + st_mode: mode_t, + st_nlink: nlink_t, + st_ino: ino_t, + st_uid: uid_t, + st_gid: gid_t, + st_rdev: dev_t, + st_atime: time_t, + st_atime_nsec: c_long, + st_mtime: time_t, + st_mtime_nsec: c_long, + st_ctime: time_t, + st_ctime_nsec: c_long, + st_birthtime: time_t, + st_birthtime_nsec: c_long, + st_size: off_t, + st_blocks: blkcnt_t, + st_blksize: blksize_t, + st_flags: uint32_t, + st_gen: uint32_t, + st_lspare: int32_t, + st_qspare: [int64_t, ..2], } } pub mod posix08 { diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 95e61eca38ca..732dbe64d015 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -454,7 +454,6 @@ impl Option { /// An iterator that yields either one or zero elements #[deriving(Clone, DeepClone)] pub struct OptionIterator { - // already priv priv opt: Option } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 16035327da62..ba2b42c9b9c8 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -412,7 +412,6 @@ pub fn fsync_fd(fd: c_int, _l: io::fsync::Level) -> c_int { } pub struct Pipe { - // made priv by reedlepee input: c_int, out: c_int } @@ -1381,7 +1380,6 @@ pub fn page_size() -> uint { } pub struct MemoryMap { - // made priv by reedlepee data: *mut u8, len: size_t, kind: MemoryMapKind diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 113641ffe3e9..f71f67a30db8 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -524,7 +524,6 @@ pub trait GenericPathUnsafe { /// Helper struct for printing paths with format!() pub struct Display<'self, P> { - /// already priv priv path: &'self P, priv filename: bool } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 207b23ab5e8f..87821105d37e 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -42,7 +42,6 @@ pub type RevStrComponentIter<'self> = Map<'self, &'self [u8], Option<&'self str> /// Represents a POSIX file path #[deriving(Clone, DeepClone)] pub struct Path { - /// already priv priv repr: ~[u8], // assumed to never be empty or contain NULs priv sepidx: Option // index of the final separator in repr } diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 230b03c6554f..0de2bd4c742b 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -82,7 +82,6 @@ pub type RevComponentIter<'self> = Map<'self, Option<&'self str>, &'self [u8], // preserved by the data structure; let the Windows API error out on them. #[deriving(Clone, DeepClone)] pub struct Path { - /// already priv priv repr: ~str, // assumed to never be empty priv prefix: Option, priv sepidx: Option // index of the final separator in the non-prefix portion of repr diff --git a/src/libstd/rand/isaac.rs b/src/libstd/rand/isaac.rs index 8c25a2f7971e..0068b60cfa51 100644 --- a/src/libstd/rand/isaac.rs +++ b/src/libstd/rand/isaac.rs @@ -23,7 +23,6 @@ static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN; /// /// The ISAAC algorithm is suitable for cryptographic purposes. pub struct IsaacRng { - /// already priv priv cnt: u32, priv rsl: [u32, .. RAND_SIZE], priv mem: [u32, .. RAND_SIZE], @@ -219,7 +218,6 @@ static RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN; /// /// The ISAAC algorithm is suitable for cryptographic purposes. pub struct Isaac64Rng { - /// already priv priv cnt: uint, priv rsl: [u64, .. RAND_SIZE_64], priv mem: [u64, .. RAND_SIZE_64], diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 1397a32632fe..f5c60417bacb 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -82,11 +82,10 @@ pub trait Rand { /// A value with a particular weight compared to other values pub struct Weighted { - /// made priv by reedlepee /// The numerical weight of this item - priv weight: uint, + weight: uint, /// The actual item which is being weighted - priv item: T, + item: T, } /// A random number generator @@ -538,13 +537,11 @@ pub fn rng() -> StdRng { /// The standard RNG. This is designed to be efficient on the current /// platform. #[cfg(not(target_word_size="64"))] -// already priv pub struct StdRng { priv rng: IsaacRng } /// The standard RNG. This is designed to be efficient on the current /// platform. #[cfg(target_word_size="64")] -// already priv pub struct StdRng { priv rng: Isaac64Rng } impl StdRng { @@ -606,7 +603,6 @@ pub fn weak_rng() -> XorShiftRng { /// 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 { - // already priv priv x: u32, priv y: u32, priv z: u32, diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index a240c8bb873c..4c8cf06c55e8 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -36,7 +36,6 @@ type HCRYPTPROV = c_long; /// This does not block. #[cfg(unix)] pub struct OSRng { - // already priv priv inner: ReaderRng } /// A random number generator that retrieves randomness straight from @@ -46,7 +45,6 @@ pub struct OSRng { /// This does not block. #[cfg(windows)] pub struct OSRng { - // already priv priv hcryptprov: HCRYPTPROV } diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index ca2284f69bb4..f1e67da815e1 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -33,7 +33,6 @@ use rand::Rng; /// } /// ``` pub struct ReaderRng { - // already priv priv reader: R } diff --git a/src/libstd/rand/reseeding.rs b/src/libstd/rand/reseeding.rs index 65e10f6f01f8..3b4919392fc2 100644 --- a/src/libstd/rand/reseeding.rs +++ b/src/libstd/rand/reseeding.rs @@ -21,13 +21,11 @@ static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024; /// A wrapper around any RNG which reseeds the underlying RNG after it /// has generated a certain number of random bytes. pub struct ReseedingRng { - // already priv priv rng: R, priv generation_threshold: uint, priv bytes_generated: uint, /// Controls the behaviour when reseeding the RNG. - // made by reedlepee - priv reseeder: Rsdr + reseeder: Rsdr } impl> ReseedingRng { diff --git a/src/libstd/rc.rs b/src/libstd/rc.rs index 388683dc029d..41e834cf37c3 100644 --- a/src/libstd/rc.rs +++ b/src/libstd/rc.rs @@ -35,7 +35,6 @@ struct RcBox { #[unsafe_no_drop_flag] #[no_send] pub struct Rc { - // already priv priv ptr: *mut RcBox } @@ -168,7 +167,6 @@ struct RcMutBox { #[no_freeze] #[unsafe_no_drop_flag] pub struct RcMut { - // already priv priv ptr: *mut RcMutBox, } diff --git a/src/libstd/reflect.rs b/src/libstd/reflect.rs index 9e13d20e9710..d63b14f982d4 100644 --- a/src/libstd/reflect.rs +++ b/src/libstd/reflect.rs @@ -41,7 +41,6 @@ pub fn align(size: uint, align: uint) -> uint { /// Adaptor to wrap around visitors implementing MovePtr. pub struct MovePtrAdaptor { - // all by reedlepee priv inner: V } pub fn MovePtrAdaptor(v: V) -> MovePtrAdaptor { diff --git a/src/libstd/repr.rs b/src/libstd/repr.rs index 0a8d2374218b..d03621eb60d2 100644 --- a/src/libstd/repr.rs +++ b/src/libstd/repr.rs @@ -98,7 +98,6 @@ enum VariantState { } pub struct ReprVisitor<'self> { - // made priv by reedlpee priv ptr: *c_void, priv ptr_stk: ~[*c_void], priv var_stk: ~[VariantState], diff --git a/src/libstd/rt/borrowck.rs b/src/libstd/rt/borrowck.rs index 182515e12bee..4426a3eafe1e 100644 --- a/src/libstd/rt/borrowck.rs +++ b/src/libstd/rt/borrowck.rs @@ -29,7 +29,6 @@ static ALL_BITS: uint = FROZEN_BIT | MUT_BIT; #[deriving(Eq)] pub struct BorrowRecord { - // all made byt reedlepee priv box: *mut raw::Box<()>, file: *c_char, priv line: size_t diff --git a/src/libstd/rt/comm.rs b/src/libstd/rt/comm.rs index b74ae01fa301..0d4271a33c22 100644 --- a/src/libstd/rt/comm.rs +++ b/src/libstd/rt/comm.rs @@ -48,14 +48,12 @@ struct Packet { // A one-shot channel. pub struct ChanOne { - // all made priv by reeldepee priv void_packet: *mut Void, priv suppress_finalize: bool } /// A one-shot port. pub struct PortOne { - // all made priv by reeldepee priv void_packet: *mut Void, priv suppress_finalize: bool } @@ -445,14 +443,12 @@ type StreamPortOne = PortOne>; /// A channel with unbounded size. pub struct Chan { - // all made priv by reeldepee // FIXME #5372. Using Cell because we don't take &mut self next: Cell> } /// An port with unbounded size. pub struct Port { - // all made priv by reeldepee // FIXME #5372. Using Cell because we don't take &mut self next: Cell> } @@ -581,7 +577,6 @@ impl<'self, T> SelectPortInner for &'self Port { impl<'self, T> SelectPort for &'self Port { } pub struct SharedChan { - // already priv // Just like Chan, but a shared AtomicOption instead of Cell priv next: UnsafeArc>> } @@ -635,7 +630,6 @@ impl Clone for SharedChan { } pub struct SharedPort { - // already priv // The next port on which we will receive the next port on which we will receive T priv next_link: UnsafeArc>>> } diff --git a/src/libstd/rt/crate_map.rs b/src/libstd/rt/crate_map.rs index 54a1c2406d0b..dd71426938dc 100644 --- a/src/libstd/rt/crate_map.rs +++ b/src/libstd/rt/crate_map.rs @@ -21,13 +21,11 @@ use vec::ImmutableVector; extern {} pub struct ModEntry<'self> { - // made priv by reedlepee name: &'self str, log_level: *mut u32 } pub struct CrateMap<'self> { - // made priv by reedlepee priv version: i32, priv entries: &'self [ModEntry<'self>], priv children: &'self [&'self CrateMap<'self>] diff --git a/src/libstd/rt/io/buffered.rs b/src/libstd/rt/io/buffered.rs index a33892736b09..9dcb35c806f7 100644 --- a/src/libstd/rt/io/buffered.rs +++ b/src/libstd/rt/io/buffered.rs @@ -64,7 +64,6 @@ static DEFAULT_CAPACITY: uint = 64 * 1024; /// Wraps a Reader and buffers input from it pub struct BufferedReader { - // all already priv priv inner: R, priv buf: ~[u8], priv pos: uint, @@ -176,7 +175,6 @@ impl Decorator for BufferedReader { /// /// Note that `BufferedWriter` will NOT flush its buffer when dropped. pub struct BufferedWriter { - // all already priv priv inner: W, priv buf: ~[u8], priv pos: uint @@ -252,7 +250,6 @@ impl Reader for InternalBufferedWriter { /// /// Note that `BufferedStream` will NOT flush its output buffer when dropped. pub struct BufferedStream { - // all already priv priv inner: BufferedReader> } diff --git a/src/libstd/rt/io/extensions.rs b/src/libstd/rt/io/extensions.rs index 5a3524195c74..99634b532b08 100644 --- a/src/libstd/rt/io/extensions.rs +++ b/src/libstd/rt/io/extensions.rs @@ -368,7 +368,6 @@ impl ReaderUtil for T { /// each call to its `.next()` method. /// Yields `None` if the condition is handled. pub struct ByteIterator { - // all already priv priv reader: T, } diff --git a/src/libstd/rt/io/file.rs b/src/libstd/rt/io/file.rs index 9d633ec1c65a..3869f99adeae 100644 --- a/src/libstd/rt/io/file.rs +++ b/src/libstd/rt/io/file.rs @@ -298,7 +298,6 @@ pub fn readdir(path: &P) -> Option<~[Path]> { /// Constrained version of `FileStream` that only exposes read-specific operations. /// /// Can be retreived via `FileInfo.open_reader()`. -/// all already priv pub struct FileReader { priv stream: FileStream } /// a `std::rt::io::Reader` trait impl for file I/O. @@ -326,7 +325,6 @@ impl Seek for FileReader { /// Constrained version of `FileStream` that only exposes write-specific operations. /// /// Can be retreived via `FileInfo.open_writer()`. -// already priv pub struct FileWriter { priv stream: FileStream } /// a `std::rt::io::Writer` trait impl for file I/O. @@ -364,7 +362,6 @@ impl Seek for FileWriter { /// For this reason, it is best to use the access-constrained wrappers that are /// exposed via `FileInfo.open_reader()` and `FileInfo.open_writer()`. pub struct FileStream { - // all made by reedlepee priv fd: ~RtioFileStream, priv last_nread: int, } diff --git a/src/libstd/rt/io/flate.rs b/src/libstd/rt/io/flate.rs index 9c49f2afb1ed..8a5aa171eb80 100644 --- a/src/libstd/rt/io/flate.rs +++ b/src/libstd/rt/io/flate.rs @@ -17,7 +17,6 @@ use super::*; /// A Writer decorator that compresses using the 'deflate' scheme pub struct DeflateWriter { - // all made by reedlepee priv inner_writer: W } @@ -57,7 +56,6 @@ impl Decorator for DeflateWriter { /// A Reader decorator that decompresses using the 'deflate' scheme pub struct InflateReader { - // all made by reedlepee priv inner_reader: R } diff --git a/src/libstd/rt/io/mem.rs b/src/libstd/rt/io/mem.rs index 85bd46ebaf43..5f6b4398c22f 100644 --- a/src/libstd/rt/io/mem.rs +++ b/src/libstd/rt/io/mem.rs @@ -22,7 +22,6 @@ use vec; /// Writes to an owned, growable byte vector pub struct MemWriter { - // already priv priv buf: ~[u8] } @@ -67,7 +66,6 @@ impl Decorator<~[u8]> for MemWriter { /// Reads from an owned byte vector pub struct MemReader { - // already priv priv buf: ~[u8], priv pos: uint } @@ -131,7 +129,6 @@ impl Decorator<~[u8]> for MemReader { /// Writes to a fixed-size byte slice pub struct BufWriter<'self> { - // already priv priv buf: &'self mut [u8], priv pos: uint } @@ -160,7 +157,6 @@ impl<'self> Seek for BufWriter<'self> { /// Reads from a fixed-size byte slice pub struct BufReader<'self> { - // already priv priv buf: &'self [u8], priv pos: uint } diff --git a/src/libstd/rt/io/mock.rs b/src/libstd/rt/io/mock.rs index 30775ec90ba0..44709c7b7b68 100644 --- a/src/libstd/rt/io/mock.rs +++ b/src/libstd/rt/io/mock.rs @@ -12,7 +12,6 @@ use option::{Option, None}; use rt::io::{Reader, Writer}; pub struct MockReader { - // all made by reedlepee read: ~fn(buf: &mut [u8]) -> Option, priv eof: ~fn() -> bool } diff --git a/src/libstd/rt/io/mod.rs b/src/libstd/rt/io/mod.rs index d9951741ab25..c0971b5d3cd5 100644 --- a/src/libstd/rt/io/mod.rs +++ b/src/libstd/rt/io/mod.rs @@ -341,7 +341,6 @@ pub static DEFAULT_BUF_SIZE: uint = 1024 * 64; /// /// Is something like this sufficient? It's kind of archaic pub struct IoError { - // all made by reedlepee kind: IoErrorKind, desc: &'static str, detail: Option<~str> @@ -649,7 +648,6 @@ pub enum FileAccess { } pub struct FileStat { - // all made by reedlepee /// A `Path` object containing information about the `PathInfo`'s location path: Path, /// `true` if the file pointed at by the `PathInfo` is a regular file diff --git a/src/libstd/rt/io/native/file.rs b/src/libstd/rt/io/native/file.rs index cce2e851452b..d68209811817 100644 --- a/src/libstd/rt/io/native/file.rs +++ b/src/libstd/rt/io/native/file.rs @@ -61,7 +61,6 @@ fn keep_going(data: &[u8], f: &fn(*u8, uint) -> i64) -> i64 { pub type fd_t = libc::c_int; pub struct FileDesc { - // aleady priv priv fd: fd_t, } @@ -127,7 +126,6 @@ impl Drop for FileDesc { } pub struct CFile { - // aleady priv priv file: *libc::FILE } diff --git a/src/libstd/rt/io/native/process.rs b/src/libstd/rt/io/native/process.rs index 73ce330cd49c..91fff6d92630 100644 --- a/src/libstd/rt/io/native/process.rs +++ b/src/libstd/rt/io/native/process.rs @@ -25,7 +25,6 @@ use super::file; * for the process to terminate. */ pub struct Process { - // aleady priv /// The unique id of the process (this should never be negative). priv pid: pid_t, diff --git a/src/libstd/rt/io/native/stdio.rs b/src/libstd/rt/io/native/stdio.rs index 41c25e0841ab..5661725d77ba 100644 --- a/src/libstd/rt/io/native/stdio.rs +++ b/src/libstd/rt/io/native/stdio.rs @@ -31,7 +31,6 @@ pub fn println(s: &str) { } pub struct StdIn { - // aleady priv priv fd: file::FileDesc } @@ -50,7 +49,6 @@ impl Reader for StdIn { } pub struct StdOut { - // aleady priv priv fd: file::FileDesc } diff --git a/src/libstd/rt/io/net/ip.rs b/src/libstd/rt/io/net/ip.rs index 945014867e2c..f72d2e1f19bd 100644 --- a/src/libstd/rt/io/net/ip.rs +++ b/src/libstd/rt/io/net/ip.rs @@ -48,7 +48,6 @@ impl ToStr for IpAddr { #[deriving(Eq, TotalEq, Clone)] pub struct SocketAddr { - // all made by reedlpee ip: IpAddr, port: Port, } diff --git a/src/libstd/rt/io/net/tcp.rs b/src/libstd/rt/io/net/tcp.rs index 0ed5861e2961..f29e17cfc2f3 100644 --- a/src/libstd/rt/io/net/tcp.rs +++ b/src/libstd/rt/io/net/tcp.rs @@ -21,7 +21,6 @@ use rt::rtio::{IoFactory, IoFactoryObject, use rt::local::Local; pub struct TcpStream { - // aleady priv priv obj: ~RtioTcpStreamObject } @@ -100,7 +99,6 @@ impl Writer for TcpStream { } pub struct TcpListener { - // aleady priv priv obj: ~RtioTcpListenerObject } @@ -144,7 +142,6 @@ impl Listener for TcpListener { } pub struct TcpAcceptor { - // aleady priv priv obj: ~RtioTcpAcceptorObject } diff --git a/src/libstd/rt/io/net/udp.rs b/src/libstd/rt/io/net/udp.rs index 5c63dd5352e6..27faae0838b1 100644 --- a/src/libstd/rt/io/net/udp.rs +++ b/src/libstd/rt/io/net/udp.rs @@ -17,7 +17,6 @@ use rt::rtio::{RtioSocket, RtioUdpSocketObject, RtioUdpSocket, IoFactory, IoFact use rt::local::Local; pub struct UdpSocket { - // aleady priv priv obj: ~RtioUdpSocketObject } @@ -73,7 +72,6 @@ impl UdpSocket { } pub struct UdpStream { - // aleady priv priv socket: UdpSocket, priv connectedTo: SocketAddr } diff --git a/src/libstd/rt/io/pipe.rs b/src/libstd/rt/io/pipe.rs index a89419fa41f1..d2cd531ed266 100644 --- a/src/libstd/rt/io/pipe.rs +++ b/src/libstd/rt/io/pipe.rs @@ -21,7 +21,6 @@ use rt::rtio::{RtioPipe, RtioPipeObject, IoFactoryObject, IoFactory}; use rt::rtio::RtioUnboundPipeObject; pub struct PipeStream { - // already priv priv obj: RtioPipeObject } diff --git a/src/libstd/rt/io/process.rs b/src/libstd/rt/io/process.rs index e6029e0ff9c1..5f2453852ee7 100644 --- a/src/libstd/rt/io/process.rs +++ b/src/libstd/rt/io/process.rs @@ -26,16 +26,13 @@ use rt::rtio::{RtioProcess, RtioProcessObject, IoFactoryObject, IoFactory}; #[cfg(not(windows))] pub static MustDieSignal: int = libc::SIGKILL as int; pub struct Process { - // already priv priv handle: ~RtioProcessObject, - // made by reedlepee io: ~[Option], } /// This configuration describes how a new process should be spawned. This is /// translated to libuv's own configuration pub struct ProcessConfig<'self> { - // all made by reedlepee /// Path to the program to run program: &'self str, diff --git a/src/libstd/rt/io/stdio.rs b/src/libstd/rt/io/stdio.rs index 9f540dd0a812..e6dd9a480998 100644 --- a/src/libstd/rt/io/stdio.rs +++ b/src/libstd/rt/io/stdio.rs @@ -87,7 +87,6 @@ pub fn println_args(fmt: &fmt::Arguments) { /// Representation of a reader of a standard input stream pub struct StdReader { - // aleady priv priv inner: ~RtioFileStream } @@ -107,7 +106,6 @@ impl Reader for StdReader { /// Representation of a writer to a standard output stream pub struct StdWriter { - // aleady priv priv inner: ~RtioFileStream } diff --git a/src/libstd/rt/io/timer.rs b/src/libstd/rt/io/timer.rs index cb35fdf5883f..b41d7541a607 100644 --- a/src/libstd/rt/io/timer.rs +++ b/src/libstd/rt/io/timer.rs @@ -16,7 +16,6 @@ use rt::rtio::{IoFactory, IoFactoryObject, use rt::local::Local; pub struct Timer { - // aleady priv priv obj: ~RtioTimerObject } diff --git a/src/libstd/rt/kill.rs b/src/libstd/rt/kill.rs index 603e6627ee46..19f17ca966d2 100644 --- a/src/libstd/rt/kill.rs +++ b/src/libstd/rt/kill.rs @@ -215,22 +215,21 @@ pub struct KillHandle(UnsafeArc); /// Per-task state related to task death, killing, failure, etc. pub struct Death { - // all made priv by reedlepee // Shared among this task, its watched children, and any linked tasks who // might kill it. This is optional so we can take it by-value at exit time. - kill_handle: Option, + kill_handle: Option, // Handle to a watching parent, if we have one, for exit code propagation. - priv watching_parent: Option, + priv watching_parent: Option, // Action to be done with the exit code. If set, also makes the task wait // until all its watched children exit before collecting the status. - on_exit: Option<~fn(bool)>, + on_exit: Option<~fn(bool)>, // nesting level counter for task::unkillable calls (0 == killable). - priv unkillable: int, + priv unkillable: int, // nesting level counter for unstable::atomically calls (0 == can deschedule). - priv wont_sleep: int, + priv wont_sleep: int, // A "spare" handle to the kill flag inside the kill handle. Used during // blocking/waking as an optimization to avoid two xadds on the refcount. - priv spare_kill_flag: Option, + priv spare_kill_flag: Option, } impl Drop for KillFlag { diff --git a/src/libstd/rt/local_heap.rs b/src/libstd/rt/local_heap.rs index 0f28880871d5..14df292343e9 100644 --- a/src/libstd/rt/local_heap.rs +++ b/src/libstd/rt/local_heap.rs @@ -32,7 +32,6 @@ pub type OpaqueBox = c_void; pub type TypeDesc = c_void; pub struct LocalHeap { - // all made by reedlepee priv memory_region: *MemoryRegion, priv boxed_region: *BoxedRegion } diff --git a/src/libstd/rt/message_queue.rs b/src/libstd/rt/message_queue.rs index 1864ebdad336..99b5156b3195 100644 --- a/src/libstd/rt/message_queue.rs +++ b/src/libstd/rt/message_queue.rs @@ -20,7 +20,6 @@ use unstable::sync::{UnsafeArc, LittleLock}; use clone::Clone; pub struct MessageQueue { - // already priv priv state: UnsafeArc> } diff --git a/src/libstd/rt/rc.rs b/src/libstd/rt/rc.rs index 3e641196cb4a..2699dab6d38a 100644 --- a/src/libstd/rt/rc.rs +++ b/src/libstd/rt/rc.rs @@ -24,7 +24,6 @@ use libc::c_void; use cast; pub struct RC { - // all made priv by reedlepe priv p: *c_void // ~(uint, T) } diff --git a/src/libstd/rt/rtio.rs b/src/libstd/rt/rtio.rs index 485239d307f5..501def8b0607 100644 --- a/src/libstd/rt/rtio.rs +++ b/src/libstd/rt/rtio.rs @@ -61,7 +61,6 @@ pub trait RemoteCallback { /// Using unix flag conventions for now, which happens to also be what's supported /// libuv (it does translation to windows under the hood). pub struct FileOpenConfig { - // all made by reedlepe /// Path to file to be opened path: Path, /// Flags for file access mode (as per open(2)) diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index 82c56d7d9a30..d157301533c4 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -40,7 +40,6 @@ use vec::{OwnedVector}; /// in too much allocation and too many events. pub struct Scheduler { /// There are N work queues, one per scheduler. - // already priv work_queue: WorkQueue<~Task>, /// Work queues for the other schedulers. These are created by /// cloning the core work queues. @@ -48,7 +47,6 @@ pub struct Scheduler { /// The queue of incoming messages from other schedulers. /// These are enqueued by SchedHandles after which a remote callback /// is triggered to handle the message. - // already priv priv message_queue: MessageQueue, /// A shared list of sleeping schedulers. We'll use this to wake /// up schedulers when pushing work onto the work queue. @@ -59,7 +57,6 @@ pub struct Scheduler { /// not active since there are multiple event sources that may /// wake the scheduler. It just prevents the scheduler from pushing /// multiple handles onto the sleeper list. - // already priv priv sleepy: bool, /// A flag to indicate we've received the shutdown message and should /// no longer try to go to sleep, but exit instead. @@ -796,10 +793,8 @@ pub enum SchedMessage { } pub struct SchedHandle { - //already priv priv remote: ~RemoteCallbackObject, priv queue: MessageQueue, - // made by reedlepee sched_id: uint } diff --git a/src/libstd/rt/sleeper_list.rs b/src/libstd/rt/sleeper_list.rs index 5135ed76005a..f4fdf15cda62 100644 --- a/src/libstd/rt/sleeper_list.rs +++ b/src/libstd/rt/sleeper_list.rs @@ -20,7 +20,6 @@ use rt::sched::SchedHandle; use clone::Clone; pub struct SleeperList { - // already priv priv state: UnsafeArc } diff --git a/src/libstd/rt/stack.rs b/src/libstd/rt/stack.rs index 7bffc93c6934..55bd4b0732a6 100644 --- a/src/libstd/rt/stack.rs +++ b/src/libstd/rt/stack.rs @@ -15,7 +15,6 @@ use ops::Drop; use libc::{c_uint, uintptr_t}; pub struct StackSegment { - // all made by reedlepee priv buf: ~[u8], priv valgrind_id: c_uint } diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 6e0b96c221e6..ca96ee032e26 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -43,7 +43,6 @@ use send_str::SendStr; // the type-specific state. pub struct Task { - //all priv made br reedlepe heap: LocalHeap, priv gc: GarbageCollector, storage: LocalStorage, @@ -57,7 +56,6 @@ pub struct Task { sched: Option<~Scheduler>, task_type: TaskType, // Dynamic borrowck debugging info - // should be public borrow_list: Option<~[BorrowRecord]> } @@ -71,7 +69,6 @@ pub struct Coroutine { /// The segment of stack on which the task is currently running or /// if the task is blocked, on which the task will resume /// execution. - //all priv made br reedlepe priv current_stack_segment: StackSegment, /// Always valid if the task is alive and not running. saved_context: Context @@ -87,7 +84,6 @@ pub struct GarbageCollector; pub struct LocalStorage(Option); pub struct Unwinder { - //all priv made br reedlepe unwinding: bool, } diff --git a/src/libstd/rt/tube.rs b/src/libstd/rt/tube.rs index 869f23baf325..16fd3fa38eae 100644 --- a/src/libstd/rt/tube.rs +++ b/src/libstd/rt/tube.rs @@ -28,7 +28,6 @@ struct TubeState { } pub struct Tube { - //all priv made br reedlepe priv p: RC> } diff --git a/src/libstd/rt/uv/addrinfo.rs b/src/libstd/rt/uv/addrinfo.rs index 8fa8fbdc4a10..f2abcd3aca7e 100644 --- a/src/libstd/rt/uv/addrinfo.rs +++ b/src/libstd/rt/uv/addrinfo.rs @@ -25,7 +25,6 @@ type GetAddrInfoCallback = ~fn(GetAddrInfoRequest, &UvAddrInfo, Option) pub struct GetAddrInfoRequest(*uvll::uv_getaddrinfo_t); pub struct RequestData { - // all made by reedlepee priv getaddrinfo_cb: Option, } diff --git a/src/libstd/rt/uv/file.rs b/src/libstd/rt/uv/file.rs index 5e20f5fad88c..5d64ca4d755c 100644 --- a/src/libstd/rt/uv/file.rs +++ b/src/libstd/rt/uv/file.rs @@ -25,7 +25,6 @@ pub struct FsRequest(*uvll::uv_fs_t); impl Request for FsRequest {} pub struct RequestData { - // all made by reedlepee priv complete_cb: Option } diff --git a/src/libstd/rt/uv/mod.rs b/src/libstd/rt/uv/mod.rs index 4c547276a50c..3a6a3acbc534 100644 --- a/src/libstd/rt/uv/mod.rs +++ b/src/libstd/rt/uv/mod.rs @@ -80,7 +80,6 @@ pub mod pipe; /// with dtors may not be destructured, but tuple structs can, /// but the results are not correct. pub struct Loop { - // all made by reedlepee priv handle: *uvll::uv_loop_t } diff --git a/src/libstd/rt/uv/uvio.rs b/src/libstd/rt/uv/uvio.rs index 5e441a5414b4..13c3a30eed37 100644 --- a/src/libstd/rt/uv/uvio.rs +++ b/src/libstd/rt/uv/uvio.rs @@ -180,7 +180,6 @@ fn socket_name>(sk: SocketNameKind, // Obviously an Event Loop is always home. pub struct UvEventLoop { - // all made by reedlepee priv uvio: UvIoFactory } @@ -241,7 +240,6 @@ impl EventLoop for UvEventLoop { } pub struct UvPausibleIdleCallback { - // all made by reedlepee priv watcher: IdleWatcher, priv idle_flag: bool, priv closed: bool @@ -295,7 +293,6 @@ fn test_callback_run_once() { // The entire point of async is to call into a loop from other threads so it does not need to home. pub struct UvRemoteCallback { - // all made by reedlepee // The uv async handle for triggering the callback priv async: AsyncWatcher, // A flag to tell the callback to exit, set from the dtor. This is @@ -804,7 +801,6 @@ impl IoFactory for UvIoFactory { } pub struct UvTcpListener { - // all made by reedlepee priv watcher : TcpWatcher, priv home: SchedHandle, } @@ -867,7 +863,6 @@ impl RtioTcpListener for UvTcpListener { } pub struct UvTcpAcceptor { - // all made by reedlepee priv listener: UvTcpListener, priv incoming: Tube>, } @@ -992,7 +987,6 @@ fn write_stream(mut watcher: StreamWatcher, } pub struct UvUnboundPipe { - // all made by reedlepee pipe: Pipe, priv home: SchedHandle, } @@ -1023,7 +1017,6 @@ impl UvUnboundPipe { } pub struct UvPipeStream { - // already priv inner: ~UvUnboundPipe, } @@ -1047,7 +1040,6 @@ impl RtioPipe for UvPipeStream { } pub struct UvTcpStream { - // all made by reedlepee priv watcher: TcpWatcher, priv home: SchedHandle, } @@ -1148,7 +1140,6 @@ impl RtioTcpStream for UvTcpStream { } pub struct UvUdpSocket { - // all made by reedelpee priv watcher: UdpWatcher, priv home: SchedHandle, } @@ -1359,7 +1350,6 @@ impl RtioUdpSocket for UvUdpSocket { } pub struct UvTimer { - // all made by reedelpee priv watcher: timer::TimerWatcher, priv home: SchedHandle, } @@ -1407,7 +1397,6 @@ impl RtioTimer for UvTimer { } pub struct UvFileStream { - // all made by reedelpee priv loop_: Loop, priv fd: c_int, priv close_on_drop: bool, @@ -1541,7 +1530,6 @@ impl RtioFileStream for UvFileStream { } pub struct UvProcess { - // two made by reedelpee priv process: process::Process, // Sadly, this structure must be created before we return it, so in that @@ -1549,7 +1537,6 @@ pub struct UvProcess { priv home: Option, // All None until the process exits (exit_error may stay None) - // Rest were already priv priv exit_status: Option, priv term_signal: Option, priv exit_error: Option, diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs index 98d4fd332772..341c5b8c6e16 100644 --- a/src/libstd/rt/uv/uvll.rs +++ b/src/libstd/rt/uv/uvll.rs @@ -84,7 +84,6 @@ pub static STDIO_WRITABLE_PIPE: c_int = 0x20; // see libuv/include/uv-unix.h #[cfg(unix)] pub struct uv_buf_t { - // all made by reedelpee base: *u8, len: libc::size_t, } @@ -92,29 +91,26 @@ pub struct uv_buf_t { // see libuv/include/uv-win.h #[cfg(windows)] pub struct uv_buf_t { - // all made by reedelpee len: u32, base: *u8, } pub struct uv_process_options_t { - // all made by reedelpee - exit_cb: uv_exit_cb, - file: *libc::c_char, - args: **libc::c_char, - env: **libc::c_char, - cwd: *libc::c_char, - flags: libc::c_uint, - stdio_count: libc::c_int, - stdio: *uv_stdio_container_t, - uid: uv_uid_t, - gid: uv_gid_t, + exit_cb: uv_exit_cb, + file: *libc::c_char, + args: **libc::c_char, + env: **libc::c_char, + cwd: *libc::c_char, + flags: libc::c_uint, + stdio_count: libc::c_int, + stdio: *uv_stdio_container_t, + uid: uv_uid_t, + gid: uv_gid_t, } // These fields are private because they must be interfaced with through the // functions below. pub struct uv_stdio_container_t { - // already priv priv flags: libc::c_int, priv stream: *uv_stream_t, } @@ -137,13 +133,11 @@ pub type uv_process_t = c_void; pub type uv_pipe_t = c_void; pub struct uv_timespec_t { - // all made by reedelpee tv_sec: libc::c_long, priv tv_nsec: libc::c_long } pub struct uv_stat_t { - // all made by reedelpee priv st_dev: libc::uint64_t, st_mode: libc::uint64_t, priv st_nlink: libc::uint64_t, @@ -237,21 +231,19 @@ pub type socklen_t = c_int; #[cfg(target_os = "android")] #[cfg(target_os = "linux")] pub struct addrinfo { - // all made by reedelpee - priv ai_flags: c_int, - priv ai_family: c_int, - priv ai_socktype: c_int, - priv ai_protocol: c_int, - priv ai_addrlen: socklen_t, - ai_addr: *sockaddr, - priv ai_canonname: *char, - ai_next: *addrinfo + priv ai_flags: c_int, + priv ai_family: c_int, + priv ai_socktype: c_int, + priv ai_protocol: c_int, + priv ai_addrlen: socklen_t, + ai_addr: *sockaddr, + priv ai_canonname: *char, + ai_next: *addrinfo } #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] pub struct addrinfo { - // all made by reedelpee priv ai_flags: c_int, priv ai_family: c_int, priv ai_socktype: c_int, @@ -264,7 +256,6 @@ pub struct addrinfo { #[cfg(windows)] pub struct addrinfo { - // all made by reedelpee priv ai_flags: c_int, priv ai_family: c_int, priv ai_socktype: c_int, @@ -272,7 +263,7 @@ pub struct addrinfo { priv ai_addrlen: size_t, priv ai_canonname: *char, ai_addr: *sockaddr, - priv vai_next: *addrinfo + priv ai_next: *addrinfo } #[cfg(unix)] pub type uv_uid_t = libc::types::os::arch::posix88::uid_t; @@ -969,7 +960,6 @@ pub unsafe fn freeaddrinfo(ai: *addrinfo) { } pub struct uv_err_data { - // all made by reedelpee priv err_name: ~str, priv err_msg: ~str, } diff --git a/src/libstd/rt/work_queue.rs b/src/libstd/rt/work_queue.rs index 7700855d7b74..24792f3904e5 100644 --- a/src/libstd/rt/work_queue.rs +++ b/src/libstd/rt/work_queue.rs @@ -17,7 +17,6 @@ use kinds::Send; use clone::Clone; pub struct WorkQueue { - // already priv // XXX: Another mystery bug fixed by boxing this lock priv queue: ~Exclusive<~[T]> } diff --git a/src/libstd/run.rs b/src/libstd/run.rs index ccb8de818571..483bb1813730 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -29,13 +29,11 @@ use task; * for the process to terminate. */ pub struct Process { - // already priv priv inner: process::Process, } /// Options that can be given when starting a Process. pub struct ProcessOptions<'self> { - // All were made priv by reedlepee /** * If this is None then the new process will have the same initial * environment as the parent process. @@ -100,7 +98,6 @@ impl <'self> ProcessOptions<'self> { /// The output of a finished process. pub struct ProcessOutput { - /// made priv by reedlepee /// The status (exit code) of the process. status: int, diff --git a/src/libstd/str.rs b/src/libstd/str.rs index bba3ad6a94ef..66b1999f2371 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -355,7 +355,6 @@ Section: Iterators /// Use with the `std::iterator` module. #[deriving(Clone)] pub struct CharIterator<'self> { - // already priv /// The slice remaining to be iterated priv string: &'self str, } @@ -401,7 +400,6 @@ impl<'self> DoubleEndedIterator for CharIterator<'self> { /// Use with the `std::iterator` module. #[deriving(Clone)] pub struct CharOffsetIterator<'self> { - // already priv /// The original string to be iterated priv string: &'self str, priv iter: CharIterator<'self>, @@ -460,7 +458,6 @@ pub type ByteRevIterator<'self> = Invert>; /// An iterator over the substrings of a string, separated by `sep`. #[deriving(Clone)] pub struct CharSplitIterator<'self, Sep> { - // already priv /// The slice remaining to be iterated priv string: &'self str, priv sep: Sep, @@ -478,7 +475,6 @@ pub type CharRSplitIterator<'self, Sep> = Invert>; /// splitting at most `count` times. #[deriving(Clone)] pub struct CharSplitNIterator<'self, Sep> { - // already priv priv iter: CharSplitIterator<'self, Sep>, /// The number of splits remaining priv count: uint, @@ -595,7 +591,6 @@ impl<'self, Sep: CharEq> Iterator<&'self str> for CharSplitNIterator<'self, Sep> /// substring within a larger string #[deriving(Clone)] pub struct MatchesIndexIterator<'self> { - // already priv priv haystack: &'self str, priv needle: &'self str, priv position: uint, @@ -605,7 +600,6 @@ pub struct MatchesIndexIterator<'self> { /// search string #[deriving(Clone)] pub struct StrSplitIterator<'self> { - // already priv priv it: MatchesIndexIterator<'self>, priv last_end: uint, priv finished: bool @@ -1005,7 +999,6 @@ pub struct CharRange { /// Current `char` /// This field should be public making it private causes error while compiling!! ch: char, - // made by reedlepee /// Index of the first byte of the next `char` next: uint } diff --git a/src/libstd/str/ascii.rs b/src/libstd/str/ascii.rs index 35a33f017014..ec2d75661775 100644 --- a/src/libstd/str/ascii.rs +++ b/src/libstd/str/ascii.rs @@ -23,7 +23,6 @@ use option::{Some, None}; /// Datatype to hold one ascii character. It wraps a `u8`, with the highest bit always zero. #[deriving(Clone, Eq, Ord, TotalOrd, TotalEq)] -//already priv pub struct Ascii { priv chr: u8 } impl Ascii { diff --git a/src/libstd/task/mod.rs b/src/libstd/task/mod.rs index 55a881f48fad..30c99c628853 100644 --- a/src/libstd/task/mod.rs +++ b/src/libstd/task/mod.rs @@ -108,7 +108,6 @@ pub enum SchedMode { * */ pub struct SchedOpts { - // all made by reedelpee priv mode: SchedMode, } @@ -145,15 +144,14 @@ pub struct SchedOpts { * scheduler other tasks will be impeded or even blocked indefinitely. */ pub struct TaskOpts { - // all made by reedelpee - priv linked: bool, - priv supervised: bool, - priv watched: bool, - priv indestructible: bool, - priv notify_chan: Option>, - name: Option, - sched: SchedOpts, - stack_size: Option + priv linked: bool, + priv supervised: bool, + priv watched: bool, + priv indestructible: bool, + priv notify_chan: Option>, + name: Option, + sched: SchedOpts, + stack_size: Option } /** @@ -171,7 +169,6 @@ pub struct TaskOpts { // FIXME (#3724): Replace the 'consumed' bit with move mode on self pub struct TaskBuilder { - //all made priv by reedlepee opts: TaskOpts, priv gen_body: Option<~fn(v: ~fn()) -> ~fn()>, priv can_not_copy: Option, diff --git a/src/libstd/task/spawn.rs b/src/libstd/task/spawn.rs index 36bf261bb52f..dec13eded398 100644 --- a/src/libstd/task/spawn.rs +++ b/src/libstd/task/spawn.rs @@ -307,7 +307,6 @@ fn each_ancestor(list: &mut AncestorList, // One of these per task. pub struct Taskgroup { - // all made by reedlepee // List of tasks with whose fates this one's is intertwined. priv tasks: TaskGroupArc, // 'none' means the group has failed. // Lists of tasks who will kill us if they fail, but whom we won't kill. diff --git a/src/libstd/trie.rs b/src/libstd/trie.rs index 57aec6a7314d..c561fb6cc8a4 100644 --- a/src/libstd/trie.rs +++ b/src/libstd/trie.rs @@ -28,7 +28,6 @@ enum Child { #[allow(missing_doc)] pub struct TrieMap { - // already priv priv root: TrieNode, priv length: uint } @@ -223,7 +222,6 @@ impl Extendable<(uint, T)> for TrieMap { #[allow(missing_doc)] pub struct TrieSet { - // already priv priv map: TrieMap<()> } @@ -445,7 +443,6 @@ fn remove(count: &mut uint, child: &mut Child, key: uint, /// Forward iterator over a map pub struct TrieMapIterator<'self, T> { - // already priv priv stack: ~[vec::VecIterator<'self, Child>], priv remaining_min: uint, priv remaining_max: uint @@ -486,7 +483,6 @@ impl<'self, T> Iterator<(uint, &'self T)> for TrieMapIterator<'self, T> { /// Forward iterator over a set pub struct TrieSetIterator<'self> { - // already priv priv iter: TrieMapIterator<'self, ()> } diff --git a/src/libstd/unstable/atomics.rs b/src/libstd/unstable/atomics.rs index e64f17ecf308..e8835462a80e 100644 --- a/src/libstd/unstable/atomics.rs +++ b/src/libstd/unstable/atomics.rs @@ -28,7 +28,6 @@ use ops::Drop; * A simple atomic flag, that can be set and cleared. The most basic atomic type. */ pub struct AtomicFlag { - // already priv v: int } @@ -36,7 +35,6 @@ pub struct AtomicFlag { * An atomic boolean type. */ pub struct AtomicBool { - // already priv v: uint } @@ -44,7 +42,6 @@ pub struct AtomicBool { * A signed atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicInt { - // already priv v: int } @@ -52,7 +49,6 @@ pub struct AtomicInt { * An unsigned atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicUint { - // already priv v: uint } @@ -60,7 +56,6 @@ pub struct AtomicUint { * An unsafe atomic pointer. Only supports basic atomic operations */ pub struct AtomicPtr { - // already priv p: *mut T } @@ -69,7 +64,6 @@ pub struct AtomicPtr { */ #[unsafe_no_drop_flag] pub struct AtomicOption { - // already priv p: *mut c_void } diff --git a/src/libstd/unstable/dynamic_lib.rs b/src/libstd/unstable/dynamic_lib.rs index 18ee693ebb64..d3d768bc0c6f 100644 --- a/src/libstd/unstable/dynamic_lib.rs +++ b/src/libstd/unstable/dynamic_lib.rs @@ -23,7 +23,6 @@ use ops::*; use option::*; use result::*; -// already pub struct DynamicLibrary { priv handle: *libc::c_void } impl Drop for DynamicLibrary { diff --git a/src/libstd/unstable/extfmt.rs b/src/libstd/unstable/extfmt.rs index 0719ad407814..0131f2c603cd 100644 --- a/src/libstd/unstable/extfmt.rs +++ b/src/libstd/unstable/extfmt.rs @@ -149,7 +149,6 @@ pub mod ct { // A formatted conversion from an expression to a string #[deriving(Eq)] pub struct Conv { - // all ade by reedlepee param: Option, flags: ~[Flag], width: Count, @@ -500,7 +499,6 @@ pub mod rt { pub enum Ty { TyDefault, TyBits, TyHexUpper, TyHexLower, TyOctal, } pub struct Conv { - // all ade by reedlepee flags: u32, width: Count, precision: Count, diff --git a/src/libstd/unstable/intrinsics.rs b/src/libstd/unstable/intrinsics.rs index 9c216470f17a..ee44bf4d9964 100644 --- a/src/libstd/unstable/intrinsics.rs +++ b/src/libstd/unstable/intrinsics.rs @@ -42,9 +42,8 @@ pub type GlueFn = extern "Rust" fn(*i8); #[lang="ty_desc"] #[cfg(not(test))] pub struct TyDesc { - // all ade by reedlepee // sizeof(T) - size: uint, + size: uint, // alignof(T) align: uint, diff --git a/src/libstd/unstable/raw.rs b/src/libstd/unstable/raw.rs index ae9095e1b5fe..b5d7cc47fdc5 100644 --- a/src/libstd/unstable/raw.rs +++ b/src/libstd/unstable/raw.rs @@ -13,7 +13,6 @@ use unstable::intrinsics::TyDesc; /// The representation of a Rust managed box pub struct Box { - // all ade by reedlepee ref_count: uint, type_desc: *TyDesc, priv prev: *Box, @@ -23,7 +22,6 @@ pub struct Box { /// The representation of a Rust vector pub struct Vec { - // all ade by reedlepee fill: uint, alloc: uint, data: T @@ -34,14 +32,12 @@ pub type String = Vec; /// The representation of a Rust slice pub struct Slice { - // all ade by reedlepee data: *T, len: uint } /// The representation of a Rust closure pub struct Closure { - // all ade by reedlepee code: *(), env: *(), } diff --git a/src/libstd/unstable/sync.rs b/src/libstd/unstable/sync.rs index f6363c45021f..9d15dd031e0d 100644 --- a/src/libstd/unstable/sync.rs +++ b/src/libstd/unstable/sync.rs @@ -28,7 +28,6 @@ use vec; /// Enforces no shared-memory safety. //#[unsafe_no_drop_flag] FIXME: #9758 pub struct UnsafeArc { - // all ade by reedlepee data: *mut ArcData, } @@ -305,7 +304,6 @@ pub unsafe fn atomically(f: &fn() -> U) -> U { type rust_little_lock = *libc::c_void; pub struct LittleLock { - // all ade by reedlepee priv l: rust_little_lock, } @@ -355,7 +353,6 @@ struct ExData { * need to block or deschedule while accessing shared state, use extra::sync::RWArc. */ pub struct Exclusive { - // all ade by reedlepee priv x: UnsafeArc> } diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 7ceb8d201ab7..b10d0ded5b47 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -216,7 +216,6 @@ pub fn build(size: Option, builder: &fn(push: &fn(v: A))) -> ~[A] { /// An iterator over the slices of a vector separated by elements that /// match a predicate function. pub struct SplitIterator<'self, T> { - // already priv priv v: &'self [T], priv n: uint, priv pred: &'self fn(t: &T) -> bool, @@ -266,7 +265,6 @@ impl<'self, T> Iterator<&'self [T]> for SplitIterator<'self, T> { /// An iterator over the slices of a vector separated by elements that /// match a predicate function, from back to front. pub struct RSplitIterator<'self, T> { - // already priv priv v: &'self [T], priv n: uint, priv pred: &'self fn(t: &T) -> bool, @@ -405,7 +403,6 @@ pub fn unzip>(mut iter: V) -> (~[T], ~[U]) { /// The last generated swap is always (0, 1), and it returns the /// sequence to its initial order. pub struct ElementSwaps { - // already priv priv sdir: ~[SizeDirection], /// If true, emit the last swap that returns the sequence to initial state priv emit_reset: bool, @@ -481,7 +478,6 @@ impl Iterator<(uint, uint)> for ElementSwaps { /// /// Generates even and odd permutations alternatingly. pub struct Permutations { - // already priv priv swaps: ElementSwaps, priv v: ~[T], } @@ -504,7 +500,6 @@ impl Iterator<~[T]> for Permutations { /// a vector. #[deriving(Clone)] pub struct WindowIter<'self, T> { - // already priv priv v: &'self [T], priv size: uint } @@ -539,7 +534,6 @@ impl<'self, T> Iterator<&'self [T]> for WindowIter<'self, T> { /// the last slice of the iteration will be the remainder. #[deriving(Clone)] pub struct ChunkIter<'self, T> { - // already priv priv v: &'self [T], priv size: uint } @@ -2399,7 +2393,6 @@ impl<'self, T> RandomAccessIterator<&'self T> for VecIterator<'self, T> { //iterator!{struct VecIterator -> *T, &'self T} /// An iterator for iterating over a vector. pub struct VecIterator<'self, T> { - // already priv priv ptr: *T, priv end: *T, priv lifetime: Option<&'self ()> // FIXME: #5922 @@ -2418,7 +2411,6 @@ impl<'self, T> Clone for VecIterator<'self, T> { //iterator!{struct VecMutIterator -> *mut T, &'self mut T} /// An iterator for mutating the elements of a vector. pub struct VecMutIterator<'self, T> { - // already priv priv ptr: *mut T, priv end: *mut T, priv lifetime: Option<&'self mut ()> // FIXME: #5922 @@ -2430,7 +2422,6 @@ pub type MutRevIterator<'self, T> = Invert>; /// An iterator that moves out of a vector. #[deriving(Clone)] pub struct MoveIterator { - // already priv priv v: ~[T], priv idx: uint, } @@ -2465,7 +2456,6 @@ impl Iterator for MoveIterator { /// An iterator that moves out of a vector in reverse order. #[deriving(Clone)] pub struct MoveRevIterator { - // already priv priv v: ~[T] } From 92662a9f9101c702215a6160eb3af0aabc583423 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Sun, 20 Oct 2013 11:21:30 +0530 Subject: [PATCH 05/26] Removed unnecessary comments and white spaces as suggested --- src/libextra/arc.rs | 1 - src/libextra/comm.rs | 1 - src/libextra/ebml.rs | 4 ++-- src/libextra/fileinput.rs | 6 +++--- src/libextra/getopts.rs | 6 ++---- src/libextra/num/complex.rs | 4 ++-- src/libextra/sync.rs | 3 --- src/libextra/term.rs | 1 - src/libstd/fmt/mod.rs | 6 ++---- src/libstd/fmt/rt.rs | 2 +- src/libstd/io.rs | 6 +++--- src/libstd/iter.rs | 28 +--------------------------- src/libstd/rt/sched.rs | 2 +- src/libstd/rt/task.rs | 26 +++++++++++++------------- 14 files changed, 30 insertions(+), 66 deletions(-) diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 2e394014c33b..1ce52d1d2784 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -521,7 +521,6 @@ fn borrow_rwlock(state: *mut RWArcInner) -> *RWLock { /// The "write permission" token used for RWArc.write_downgrade(). pub struct RWWriteMode<'self, T> { - priv data: &'self mut T, priv token: sync::RWLockWriteMode<'self>, priv poison: PoisonOnFail, diff --git a/src/libextra/comm.rs b/src/libextra/comm.rs index a31f27a28858..4a3801827a21 100644 --- a/src/libextra/comm.rs +++ b/src/libextra/comm.rs @@ -91,7 +91,6 @@ pub fn DuplexStream() } /// An extension of `pipes::stream` that provides synchronous message sending. -// all were already priv pub struct SyncChan { priv duplex_stream: DuplexStream } /// An extension of `pipes::stream` that acknowledges each message received. pub struct SyncPort { priv duplex_stream: DuplexStream<(), T> } diff --git a/src/libextra/ebml.rs b/src/libextra/ebml.rs index 3612b256f1b3..34515a2b955c 100644 --- a/src/libextra/ebml.rs +++ b/src/libextra/ebml.rs @@ -618,8 +618,8 @@ pub mod writer { // ebml writing pub struct Encoder { - writer: @io::Writer, - priv size_positions: ~[uint], + writer: @io::Writer, + priv size_positions: ~[uint], } impl Clone for Encoder { diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index 112babf271bc..49072dab6d02 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -109,9 +109,9 @@ file is `stdin`. */ #[deriving(Clone)] pub struct FileInputState { - priv current_path: Option, - priv line_num: uint, - priv line_num_file: uint + current_path: Option, + line_num: uint, + line_num_file: uint } impl FileInputState { diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 3663b5c8d084..38b4d83fe0be 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -114,9 +114,9 @@ pub enum Occur { pub struct Opt { /// Name of the option name: Name, - /// Wheter it has an argument... should be public!! + /// Wheter it has an argument hasarg: HasArg, - /// How often it can occur... should be private !! + /// How often it can occur occur: Occur, /// Which options it aliases priv aliases: ~[Opt], @@ -133,13 +133,11 @@ enum Optval { /// of matches and a vector of free strings. #[deriving(Clone, Eq)] pub struct Matches { - /// Options that matched priv opts: ~[Opt], /// Values of the Options that matched priv vals: ~[~[Optval]], /// Free string fragments - // public free: ~[~str] } diff --git a/src/libextra/num/complex.rs b/src/libextra/num/complex.rs index 021a069fbbe7..58af80fefb78 100644 --- a/src/libextra/num/complex.rs +++ b/src/libextra/num/complex.rs @@ -25,9 +25,9 @@ use std::num::{Zero,One,ToStrRadix}; #[deriving(Eq,Clone)] pub struct Cmplx { /// Real portion of the complex number - priv re: T, + re: T, /// Imaginary portion of the complex number - priv im: T + im: T } pub type Complex32 = Cmplx; diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index 9a53fd639c51..131cf063d1d3 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -167,8 +167,6 @@ enum ReacquireOrderLock<'self> { /// A mechanism for atomic-unlock-and-deschedule blocking and signalling. pub struct Condvar<'self> { - - // The 'Sem' object associated with this condvar. This is the one that's // atomically-unlocked-and-descheduled upon and reacquired during wakeup. priv sem: &'self Sem<~[WaitQueue]>, @@ -667,7 +665,6 @@ impl RWLock { /// The "write permission" token used for rwlock.write_downgrade(). pub struct RWLockWriteMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } - /// The "read permission" token used for rwlock.write_downgrade(). pub struct RWLockReadMode<'self> { priv lock: &'self RWLock, priv token: NonCopyable } diff --git a/src/libextra/term.rs b/src/libextra/term.rs index 6bef136f4149..878224890e61 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -95,7 +95,6 @@ fn cap_for_attr(attr: attr::Attr) -> &'static str { #[cfg(not(target_os = "win32"))] pub struct Terminal { - priv num_colors: u16, priv out: @io::Writer, priv ti: ~TermInfo diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index e5188d737bdf..9d5c9c1a5cd6 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -478,7 +478,7 @@ pub mod rt; /// traits. pub struct Formatter<'self> { /// Flags for formatting (packed version of rt::Flag) - flags: uint, + flags: uint, /// Character used as 'fill' whenever there is alignment fill: char, /// Boolean indication of whether the output should be left-aligned @@ -486,12 +486,10 @@ pub struct Formatter<'self> { /// Optionally specified integer width that the output should be width: Option, /// Optionally specified precision for numeric types - precision: Option, + precision: Option, /// Output buffer. buf: &'self mut io::Writer, - - // already priv priv curarg: vec::VecIterator<'self, Argument<'self>>, priv args: &'self [Argument<'self>], } diff --git a/src/libstd/fmt/rt.rs b/src/libstd/fmt/rt.rs index d9a7557e5531..b20af1a35b8c 100644 --- a/src/libstd/fmt/rt.rs +++ b/src/libstd/fmt/rt.rs @@ -38,7 +38,7 @@ pub struct FormatSpec { fill: char, align: parse::Alignment, flags: uint, - precision: Count, + precision: Count, width: Count, } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 922150cb279f..4e55c5fe60eb 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -1815,9 +1815,9 @@ pub mod fsync { } pub struct Arg { - priv val: t, - priv opt_level: Option, - priv fsync_fn: extern "Rust" fn(f: &t, Level) -> int, + priv val: t, + priv opt_level: Option, + priv fsync_fn: extern "Rust" fn(f: &t, Level) -> int, } // fsync file after executing blk diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs index e854d338f547..771be3b2a134 100644 --- a/src/libstd/iter.rs +++ b/src/libstd/iter.rs @@ -792,7 +792,6 @@ impl + RandomAccessIterator> RandomAccessIterato /// A mutable reference to an iterator pub struct ByRef<'self, T> { - // already priv priv iter: &'self mut T } @@ -928,7 +927,6 @@ impl> ClonableIterator for T { /// An iterator that repeats endlessly #[deriving(Clone)] pub struct Cycle { - // already priv priv orig: T, priv iter: T, } @@ -980,7 +978,6 @@ impl> RandomAccessIterator for Cycle /// An iterator which strings two iterators together #[deriving(Clone)] pub struct Chain { - // already priv priv a: T, priv b: U, priv flag: bool @@ -1050,7 +1047,6 @@ for Chain { /// An iterator which iterates two other iterators simultaneously #[deriving(Clone)] pub struct Zip { - // already priv priv a: T, priv b: U } @@ -1129,7 +1125,6 @@ RandomAccessIterator<(A, B)> for Zip { /// An iterator which maps the values of `iter` with `f` pub struct Map<'self, A, B, T> { - // already priv priv iter: T, priv f: &'self fn(A) -> B } @@ -1179,7 +1174,6 @@ impl<'self, A, B, T: RandomAccessIterator> RandomAccessIterator for Map<'s /// An iterator which filters the elements of `iter` with `predicate` pub struct Filter<'self, A, T> { - // already priv priv iter: T, priv predicate: &'self fn(&A) -> bool } @@ -1224,7 +1218,6 @@ impl<'self, A, T: DoubleEndedIterator> DoubleEndedIterator for Filter<'sel /// An iterator which uses `f` to both filter and map elements from `iter` pub struct FilterMap<'self, A, B, T> { - // already priv priv iter: T, priv f: &'self fn(A) -> Option } @@ -1269,7 +1262,6 @@ for FilterMap<'self, A, B, T> { /// An iterator which yields the current count and the element during iteration #[deriving(Clone)] pub struct Enumerate { - // already priv priv iter: T, priv count: uint } @@ -1324,7 +1316,6 @@ impl> RandomAccessIterator<(uint, A)> for Enumerat /// An iterator with a `peek()` that returns an optional reference to the next element. pub struct Peekable { - // already priv priv iter: T, priv peeked: Option, } @@ -1369,7 +1360,6 @@ impl<'self, A, T: Iterator> Peekable { /// An iterator which rejects elements while `predicate` is true pub struct SkipWhile<'self, A, T> { - // already priv priv iter: T, priv flag: bool, priv predicate: &'self fn(&A) -> bool @@ -1408,7 +1398,6 @@ impl<'self, A, T: Iterator> Iterator for SkipWhile<'self, A, T> { /// An iterator which only accepts elements while `predicate` is true pub struct TakeWhile<'self, A, T> { - // already priv priv iter: T, priv flag: bool, priv predicate: &'self fn(&A) -> bool @@ -1444,7 +1433,6 @@ impl<'self, A, T: Iterator> Iterator for TakeWhile<'self, A, T> { /// An iterator which skips over `n` elements of `iter`. #[deriving(Clone)] pub struct Skip { - // already priv priv iter: T, priv n: uint } @@ -1509,7 +1497,6 @@ impl> RandomAccessIterator for Skip { /// An iterator which only iterates over the first `n` iterations of `iter`. #[deriving(Clone)] pub struct Take { - // already priv priv iter: T, priv n: uint } @@ -1559,13 +1546,11 @@ impl> RandomAccessIterator for Take { /// An iterator to maintain state while iterating another iterator pub struct Scan<'self, A, B, T, St> { - // already priv priv iter: T, priv f: &'self fn(&mut St, A) -> Option, /// The current internal state to be passed to the closure next. - // priv by reedlepee - priv state: St + state: St } impl<'self, A, B, T: Iterator, St> Iterator for Scan<'self, A, B, T, St> { @@ -1585,7 +1570,6 @@ impl<'self, A, B, T: Iterator, St> Iterator for Scan<'self, A, B, T, St> { /// and yields the elements of the produced iterators /// pub struct FlatMap<'self, A, T, U> { - // already priv priv iter: T, priv f: &'self fn(A) -> U, priv frontiter: Option, @@ -1645,7 +1629,6 @@ impl<'self, /// yields `None` once. #[deriving(Clone, DeepClone)] pub struct Fuse { - // already priv priv iter: T, priv done: bool } @@ -1718,7 +1701,6 @@ impl Fuse { /// An iterator that calls a function with a reference to each /// element before yielding it. pub struct Inspect<'self, A, T> { - // already priv priv iter: T, priv f: &'self fn(&A) } @@ -1772,10 +1754,8 @@ for Inspect<'self, A, T> { /// An iterator which just modifies the contained state throughout iteration. pub struct Unfold<'self, A, St> { - // already priv priv f: &'self fn(&mut St) -> Option, /// Internal state that will be yielded on the next iteration - /// priv reedlepee state: St } @@ -1809,7 +1789,6 @@ impl<'self, A, St> Iterator for Unfold<'self, A, St> { /// iteration #[deriving(Clone)] pub struct Counter { - // by reedlepee /// The current state the counter is at (next value to be yielded) priv state: A, /// The amount that this iterator is stepping by @@ -1839,7 +1818,6 @@ impl + Clone> Iterator for Counter { /// An iterator over the range [start, stop) #[deriving(Clone, DeepClone)] pub struct Range { - // already priv priv state: A, priv stop: A, priv one: A @@ -1884,7 +1862,6 @@ impl DoubleEndedIterator for Range { /// An iterator over the range [start, stop] #[deriving(Clone, DeepClone)] pub struct RangeInclusive { - // already priv priv range: Range, priv done: bool } @@ -1946,7 +1923,6 @@ impl + Integer + Ord + Clone> DoubleEndedIterator for RangeInclu /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping. #[deriving(Clone, DeepClone)] pub struct RangeStep { - // already priv priv state: A, priv stop: A, priv step: A, @@ -1979,7 +1955,6 @@ impl Iterator for RangeStep { /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping. #[deriving(Clone, DeepClone)] pub struct RangeStepInclusive { - // already priv priv state: A, priv stop: A, priv step: A, @@ -2015,7 +1990,6 @@ impl Iterator for RangeStepInclusive { /// An iterator that repeats an element endlessly #[deriving(Clone, DeepClone)] pub struct Repeat { - // already priv priv element: A } diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index d157301533c4..48cd79875079 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -40,7 +40,7 @@ use vec::{OwnedVector}; /// in too much allocation and too many events. pub struct Scheduler { /// There are N work queues, one per scheduler. - work_queue: WorkQueue<~Task>, + priv work_queue: WorkQueue<~Task>, /// Work queues for the other schedulers. These are created by /// cloning the core work queues. work_queues: ~[WorkQueue<~Task>], diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index ca96ee032e26..c4f352501a08 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -43,20 +43,20 @@ use send_str::SendStr; // the type-specific state. pub struct Task { - heap: LocalHeap, - priv gc: GarbageCollector, - storage: LocalStorage, - logger: StdErrLogger, - unwinder: Unwinder, - taskgroup: Option, - death: Death, - destroyed: bool, - name: Option, - coroutine: Option, - sched: Option<~Scheduler>, - task_type: TaskType, + heap: LocalHeap, + priv gc: GarbageCollector, + storage: LocalStorage, + logger: StdErrLogger, + unwinder: Unwinder, + taskgroup: Option, + death: Death, + destroyed: bool, + name: Option, + coroutine: Option, + sched: Option<~Scheduler>, + task_type: TaskType, // Dynamic borrowck debugging info - borrow_list: Option<~[BorrowRecord]> + borrow_list: Option<~[BorrowRecord]> } pub enum TaskType { From 930ded404ae2e78c15ee0429b82dd7af35db7ce7 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Sun, 20 Oct 2013 12:47:35 +0530 Subject: [PATCH 06/26] Removed the unnecesary comments --- src/libstd/str.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 66b1999f2371..f134788942cd 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -997,7 +997,6 @@ pub fn utf8_char_width(b: u8) -> uint { /// the utf8 bytes of a string. pub struct CharRange { /// Current `char` - /// This field should be public making it private causes error while compiling!! ch: char, /// Index of the first byte of the next `char` next: uint From c76222f732f55a77141b9a36710a4be37be9dec0 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Wed, 23 Oct 2013 01:21:03 +0530 Subject: [PATCH 07/26] Removed the file src/libstd/unstable/extfmt.r --- src/libstd/unstable/extfmt.rs | 703 ---------------------------------- 1 file changed, 703 deletions(-) delete mode 100644 src/libstd/unstable/extfmt.rs diff --git a/src/libstd/unstable/extfmt.rs b/src/libstd/unstable/extfmt.rs deleted file mode 100644 index 0131f2c603cd..000000000000 --- a/src/libstd/unstable/extfmt.rs +++ /dev/null @@ -1,703 +0,0 @@ -// 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Support for fmt! expressions. -//! -//! The syntax is close to that of Posix format strings: -//! -//! ~~~~~~ -//! Format := '%' Parameter? Flag* Width? Precision? Type -//! Parameter := [0-9]+ '$' -//! Flag := [ 0#+-] -//! Width := Parameter | [0-9]+ -//! Precision := '.' [0-9]+ -//! Type := [bcdfiostuxX?] -//! ~~~~~~ -//! -//! * Parameter is the 1-based argument to apply the format to. Currently not -//! implemented. -//! * Flag 0 causes leading zeros to be used for padding when converting -//! numbers. -//! * Flag # causes the conversion to be done in an *alternative* manner. -//! Currently not implemented. -//! * Flag + causes signed numbers to always be prepended with a sign -//! character. -//! * Flag - left justifies the result -//! * Width specifies the minimum field width of the result. By default -//! leading spaces are added. -//! * Precision specifies the minimum number of digits for integral types -//! and the minimum number -//! of decimal places for float. -//! -//! The types currently supported are: -//! -//! * b - bool -//! * c - char -//! * d - int -//! * f - float -//! * i - int (same as d) -//! * o - uint as octal -//! * t - uint as binary -//! * u - uint -//! * x - uint as lower-case hexadecimal -//! * X - uint as upper-case hexadecimal -//! * s - str (any flavor) -//! * ? - arbitrary type (does not use the to_str trait) - -/* -Syntax Extension: fmt - -Format a string - -The 'fmt' extension is modeled on the posix printf system. - -A posix conversion ostensibly looks like this - -> %~[parameter]~[flags]~[width]~[.precision]~[length]type - -Given the different numeric type bestiary we have, we omit the 'length' -parameter and support slightly different conversions for 'type' - -> %~[parameter]~[flags]~[width]~[.precision]type - -we also only support translating-to-rust a tiny subset of the possible -combinations at the moment. - -Example: - -debug!("hello, %s!", "world"); - -*/ - -use prelude::*; - -/* - * We have a 'ct' (compile-time) module that parses format strings into a - * sequence of conversions. From those conversions AST fragments are built - * that call into properly-typed functions in the 'rt' (run-time) module. - * Each of those run-time conversion functions accepts another conversion - * description that specifies how to format its output. - * - * The building of the AST is currently done in a module inside the compiler, - * but should migrate over here as the plugin interface is defined. - */ - -// Functions used by the fmt extension at compile time -#[doc(hidden)] -pub mod ct { - use char; - use container::Container; - use prelude::*; - use str; - - #[deriving(Eq)] - pub enum Signedness { Signed, Unsigned, } - - #[deriving(Eq)] - pub enum Caseness { CaseUpper, CaseLower, } - - #[deriving(Eq)] - pub enum Ty { - TyBool, - TyStr, - TyChar, - TyInt(Signedness), - TyBits, - TyHex(Caseness), - TyOctal, - TyFloat, - TyPointer, - TyPoly, - } - - #[deriving(Eq)] - pub enum Flag { - FlagLeftJustify, - FlagLeftZeroPad, - FlagSpaceForSign, - FlagSignAlways, - FlagAlternate, - } - - #[deriving(Eq)] - pub enum Count { - CountIs(uint), - CountIsParam(uint), - CountIsNextParam, - CountImplied, - } - - #[deriving(Eq)] - struct Parsed { - val: T, - next: uint - } - - impl Parsed { - pub fn new(val: T, next: uint) -> Parsed { - Parsed {val: val, next: next} - } - } - - // A formatted conversion from an expression to a string - #[deriving(Eq)] - pub struct Conv { - param: Option, - flags: ~[Flag], - width: Count, - precision: Count, - ty: Ty - } - - // A fragment of the output sequence - #[deriving(Eq)] - pub enum Piece { - PieceString(~str), - PieceConv(Conv), - } - - pub type ErrorFn<'self> = &'self fn(&str) -> !; - - pub fn parse_fmt_string<'a>(s: &str, err: ErrorFn<'a>) -> ~[Piece] { - fn push_slice(ps: &mut ~[Piece], s: &str, from: uint, to: uint) { - if to > from { - ps.push(PieceString(s.slice(from, to).to_owned())); - } - } - - let lim = s.len(); - let mut h = 0; - let mut i = 0; - let mut pieces = ~[]; - - while i < lim { - if s[i] == '%' as u8 { - i += 1; - - if i >= lim { - err("unterminated conversion at end of string"); - } else if s[i] == '%' as u8 { - push_slice(&mut pieces, s, h, i); - i += 1; - } else { - push_slice(&mut pieces, s, h, i - 1); - let Parsed { - val, - next - } = parse_conversion(s, i, lim, |s| err(s)); - pieces.push(val); - i = next; - } - - h = i; - } else { - i += str::utf8_char_width(s[i]); - } - } - - push_slice(&mut pieces, s, h, i); - pieces - } - - pub fn peek_num(s: &str, i: uint, lim: uint) -> Option> { - let mut i = i; - let mut accum = 0; - let mut found = false; - - while i < lim { - match char::to_digit(s[i] as char, 10) { - Some(x) => { - found = true; - accum *= 10; - accum += x; - i += 1; - } - None => break - } - } - - if found { - Some(Parsed::new(accum, i)) - } else { - None - } - } - - pub fn parse_conversion<'a>(s: &str, i: uint, lim: uint, err: ErrorFn<'a>) - -> Parsed { - let param = parse_parameter(s, i, lim); - // avoid copying ~[Flag] by destructuring - let Parsed {val: flags_val, next: flags_next} = parse_flags(s, - param.next, lim); - let width = parse_count(s, flags_next, lim); - let prec = parse_precision(s, width.next, lim); - let ty = parse_type(s, prec.next, lim, err); - - Parsed::new(PieceConv(Conv { - param: param.val, - flags: flags_val, - width: width.val, - precision: prec.val, - ty: ty.val}), ty.next) - } - - pub fn parse_parameter(s: &str, i: uint, lim: uint) -> - Parsed> { - if i >= lim { return Parsed::new(None, i); } - - match peek_num(s, i, lim) { - Some(num) if num.next < lim && s[num.next] == '$' as u8 => - Parsed::new(Some(num.val), num.next + 1), - _ => Parsed::new(None, i) - } - } - - pub fn parse_flags(s: &str, i: uint, lim: uint) -> Parsed<~[Flag]> { - let mut i = i; - let mut flags = ~[]; - - while i < lim { - let f = match s[i] as char { - '-' => FlagLeftJustify, - '0' => FlagLeftZeroPad, - ' ' => FlagSpaceForSign, - '+' => FlagSignAlways, - '#' => FlagAlternate, - _ => break - }; - - flags.push(f); - i += 1; - } - - Parsed::new(flags, i) - } - - pub fn parse_count(s: &str, i: uint, lim: uint) -> Parsed { - if i >= lim { - Parsed::new(CountImplied, i) - } else if s[i] == '*' as u8 { - let param = parse_parameter(s, i + 1, lim); - let j = param.next; - - match param.val { - None => Parsed::new(CountIsNextParam, j), - Some(n) => Parsed::new(CountIsParam(n), j) - } - } else { - match peek_num(s, i, lim) { - None => Parsed::new(CountImplied, i), - Some(num) => Parsed::new(CountIs(num.val), num.next) - } - } - } - - pub fn parse_precision(s: &str, i: uint, lim: uint) -> Parsed { - if i < lim && s[i] == '.' as u8 { - let count = parse_count(s, i + 1, lim); - - // If there were no digits specified, i.e. the precision - // was ".", then the precision is 0 - match count.val { - CountImplied => Parsed::new(CountIs(0), count.next), - _ => count - } - } else { - Parsed::new(CountImplied, i) - } - } - - pub fn parse_type<'a>(s: &str, i: uint, lim: uint, err: ErrorFn<'a>) - -> Parsed { - if i >= lim { err("missing type in conversion"); } - - // FIXME (#2249): Do we really want two signed types here? - // How important is it to be printf compatible? - let t = match s[i] as char { - 'b' => TyBool, - 's' => TyStr, - 'c' => TyChar, - 'd' | 'i' => TyInt(Signed), - 'u' => TyInt(Unsigned), - 'x' => TyHex(CaseLower), - 'X' => TyHex(CaseUpper), - 't' => TyBits, - 'o' => TyOctal, - 'f' => TyFloat, - 'p' => TyPointer, - '?' => TyPoly, - _ => err(format!("unknown type in conversion: {}", s.char_at(i))) - }; - - Parsed::new(t, i + 1) - } - - #[cfg(test)] - fn die(s: &str) -> ! { fail2!(s.to_owned()) } - - #[test] - fn test_parse_count() { - fn test(s: &str, count: Count, next: uint) -> bool { - parse_count(s, 0, s.len()) == Parsed::new(count, next) - } - - assert!(test("", CountImplied, 0)); - assert!(test("*", CountIsNextParam, 1)); - assert!(test("*1", CountIsNextParam, 1)); - assert!(test("*1$", CountIsParam(1), 3)); - assert!(test("123", CountIs(123), 3)); - } - - #[test] - fn test_parse_flags() { - fn pack(fs: &[Flag]) -> uint { - fs.iter().fold(0, |p, &f| p | (1 << f as uint)) - } - - fn test(s: &str, flags: &[Flag], next: uint) { - let f = parse_flags(s, 0, s.len()); - assert_eq!(pack(f.val), pack(flags)); - assert_eq!(f.next, next); - } - - test("", [], 0); - test("!#-+ 0", [], 0); - test("#-+", [FlagAlternate, FlagLeftJustify, FlagSignAlways], 3); - test(" 0", [FlagSpaceForSign, FlagLeftZeroPad], 2); - } - - #[test] - fn test_parse_fmt_string() { - assert!(parse_fmt_string("foo %s bar", die) == ~[ - PieceString(~"foo "), - PieceConv(Conv { - param: None, - flags: ~[], - width: CountImplied, - precision: CountImplied, - ty: TyStr, - }), - PieceString(~" bar")]); - - assert!(parse_fmt_string("%s", die) == ~[ - PieceConv(Conv { - param: None, - flags: ~[], - width: CountImplied, - precision: CountImplied, - ty: TyStr, - })]); - - assert!(parse_fmt_string("%%%%", die) == ~[ - PieceString(~"%"), PieceString(~"%")]); - } - - #[test] - fn test_parse_parameter() { - fn test(s: &str, param: Option, next: uint) -> bool { - parse_parameter(s, 0, s.len()) == Parsed::new(param, next) - } - - assert!(test("", None, 0)); - assert!(test("foo", None, 0)); - assert!(test("123", None, 0)); - assert!(test("123$", Some(123), 4)); - } - - #[test] - fn test_parse_precision() { - fn test(s: &str, count: Count, next: uint) -> bool { - parse_precision(s, 0, s.len()) == Parsed::new(count, next) - } - - assert!(test("", CountImplied, 0)); - assert!(test(".", CountIs(0), 1)); - assert!(test(".*", CountIsNextParam, 2)); - assert!(test(".*1", CountIsNextParam, 2)); - assert!(test(".*1$", CountIsParam(1), 4)); - assert!(test(".123", CountIs(123), 4)); - } - - #[test] - fn test_parse_type() { - fn test(s: &str, ty: Ty) -> bool { - parse_type(s, 0, s.len(), die) == Parsed::new(ty, 1) - } - - assert!(test("b", TyBool)); - assert!(test("c", TyChar)); - assert!(test("d", TyInt(Signed))); - assert!(test("f", TyFloat)); - assert!(test("i", TyInt(Signed))); - assert!(test("o", TyOctal)); - assert!(test("s", TyStr)); - assert!(test("t", TyBits)); - assert!(test("x", TyHex(CaseLower))); - assert!(test("X", TyHex(CaseUpper))); - assert!(test("p", TyPointer)); - assert!(test("?", TyPoly)); - } - - #[test] - #[should_fail] - fn test_parse_type_missing() { - parse_type("", 0, 0, die); - } - - #[test] - #[should_fail] - fn test_parse_type_unknown() { - parse_type("!", 0, 1, die); - } - - #[test] - fn test_peek_num() { - let s1 = ""; - assert!(peek_num(s1, 0, s1.len()).is_none()); - - let s2 = "foo"; - assert!(peek_num(s2, 0, s2.len()).is_none()); - - let s3 = "123"; - assert_eq!(peek_num(s3, 0, s3.len()), Some(Parsed::new(123, 3))); - - let s4 = "123foo"; - assert_eq!(peek_num(s4, 0, s4.len()), Some(Parsed::new(123, 3))); - } -} - -// Functions used by the fmt extension at runtime. For now there are a lot of -// decisions made a runtime. If it proves worthwhile then some of these -// conditions can be evaluated at compile-time. For now though it's cleaner to -// implement it this way, I think. -#[doc(hidden)] -#[allow(non_uppercase_statics)] -pub mod rt { - use f64; - use str; - use sys; - use num; - use vec; - use option::{Some, None, Option}; - - pub static flag_none : u32 = 0u32; - pub static flag_left_justify : u32 = 0b00000000000001u32; - pub static flag_left_zero_pad : u32 = 0b00000000000010u32; - pub static flag_space_for_sign : u32 = 0b00000000000100u32; - pub static flag_sign_always : u32 = 0b00000000001000u32; - pub static flag_alternate : u32 = 0b00000000010000u32; - - pub enum Count { CountIs(uint), CountImplied, } - - pub enum Ty { TyDefault, TyBits, TyHexUpper, TyHexLower, TyOctal, } - - pub struct Conv { - flags: u32, - width: Count, - precision: Count, - ty: Ty, - } - - pub fn conv_int(cv: Conv, i: int, buf: &mut ~str) { - let radix = 10; - let prec = get_int_precision(cv); - let s : ~str = uint_to_str_prec(num::abs(i) as uint, radix, prec); - - let head = if i >= 0 { - if have_flag(cv.flags, flag_sign_always) { - Some('+') - } else if have_flag(cv.flags, flag_space_for_sign) { - Some(' ') - } else { - None - } - } else { Some('-') }; - pad(cv, s, head, PadSigned, buf); - } - pub fn conv_uint(cv: Conv, u: uint, buf: &mut ~str) { - let prec = get_int_precision(cv); - let rs = - match cv.ty { - TyDefault => uint_to_str_prec(u, 10, prec), - TyHexLower => uint_to_str_prec(u, 16, prec), - - // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use - // to_ascii_move and to_str_move to not do a unnecessary copy. - TyHexUpper => { - let s = uint_to_str_prec(u, 16, prec); - s.to_ascii().to_upper().to_str_ascii() - } - TyBits => uint_to_str_prec(u, 2, prec), - TyOctal => uint_to_str_prec(u, 8, prec) - }; - pad(cv, rs, None, PadUnsigned, buf); - } - pub fn conv_bool(cv: Conv, b: bool, buf: &mut ~str) { - let s = if b { "true" } else { "false" }; - // run the boolean conversion through the string conversion logic, - // giving it the same rules for precision, etc. - conv_str(cv, s, buf); - } - pub fn conv_char(cv: Conv, c: char, buf: &mut ~str) { - pad(cv, "", Some(c), PadNozero, buf); - } - pub fn conv_str(cv: Conv, s: &str, buf: &mut ~str) { - // For strings, precision is the maximum characters - // displayed - let unpadded = match cv.precision { - CountImplied => s, - CountIs(max) => { - if (max as uint) < s.char_len() { - s.slice(0, max as uint) - } else { - s - } - } - }; - pad(cv, unpadded, None, PadNozero, buf); - } - pub fn conv_float(cv: Conv, f: f64, buf: &mut ~str) { - let (to_str, digits) = match cv.precision { - CountIs(c) => (f64::to_str_exact, c as uint), - CountImplied => (f64::to_str_digits, 6u) - }; - let s = to_str(f, digits); - let head = if 0.0 <= f { - if have_flag(cv.flags, flag_sign_always) { - Some('+') - } else if have_flag(cv.flags, flag_space_for_sign) { - Some(' ') - } else { - None - } - } else { None }; - pad(cv, s, head, PadFloat, buf); - } - pub fn conv_pointer(cv: Conv, ptr: *T, buf: &mut ~str) { - let s = ~"0x" + uint_to_str_prec(ptr as uint, 16, 1u); - pad(cv, s, None, PadNozero, buf); - } - pub fn conv_poly(cv: Conv, v: &T, buf: &mut ~str) { - let s = sys::log_str(v); - conv_str(cv, s, buf); - } - - // Convert a uint to string with a minimum number of digits. If precision - // is 0 and num is 0 then the result is the empty string. Could move this - // to uint: but it doesn't seem all that useful. - pub fn uint_to_str_prec(num: uint, radix: uint, prec: uint) -> ~str { - return if prec == 0u && num == 0u { - ~"" - } else { - let s = num.to_str_radix(radix); - let len = s.char_len(); - if len < prec { - let diff = prec - len; - let pad = str::from_chars(vec::from_elem(diff, '0')); - pad + s - } else { s } - }; - } - pub fn get_int_precision(cv: Conv) -> uint { - return match cv.precision { - CountIs(c) => c as uint, - CountImplied => 1u - }; - } - - #[deriving(Eq)] - pub enum PadMode { PadSigned, PadUnsigned, PadNozero, PadFloat } - - pub fn pad(cv: Conv, s: &str, head: Option, mode: PadMode, - buf: &mut ~str) { - let headsize = match head { Some(_) => 1, _ => 0 }; - let uwidth : uint = match cv.width { - CountImplied => { - for &c in head.iter() { - buf.push_char(c); - } - return buf.push_str(s); - } - CountIs(width) => { width as uint } - }; - let strlen = s.char_len() + headsize; - if uwidth <= strlen { - for &c in head.iter() { - buf.push_char(c); - } - return buf.push_str(s); - } - let mut padchar = ' '; - let diff = uwidth - strlen; - if have_flag(cv.flags, flag_left_justify) { - for &c in head.iter() { - buf.push_char(c); - } - buf.push_str(s); - do diff.times { - buf.push_char(padchar); - } - return; - } - let (might_zero_pad, signed) = match mode { - PadNozero => (false, true), - PadSigned => (true, true), - PadFloat => (true, true), - PadUnsigned => (true, false) - }; - fn have_precision(cv: Conv) -> bool { - return match cv.precision { CountImplied => false, _ => true }; - } - let zero_padding = { - if might_zero_pad && have_flag(cv.flags, flag_left_zero_pad) && - (!have_precision(cv) || mode == PadFloat) { - padchar = '0'; - true - } else { - false - } - }; - let padstr = str::from_chars(vec::from_elem(diff, padchar)); - // This is completely heinous. If we have a signed value then - // potentially rip apart the intermediate result and insert some - // zeros. It may make sense to convert zero padding to a precision - // instead. - - if signed && zero_padding { - for &head in head.iter() { - if head == '+' || head == '-' || head == ' ' { - buf.push_char(head); - buf.push_str(padstr); - buf.push_str(s); - return; - } - } - } - buf.push_str(padstr); - for &c in head.iter() { - buf.push_char(c); - } - buf.push_str(s); - } - #[inline] - pub fn have_flag(flags: u32, f: u32) -> bool { - flags & f != 0 - } -} - -// Bulk of the tests are in src/test/run-pass/syntax-extension-fmt.rs -#[cfg(test)] -mod test { - #[test] - fn fmt_slice() { - let s = "abc"; - let _s = format!("{}", s); - } -} From 7e6f5bb5c9eaab292a755036656cf62bfc669974 Mon Sep 17 00:00:00 2001 From: reedlepee Date: Wed, 23 Oct 2013 03:25:10 +0530 Subject: [PATCH 08/26] Making ai_next field public --- src/libstd/rt/uv/uvll.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs index 341c5b8c6e16..96c5dd068d0b 100644 --- a/src/libstd/rt/uv/uvll.rs +++ b/src/libstd/rt/uv/uvll.rs @@ -263,7 +263,7 @@ pub struct addrinfo { priv ai_addrlen: size_t, priv ai_canonname: *char, ai_addr: *sockaddr, - priv ai_next: *addrinfo + ai_next: *addrinfo } #[cfg(unix)] pub type uv_uid_t = libc::types::os::arch::posix88::uid_t; From e6d8f06cad4241d7e7eca158814c70ad24c70aed Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 21 Oct 2013 14:16:38 -0700 Subject: [PATCH 09/26] Tidy up asm! usage in libstd --- src/libstd/rt/context.rs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/libstd/rt/context.rs b/src/libstd/rt/context.rs index 7f7545ca230f..bf8f4a63bcaf 100644 --- a/src/libstd/rt/context.rs +++ b/src/libstd/rt/context.rs @@ -391,36 +391,32 @@ pub unsafe fn record_sp_limit(limit: uint) { /// As with the setter, this function does not have a __morestack header and can /// therefore be called in a "we're out of stack" situation. #[inline(always)] -// NOTE: after the next snapshot, can remove the initialization before inline -// assembly due to an improvement in how it's handled, then this specific -// allow directive should get removed. -#[allow(dead_assignment)] pub unsafe fn get_sp_limit() -> uint { return target_get_sp_limit(); // x86-64 #[cfg(target_arch = "x86_64", target_os = "macos")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movq $$0x60+90*8, %rsi movq %gs:(%rsi), $0" : "=r"(limit) :: "rsi" : "volatile"); return limit; } #[cfg(target_arch = "x86_64", target_os = "linux")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movq %fs:112, $0" : "=r"(limit) ::: "volatile"); return limit; } #[cfg(target_arch = "x86_64", target_os = "win32")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movq %gs:0x28, $0" : "=r"(limit) ::: "volatile"); return limit; } #[cfg(target_arch = "x86_64", target_os = "freebsd")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movq %fs:24, $0" : "=r"(limit) ::: "volatile"); return limit; } @@ -428,7 +424,7 @@ pub unsafe fn get_sp_limit() -> uint { // x86 #[cfg(target_arch = "x86", target_os = "macos")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movl $$0x48+90*4, %eax movl %gs:(%eax), $0" : "=r"(limit) :: "eax" : "volatile"); return limit; @@ -436,13 +432,13 @@ pub unsafe fn get_sp_limit() -> uint { #[cfg(target_arch = "x86", target_os = "linux")] #[cfg(target_arch = "x86", target_os = "freebsd")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movl %gs:48, $0" : "=r"(limit) ::: "volatile"); return limit; } #[cfg(target_arch = "x86", target_os = "win32")] #[inline(always)] unsafe fn target_get_sp_limit() -> uint { - let mut limit: uint = 0; + let limit; asm!("movl %fs:0x14, $0" : "=r"(limit) ::: "volatile"); return limit; } From 2cd772bdba10ac5b8449595cc218419c33b9bcf4 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 10 Oct 2013 13:59:55 +1100 Subject: [PATCH 10/26] std::rand: add the Sample and IndependentSample traits. These are a "parameterised" Rand. --- src/libstd/rand/distributions.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 0902100dca60..845d8bbc9525 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -23,6 +23,24 @@ use num; use rand::{Rng,Rand}; +/// Things that can be used to create a random instance of `Support`. +pub trait Sample { + /// Generate a random value of `Support`, using `rng` as the + /// source of randomness. + fn sample(&mut self, rng: &mut R) -> Support; +} + +/// `Sample`s that do not require keeping track of state, so each +/// sample is (statistically) independent of all others, assuming the +/// `Rng` used has this property. +// XXX maybe having this separate is overkill (the only reason is to +// take &self rather than &mut self)? or maybe this should be the +// trait called `Sample` and the other should be `DependentSample`. +pub trait IndependentSample: Sample { + /// Generate a random value. + fn ind_sample(&self, &mut R) -> Support; +} + mod ziggurat_tables; // inlining should mean there is no performance penalty for this From 5aaef138ff4d717ab723ac024c94c92539b4daa7 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 10 Oct 2013 14:30:34 +1100 Subject: [PATCH 11/26] std::rand: Add RandSample for Sample-ing Rand types directly. --- src/libstd/rand/distributions.rs | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 845d8bbc9525..0ee073a926bd 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -41,6 +41,20 @@ pub trait IndependentSample: Sample { fn ind_sample(&self, &mut R) -> Support; } +/// A wrapper for generating types that implement `Rand` via the +/// `Sample` & `IndependentSample` traits. +pub struct RandSample; + +impl Sample for RandSample { + fn sample(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } +} + +impl IndependentSample for RandSample { + fn ind_sample(&self, rng: &mut R) -> Sup { + rng.gen() + } +} + mod ziggurat_tables; // inlining should mean there is no performance penalty for this @@ -166,3 +180,24 @@ impl Rand for Exp1 { pdf, zero_case)) } } + +#[cfg(test)] +mod tests { + use rand::*; + use super::*; + + struct ConstRand(uint); + impl Rand for ConstRand { + fn rand(_: &mut R) -> ConstRand { + ConstRand(0) + } + } + + #[test] + fn test_rand_sample() { + let mut rand_sample = RandSample::; + + assert_eq!(*rand_sample.sample(task_rng()), 0); + assert_eq!(*rand_sample.ind_sample(task_rng()), 0); + } +} From 1420272ddc174996c532e14623d9f897ba5e7a9d Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 10 Oct 2013 20:16:06 +1100 Subject: [PATCH 12/26] std::rand: full exponential & normal distributions Complete the implementation of Exp and Normal started by Exp1 and StandardNormal by creating types implementing Sample & IndependentSample with the appropriate parameters. --- src/libstd/rand/distributions.rs | 140 ++++++++++++++++++++++++++----- 1 file changed, 118 insertions(+), 22 deletions(-) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 0ee073a926bd..6b23bff4c457 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -94,17 +94,6 @@ fn ziggurat(rng: &mut R, /// /// Note that this has to be unwrapped before use as an `f64` (using either /// `*` or `cast::transmute` is safe). -/// -/// # Example -/// -/// ``` -/// use std::rand::distributions::StandardNormal; -/// -/// fn main() { -/// let normal = 2.0 + (*rand::random::()) * 3.0; -/// println!("{} is from a N(2, 9) distribution", normal) -/// } -/// ``` pub struct StandardNormal(f64); impl Rand for StandardNormal { @@ -142,23 +131,52 @@ impl Rand for StandardNormal { } } +/// The `N(mean, std_dev**2)` distribution, i.e. samples from a normal +/// distribution with mean `mean` and standard deviation `std_dev`. +/// +/// # Example +/// +/// ``` +/// use std::rand; +/// use std::rand::distributions::{Normal, IndependentSample}; +/// +/// fn main() { +/// let normal = Normal::new(2.0, 3.0); +/// let v = normal.ind_sample(rand::task_rng()); +/// println!("{} is from a N(2, 9) distribution", v) +/// } +/// ``` +pub struct Normal { + priv mean: f64, + priv std_dev: f64 +} + +impl Normal { + /// Construct a new `Normal` distribution with the given mean and + /// standard deviation. Fails if `std_dev < 0`. + pub fn new(mean: f64, std_dev: f64) -> Normal { + assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); + Normal { + mean: mean, + std_dev: std_dev + } + } +} +impl Sample for Normal { + fn sample(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } +} +impl IndependentSample for Normal { + fn ind_sample(&self, rng: &mut R) -> f64 { + self.mean + self.std_dev * (*rng.gen::()) + } +} + /// A wrapper around an `f64` to generate Exp(1) random numbers. Dividing by /// the desired rate `lambda` will give Exp(lambda) distributed random /// numbers. /// /// Note that this has to be unwrapped before use as an `f64` (using either /// `*` or `cast::transmute` is safe). -/// -/// # Example -/// -/// ``` -/// use std::rand::distributions::Exp1; -/// -/// fn main() { -/// let exp2 = (*rand::random::()) * 0.5; -/// println!("{} is from a Exp(2) distribution", exp2); -/// } -/// ``` pub struct Exp1(f64); // This could be done via `-rng.gen::().ln()` but that is slower. @@ -181,10 +199,53 @@ impl Rand for Exp1 { } } +/// The `Exp(lambda)` distribution; i.e. samples from the exponential +/// distribution with rate parameter `lambda`. +/// +/// This distribution has density function: `f(x) = lambda * +/// exp(-lambda * x)` for `x > 0`. +/// +/// # Example +/// +/// ``` +/// use std::rand; +/// use std::rand::distributions::{Exp, IndependentSample}; +/// +/// fn main() { +/// let exp = Exp::new(2.0); +/// let v = exp.ind_sample(rand::task_rng()); +/// println!("{} is from a Exp(2) distribution", v); +/// } +/// ``` +pub struct Exp { + /// `lambda` stored as `1/lambda`, since this is what we scale by. + priv lambda_inverse: f64 +} + +impl Exp { + /// Construct a new `Exp` with the given shape parameter + /// `lambda`. Fails if `lambda <= 0`. + pub fn new(lambda: f64) -> Exp { + assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0"); + Exp { lambda_inverse: 1.0 / lambda } + } +} + +impl Sample for Exp { + fn sample(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } +} +impl IndependentSample for Exp { + fn ind_sample(&self, rng: &mut R) -> f64 { + (*rng.gen::()) * self.lambda_inverse + } +} + #[cfg(test)] mod tests { use rand::*; use super::*; + use iter::range; + use option::{Some, None}; struct ConstRand(uint); impl Rand for ConstRand { @@ -200,4 +261,39 @@ mod tests { assert_eq!(*rand_sample.sample(task_rng()), 0); assert_eq!(*rand_sample.ind_sample(task_rng()), 0); } + + #[test] + fn test_normal() { + let mut norm = Normal::new(10.0, 10.0); + let rng = task_rng(); + for _ in range(0, 1000) { + norm.sample(rng); + norm.ind_sample(rng); + } + } + #[test] + #[should_fail] + fn test_normal_invalid_sd() { + Normal::new(10.0, -1.0); + } + + #[test] + fn test_exp() { + let mut exp = Exp::new(10.0); + let rng = task_rng(); + for _ in range(0, 1000) { + assert!(exp.sample(rng) >= 0.0); + assert!(exp.ind_sample(rng) >= 0.0); + } + } + #[test] + #[should_fail] + fn test_exp_invalid_lambda_zero() { + Exp::new(0.0); + } + #[test] + #[should_fail] + fn test_exp_invalid_lambda_neg() { + Exp::new(-10.0); + } } From 148f737c199a5c9dd6d349751072add3cc458533 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 10 Oct 2013 20:18:07 +1100 Subject: [PATCH 13/26] std::rand: add distributions::Range for generating [lo, hi). This reifies the computations required for uniformity done by (the old) `Rng.gen_integer_range` (now Rng.gen_range), so that they can be amortised over many invocations, if it is called in a loop. Also, it makes it correct, but using a trait + impls for each type, rather than trying to coerce `Int` + `u64` to do the right thing. This also makes it more extensible, e.g. big integers could & should implement SampleRange. --- src/libextra/base64.rs | 2 +- src/libextra/crypto/cryptoutil.rs | 2 +- src/libextra/flate.rs | 2 +- src/libextra/sort.rs | 12 +- src/libextra/treemap.rs | 2 +- src/libstd/rand/distributions.rs | 4 + src/libstd/rand/mod.rs | 70 +++++---- src/libstd/rand/range.rs | 235 ++++++++++++++++++++++++++++++ src/libstd/rt/comm.rs | 2 +- src/libstd/rt/sched.rs | 2 +- src/test/bench/core-std.rs | 6 +- 11 files changed, 287 insertions(+), 52 deletions(-) create mode 100644 src/libstd/rand/range.rs diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index 3960be466869..429f7adf5f53 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -318,7 +318,7 @@ mod test { use std::vec; do 1000.times { - let times = task_rng().gen_integer_range(1u, 100); + let times = task_rng().gen_range(1u, 100); let v = vec::from_fn(times, |_| random::()); assert_eq!(v.to_base64(STANDARD).from_base64().unwrap(), v); } diff --git a/src/libextra/crypto/cryptoutil.rs b/src/libextra/crypto/cryptoutil.rs index 97b82383d843..bb3524a7d490 100644 --- a/src/libextra/crypto/cryptoutil.rs +++ b/src/libextra/crypto/cryptoutil.rs @@ -365,7 +365,7 @@ pub mod test { digest.reset(); while count < total_size { - let next: uint = rng.gen_integer_range(0, 2 * blocksize + 1); + let next: uint = rng.gen_range(0, 2 * blocksize + 1); let remaining = total_size - count; let size = if next > remaining { remaining } else { next }; digest.input(buffer.slice_to(size)); diff --git a/src/libextra/flate.rs b/src/libextra/flate.rs index 9d6c2e8aa820..3f3b588e8bc1 100644 --- a/src/libextra/flate.rs +++ b/src/libextra/flate.rs @@ -113,7 +113,7 @@ mod tests { let mut r = rand::rng(); let mut words = ~[]; do 20.times { - let range = r.gen_integer_range(1u, 10); + let range = r.gen_range(1u, 10); words.push(r.gen_vec::(range)); } do 20.times { diff --git a/src/libextra/sort.rs b/src/libextra/sort.rs index d884f4f05c17..2a456f8de3eb 100644 --- a/src/libextra/sort.rs +++ b/src/libextra/sort.rs @@ -1069,8 +1069,8 @@ mod big_tests { isSorted(arr); do 3.times { - let i1 = rng.gen_integer_range(0u, n); - let i2 = rng.gen_integer_range(0u, n); + let i1 = rng.gen_range(0u, n); + let i2 = rng.gen_range(0u, n); arr.swap(i1, i2); } tim_sort(arr); // 3sort @@ -1088,7 +1088,7 @@ mod big_tests { isSorted(arr); do (n/100).times { - let idx = rng.gen_integer_range(0u, n); + let idx = rng.gen_range(0u, n); arr[idx] = rng.gen(); } tim_sort(arr); @@ -1141,8 +1141,8 @@ mod big_tests { isSorted(arr); do 3.times { - let i1 = rng.gen_integer_range(0u, n); - let i2 = rng.gen_integer_range(0u, n); + let i1 = rng.gen_range(0u, n); + let i2 = rng.gen_range(0u, n); arr.swap(i1, i2); } tim_sort(arr); // 3sort @@ -1160,7 +1160,7 @@ mod big_tests { isSorted(arr); do (n/100).times { - let idx = rng.gen_integer_range(0u, n); + let idx = rng.gen_range(0u, n); arr[idx] = @rng.gen(); } tim_sort(arr); diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index ad196b32fb2c..7ef9ba76b995 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -1028,7 +1028,7 @@ mod test_treemap { } do 30.times { - let r = rng.gen_integer_range(0, ctrl.len()); + let r = rng.gen_range(0, ctrl.len()); let (key, _) = ctrl.remove(r); assert!(map.remove(&key)); check_structure(&map); diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 6b23bff4c457..b31e72bc697c 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -23,6 +23,10 @@ use num; use rand::{Rng,Rand}; +pub use self::range::Range; + +pub mod range; + /// Things that can be used to create a random instance of `Support`. pub trait Sample { /// Generate a random value of `Support`, using `rng` as the diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index f5c60417bacb..178f5106d284 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -55,17 +55,20 @@ fn main () { use mem::size_of; use unstable::raw::Slice; use cast; +use cmp::Ord; use container::Container; use iter::{Iterator, range}; use local_data; use prelude::*; use str; -use u64; use vec; pub use self::isaac::{IsaacRng, Isaac64Rng}; pub use self::os::OSRng; +use self::distributions::{Range, IndependentSample}; +use self::distributions::range::SampleRange; + pub mod distributions; pub mod isaac; pub mod os; @@ -218,14 +221,14 @@ pub trait Rng { vec::from_fn(len, |_| self.gen()) } - /// Generate a random primitive integer in the range [`low`, - /// `high`). Fails if `low >= high`. + /// Generate a random value in the range [`low`, `high`). Fails if + /// `low >= high`. /// - /// This gives a uniform distribution (assuming this RNG is itself - /// uniform), even for edge cases like `gen_integer_range(0u8, - /// 170)`, which a naive modulo operation would return numbers - /// less than 85 with double the probability to those greater than - /// 85. + /// This is a convenience wrapper around + /// `distributions::Range`. If this function will be called + /// repeatedly with the same arguments, one should use `Range`, as + /// that will amortize the computations that allow for perfect + /// uniformity, as they only happen on initialization. /// /// # Example /// @@ -235,22 +238,15 @@ pub trait Rng { /// /// fn main() { /// let mut rng = rand::task_rng(); - /// let n: uint = rng.gen_integer_range(0u, 10); + /// let n: uint = rng.gen_range(0u, 10); /// println!("{}", n); - /// let m: int = rng.gen_integer_range(-40, 400); + /// let m: float = rng.gen_range(-40.0, 1.3e5); /// println!("{}", m); /// } /// ``` - fn gen_integer_range(&mut self, low: T, high: T) -> T { - assert!(low < high, "RNG.gen_integer_range called with low >= high"); - let range = (high - low).to_u64().unwrap(); - let accept_zone = u64::max_value - u64::max_value % range; - loop { - let rand = self.gen::(); - if rand < accept_zone { - return low + NumCast::from(rand % range).unwrap(); - } - } + fn gen_range(&mut self, low: T, high: T) -> T { + assert!(low < high, "Rng.gen_range called with low >= high"); + Range::new(low, high).ind_sample(self) } /// Return a bool with a 1 in n chance of true @@ -267,7 +263,7 @@ pub trait Rng { /// } /// ``` fn gen_weighted_bool(&mut self, n: uint) -> bool { - n == 0 || self.gen_integer_range(0, n) == 0 + n == 0 || self.gen_range(0, n) == 0 } /// Return a random string of the specified length composed of @@ -317,7 +313,7 @@ pub trait Rng { if values.is_empty() { None } else { - Some(&values[self.gen_integer_range(0u, values.len())]) + Some(&values[self.gen_range(0u, values.len())]) } } @@ -368,7 +364,7 @@ pub trait Rng { if total == 0u { return None; } - let chosen = self.gen_integer_range(0u, total); + let chosen = self.gen_range(0u, total); let mut so_far = 0u; for item in v.iter() { so_far += item.weight; @@ -447,7 +443,7 @@ pub trait Rng { // invariant: elements with index >= i have been locked in place. i -= 1u; // lock element i in place. - values.swap(i, self.gen_integer_range(0u, i + 1u)); + values.swap(i, self.gen_range(0u, i + 1u)); } } @@ -473,7 +469,7 @@ pub trait Rng { continue } - let k = self.gen_integer_range(0, i + 1); + let k = self.gen_range(0, i + 1); if k < reservoir.len() { reservoir[k] = elem } @@ -760,36 +756,36 @@ mod test { } #[test] - fn test_gen_integer_range() { + fn test_gen_range() { let mut r = rng(); for _ in range(0, 1000) { - let a = r.gen_integer_range(-3i, 42); + let a = r.gen_range(-3i, 42); assert!(a >= -3 && a < 42); - assert_eq!(r.gen_integer_range(0, 1), 0); - assert_eq!(r.gen_integer_range(-12, -11), -12); + assert_eq!(r.gen_range(0, 1), 0); + assert_eq!(r.gen_range(-12, -11), -12); } for _ in range(0, 1000) { - let a = r.gen_integer_range(10, 42); + let a = r.gen_range(10, 42); assert!(a >= 10 && a < 42); - assert_eq!(r.gen_integer_range(0, 1), 0); - assert_eq!(r.gen_integer_range(3_000_000u, 3_000_001), 3_000_000); + assert_eq!(r.gen_range(0, 1), 0); + assert_eq!(r.gen_range(3_000_000u, 3_000_001), 3_000_000); } } #[test] #[should_fail] - fn test_gen_integer_range_fail_int() { + fn test_gen_range_fail_int() { let mut r = rng(); - r.gen_integer_range(5i, -2); + r.gen_range(5i, -2); } #[test] #[should_fail] - fn test_gen_integer_range_fail_uint() { + fn test_gen_range_fail_uint() { let mut r = rng(); - r.gen_integer_range(5u, 2u); + r.gen_range(5u, 2u); } #[test] @@ -894,7 +890,7 @@ mod test { let mut r = task_rng(); r.gen::(); assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]); - assert_eq!(r.gen_integer_range(0u, 1u), 0u); + assert_eq!(r.gen_range(0u, 1u), 0u); } #[test] diff --git a/src/libstd/rand/range.rs b/src/libstd/rand/range.rs new file mode 100644 index 000000000000..1b805a0b8f76 --- /dev/null +++ b/src/libstd/rand/range.rs @@ -0,0 +1,235 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Generating numbers between two others. + +// this is surprisingly complicated to be both generic & correct + +use cmp::Ord; +use num::Bounded; +use rand::Rng; +use rand::distributions::{Sample, IndependentSample}; + +/// Sample values uniformly between two bounds. +/// +/// This gives a uniform distribution (assuming the RNG used to sample +/// it is itself uniform & the `SampleRange` implementation for the +/// given type is correct), even for edge cases like `low = 0u8`, +/// `high = 170u8`, for which a naive modulo operation would return +/// numbers less than 85 with double the probability to those greater +/// than 85. +/// +/// Types should attempt to sample in `[low, high)`, i.e., not +/// including `high`, but this may be very difficult. All the +/// primitive integer types satisfy this property, and the float types +/// normally satisfy it, but rounding may mean `high` can occur. +/// +/// # Example +/// +/// ```rust +/// use std::rand; +/// use std::rand::distributions::{IndependentSample, Range}; +/// +/// fn main() { +/// let between = Range::new(10u, 10000u); +/// let rng = rand::task_rng(); +/// let mut sum = 0; +/// for _ in range(0, 1000) { +/// sum += between.ind_sample(rng); +/// } +/// println!("{}", sum); +/// } +/// ``` +pub struct Range { + priv low: X, + priv range: X, + priv accept_zone: X +} + +impl Range { + /// Create a new `Range` instance that samples uniformly from + /// `[low, high)`. Fails if `low >= high`. + pub fn new(low: X, high: X) -> Range { + assert!(low < high, "Range::new called with `low >= high`"); + SampleRange::construct_range(low, high) + } +} + +impl Sample for Range { + #[inline] + fn sample(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } +} +impl IndependentSample for Range { + fn ind_sample(&self, rng: &mut R) -> Sup { + SampleRange::sample_range(self, rng) + } +} + +/// The helper trait for types that have a sensible way to sample +/// uniformly between two values. This should not be used directly, +/// and is only to facilitate `Range`. +pub trait SampleRange { + /// Construct the `Range` object that `sample_range` + /// requires. This should not ever be called directly, only via + /// `Range::new`, which will check that `low < high`, so this + /// function doesn't have to repeat the check. + fn construct_range(low: Self, high: Self) -> Range; + + /// Sample a value from the given `Range` with the given `Rng` as + /// a source of randomness. + fn sample_range(r: &Range, rng: &mut R) -> Self; +} + +macro_rules! integer_impl { + ($ty:ty, $unsigned:ty) => { + impl SampleRange for $ty { + // we play free and fast with unsigned vs signed here + // (when $ty is signed), but that's fine, since the + // contract of this macro is for $ty and $unsigned to be + // "bit-equal", so casting between them is a no-op & a + // bijection. + + fn construct_range(low: $ty, high: $ty) -> Range<$ty> { + let range = high as $unsigned - low as $unsigned; + let unsigned_max: $unsigned = Bounded::max_value(); + + // this is the largest number that fits into $unsigned + // that `range` divides evenly, so, if we've sampled + // `n` uniformly from this region, then `n % range` is + // uniform in [0, range) + let zone = unsigned_max - unsigned_max % range; + + Range { + low: low, + range: range as $ty, + accept_zone: zone as $ty + } + } + #[inline] + fn sample_range(r: &Range<$ty>, rng: &mut R) -> $ty { + loop { + // rejection sample + let v = rng.gen::<$unsigned>(); + // until we find something that fits into the + // region which r.range evenly divides (this will + // be uniformly distributed) + if v < r.accept_zone as $unsigned { + // and return it, with some adjustments + return r.low + (v % r.range as $unsigned) as $ty; + } + } + } + } + } +} + +integer_impl! { i8, u8 } +integer_impl! { i16, u16 } +integer_impl! { i32, u32 } +integer_impl! { i64, u64 } +integer_impl! { int, uint } +integer_impl! { u8, u8 } +integer_impl! { u16, u16 } +integer_impl! { u32, u32 } +integer_impl! { u64, u64 } +integer_impl! { uint, uint } + +macro_rules! float_impl { + ($ty:ty) => { + impl SampleRange for $ty { + fn construct_range(low: $ty, high: $ty) -> Range<$ty> { + Range { + low: low, + range: high - low, + accept_zone: 0.0 // unused + } + } + fn sample_range(r: &Range<$ty>, rng: &mut R) -> $ty { + r.low + r.range * rng.gen() + } + } + } +} + +float_impl! { f32 } +float_impl! { f64 } + +#[cfg(test)] +mod tests { + use super::*; + use rand::*; + use num::Bounded; + use iter::range; + use option::{Some, None}; + use vec::ImmutableVector; + + #[should_fail] + #[test] + fn test_range_bad_limits_equal() { + Range::new(10, 10); + } + #[should_fail] + #[test] + fn test_range_bad_limits_flipped() { + Range::new(10, 5); + } + + #[test] + fn test_integers() { + let rng = task_rng(); + macro_rules! t ( + ($($ty:ty),*) => {{ + $( + let v: &[($ty, $ty)] = [(0, 10), + (10, 127), + (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) { + let v = sampler.sample(rng); + assert!(low <= v && v < high); + let v = sampler.ind_sample(rng); + assert!(low <= v && v < high); + } + } + )* + }} + ); + t!(i8, i16, i32, i64, int, + u8, u16, u32, u64, uint) + } + + #[test] + fn test_floats() { + let rng = task_rng(); + macro_rules! t ( + ($($ty:ty),*) => {{ + $( + let v: &[($ty, $ty)] = [(0.0, 100.0), + (-1e35, -1e25), + (1e-35, 1e-25), + (-1e35, 1e35)]; + for &(low, high) in v.iter() { + let mut sampler: Range<$ty> = Range::new(low, high); + for _ in range(0, 1000) { + let v = sampler.sample(rng); + assert!(low <= v && v < high); + let v = sampler.ind_sample(rng); + assert!(low <= v && v < high); + } + } + )* + }} + ); + + t!(f32, f64) + } + +} diff --git a/src/libstd/rt/comm.rs b/src/libstd/rt/comm.rs index 4eae8bdc9a82..967dedd94a62 100644 --- a/src/libstd/rt/comm.rs +++ b/src/libstd/rt/comm.rs @@ -1117,7 +1117,7 @@ mod test { let total = stress_factor() + 10; let mut rng = rand::rng(); do total.times { - let msgs = rng.gen_integer_range(0u, 10); + let msgs = rng.gen_range(0u, 10); let pipe_clone = pipe.clone(); let end_chan_clone = end_chan.clone(); do spawntask_random { diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index 336d2518e437..c1090d360106 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -431,7 +431,7 @@ impl Scheduler { fn try_steals(&mut self) -> Option<~Task> { let work_queues = &mut self.work_queues; let len = work_queues.len(); - let start_index = self.rng.gen_integer_range(0, len); + let start_index = self.rng.gen_range(0, len); for index in range(0, len).map(|i| (i + start_index) % len) { match work_queues[index].steal() { Some(task) => { diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index f549f747ef79..dbd1edffe782 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -90,7 +90,7 @@ fn vec_plus() { let mut v = ~[]; let mut i = 0; while i < 1500 { - let rv = vec::from_elem(r.gen_integer_range(0u, i + 1), i); + let rv = vec::from_elem(r.gen_range(0u, i + 1), i); if r.gen() { v.push_all_move(rv); } else { @@ -106,7 +106,7 @@ fn vec_append() { let mut v = ~[]; let mut i = 0; while i < 1500 { - let rv = vec::from_elem(r.gen_integer_range(0u, i + 1), i); + let rv = vec::from_elem(r.gen_range(0u, i + 1), i); if r.gen() { v = vec::append(v, rv); } @@ -122,7 +122,7 @@ fn vec_push_all() { let mut v = ~[]; for i in range(0u, 1500) { - let mut rv = vec::from_elem(r.gen_integer_range(0u, i + 1), i); + let mut rv = vec::from_elem(r.gen_range(0u, i + 1), i); if r.gen() { v.push_all(rv); } From e0eb1280867e14bdb123c3b19eda93b8906899d2 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 11 Oct 2013 17:25:40 +1100 Subject: [PATCH 14/26] std::rand: documentation & references. Most importantly, links to the papers/references for the core algorithms (the RNG ones & the distribution ones). --- src/libstd/rand/distributions.rs | 73 ++++++++++++++++++++------------ src/libstd/rand/isaac.rs | 24 ++++++++--- src/libstd/rand/mod.rs | 31 +++++++++++--- src/libstd/rand/os.rs | 16 +++++-- src/rt/rust_builtin.cpp | 2 + 5 files changed, 102 insertions(+), 44 deletions(-) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index b31e72bc697c..23726490b4a2 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Sampling from random distributions +/*! +Sampling from random distributions. -// Some implementations use the Ziggurat method -// https://en.wikipedia.org/wiki/Ziggurat_algorithm -// -// The version used here is ZIGNOR [Doornik 2005, "An Improved -// Ziggurat Method to Generate Normal Random Samples"] which is slower -// (about double, it generates an extra random number) than the -// canonical version [Marsaglia & Tsang 2000, "The Ziggurat Method for -// Generating Random Variables"], but more robust. If one wanted, one -// could implement VIZIGNOR the ZIGNOR paper for more speed. +This is a generalization of `Rand` to allow parameters to control the +exact properties of the generated values, e.g. the mean and standard +deviation of a normal distribution. The `Sample` trait is the most +general, and allows for generating values that change some state +internally. The `IndependentSample` trait is for generating values +that do not need to record state. + +*/ use num; use rand::{Rng,Rand}; @@ -27,16 +27,18 @@ pub use self::range::Range; pub mod range; -/// Things that can be used to create a random instance of `Support`. +/// Types that can be used to create a random instance of `Support`. pub trait Sample { /// Generate a random value of `Support`, using `rng` as the /// source of randomness. fn sample(&mut self, rng: &mut R) -> Support; } -/// `Sample`s that do not require keeping track of state, so each -/// sample is (statistically) independent of all others, assuming the -/// `Rng` used has this property. +/// `Sample`s that do not require keeping track of state. +/// +/// Since no state is recored, each sample is (statistically) +/// independent of all others, assuming the `Rng` used has this +/// property. // XXX maybe having this separate is overkill (the only reason is to // take &self rather than &mut self)? or maybe this should be the // trait called `Sample` and the other should be `DependentSample`. @@ -91,13 +93,19 @@ fn ziggurat(rng: &mut R, } } -/// A wrapper around an `f64` to generate N(0, 1) random numbers (a.k.a. a -/// standard normal, or Gaussian). Multiplying the generated values by the -/// desired standard deviation `sigma` then adding the desired mean `mu` will -/// give N(mu, sigma^2) distributed random numbers. +/// A wrapper around an `f64` to generate N(0, 1) random numbers +/// (a.k.a. a standard normal, or Gaussian). /// -/// Note that this has to be unwrapped before use as an `f64` (using either -/// `*` or `cast::transmute` is safe). +/// See `Normal` for the general normal distribution. That this has to +/// be unwrapped before use as an `f64` (using either `*` or +/// `cast::transmute` is safe). +/// +/// Implemented via the ZIGNOR variant[1] of the Ziggurat method. +/// +/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to +/// Generate Normal Random +/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield +/// College, Oxford pub struct StandardNormal(f64); impl Rand for StandardNormal { @@ -135,8 +143,10 @@ impl Rand for StandardNormal { } } -/// The `N(mean, std_dev**2)` distribution, i.e. samples from a normal -/// distribution with mean `mean` and standard deviation `std_dev`. +/// The normal distribution `N(mean, std_dev**2)`. +/// +/// This uses the ZIGNOR variant of the Ziggurat method, see +/// `StandardNormal` for more details. /// /// # Example /// @@ -175,12 +185,20 @@ impl IndependentSample for Normal { } } -/// A wrapper around an `f64` to generate Exp(1) random numbers. Dividing by -/// the desired rate `lambda` will give Exp(lambda) distributed random -/// numbers. +/// A wrapper around an `f64` to generate Exp(1) random numbers. /// -/// Note that this has to be unwrapped before use as an `f64` (using either +/// See `Exp` for the general exponential distribution.Note that this + // has to be unwrapped before use as an `f64` (using either /// `*` or `cast::transmute` is safe). +/// +/// Implemented via the ZIGNOR variant[1] of the Ziggurat method. The +/// exact description in the paper was adjusted to use tables for the +/// exponential distribution rather than normal. +/// +/// [1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to +/// Generate Normal Random +/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield +/// College, Oxford pub struct Exp1(f64); // This could be done via `-rng.gen::().ln()` but that is slower. @@ -203,8 +221,7 @@ impl Rand for Exp1 { } } -/// The `Exp(lambda)` distribution; i.e. samples from the exponential -/// distribution with rate parameter `lambda`. +/// The exponential distribution `Exp(lambda)`. /// /// This distribution has density function: `f(x) = lambda * /// exp(-lambda * x)` for `x > 0`. diff --git a/src/libstd/rand/isaac.rs b/src/libstd/rand/isaac.rs index 0068b60cfa51..2fd58d0314e7 100644 --- a/src/libstd/rand/isaac.rs +++ b/src/libstd/rand/isaac.rs @@ -18,10 +18,15 @@ use option::{None, Some}; 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). +/// A random number generator that uses the ISAAC algorithm[1]. /// -/// The ISAAC algorithm is suitable for cryptographic purposes. +/// The ISAAC algorithm is generally accepted as suitable for +/// cryptographic purposes, but this implementation has not be +/// verified as such. Prefer a generator like `OSRng` that defers to +/// the operating system for cases that need high security. +/// +/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number +/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html) pub struct IsaacRng { priv cnt: u32, priv rsl: [u32, .. RAND_SIZE], @@ -212,11 +217,16 @@ impl<'self> SeedableRng<&'self [u32]> for IsaacRng { static RAND_SIZE_64_LEN: uint = 8; static RAND_SIZE_64: uint = 1 << RAND_SIZE_64_LEN; -/// A random number generator that uses the 64-bit variant of the -/// [ISAAC -/// algorithm](http://en.wikipedia.org/wiki/ISAAC_%28cipher%29). +/// A random number generator that uses ISAAC-64[1], the 64-bit +/// variant of the ISAAC algorithm. /// -/// The ISAAC algorithm is suitable for cryptographic purposes. +/// The ISAAC algorithm is generally accepted as suitable for +/// cryptographic purposes, but this implementation has not be +/// verified as such. Prefer a generator like `OSRng` that defers to +/// the operating system for cases that need high security. +/// +/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number +/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html) pub struct Isaac64Rng { priv cnt: uint, priv rsl: [u64, .. RAND_SIZE_64], diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 178f5106d284..b94d8d72e372 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -28,6 +28,23 @@ from an operating-system source of randomness, e.g. `/dev/urandom` on Unix systems, and will automatically reseed itself from this source after generating 32 KiB of random data. +# Cryptographic security + +An application that requires random numbers for cryptographic purposes +should prefer `OSRng`, which reads randomness from one of the source +that the operating system provides (e.g. `/dev/urandom` on +Unixes). The other random number generators provided by this module +are either known to be insecure (`XorShiftRng`), or are not verified +to be secure (`IsaacRng`, `Isaac64Rng` and `StdRng`). + +*Note*: on Linux, `/dev/random` is more secure than `/dev/urandom`, +but it is a blocking RNG, and will wait until it has determined that +it has collected enough entropy to fulfill a request for random +data. It can be used with the `Rng` trait provided by this module by +opening the file and passing it to `reader::ReaderRng`. Since it +blocks, `/dev/random` should only be used to retrieve small amounts of +randomness. + # Examples ```rust @@ -516,8 +533,8 @@ pub trait SeedableRng: Rng { /// 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 +/// It returns the strongest `Rng` algorithm currently implemented in +/// pure Rust. If you require a specifically seeded `Rng` for /// consistency over time you should pick one algorithm and create the /// `Rng` yourself. /// @@ -592,12 +609,16 @@ pub fn weak_rng() -> XorShiftRng { XorShiftRng::new() } -/// An [Xorshift random number -/// generator](http://en.wikipedia.org/wiki/Xorshift). +/// An Xorshift[1] random number +/// generator. /// /// 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`. +/// requirements, use a more secure one such as `IsaacRng` or `OSRng`. +/// +/// [1]: Marsaglia, George (July 2003). ["Xorshift +/// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of +/// Statistical Software*. Vol. 8 (Issue 14). pub struct XorShiftRng { priv x: u32, priv y: u32, diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 4c8cf06c55e8..5ed8d6b10d1b 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -30,8 +30,12 @@ type HCRYPTPROV = c_long; // assume they work when we call them. /// A random number generator that retrieves randomness straight from -/// the operating system. On Unix-like systems this reads from -/// `/dev/urandom`, on Windows this uses `CryptGenRandom`. +/// the operating system. Platform sources: +/// +/// - Unix-like systems (Linux, Android, Mac OSX): read directly from +/// `/dev/urandom`. +/// - Windows: calls `CryptGenRandom`, using the default cryptographic +/// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] @@ -39,8 +43,12 @@ pub struct OSRng { priv inner: ReaderRng } /// A random number generator that retrieves randomness straight from -/// the operating system. On Unix-like systems this reads from -/// `/dev/urandom`, on Windows this uses `CryptGenRandom`. +/// the operating system. Platform sources: +/// +/// - Unix-like systems (Linux, Android, Mac OSX): read directly from +/// `/dev/urandom`. +/// - Windows: calls `CryptGenRandom`, using the default cryptographic +/// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(windows)] diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index 17f05b590905..770205376616 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -672,6 +672,8 @@ extern "C" CDECL void rust_win32_rand_acquire(HCRYPTPROV* phProv) { win32_require (_T("CryptAcquireContext"), + // changes to the parameters here should be reflected in the docs of + // std::rand::os::OSRng CryptAcquireContext(phProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT|CRYPT_SILENT)); From ed5f2d7c7c673dcbadcf71444251cebe72e6345b Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 11 Oct 2013 19:38:32 +1100 Subject: [PATCH 15/26] std::rand: optimise & document ziggurat. Before: test rand::distributions::bench::rand_exp ... bench: 1399 ns/iter (+/- 124) = 571 MB/s test rand::distributions::bench::rand_normal ... bench: 1611 ns/iter (+/- 123) = 496 MB/s After: test rand::distributions::bench::rand_exp ... bench: 712 ns/iter (+/- 43) = 1123 MB/s test rand::distributions::bench::rand_normal ... bench: 1007 ns/iter (+/- 81) = 794 MB/s --- src/libstd/rand/distributions.rs | 80 ++++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 8 deletions(-) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 23726490b4a2..4a025ae05d7e 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -63,21 +63,48 @@ impl IndependentSample for RandSample { mod ziggurat_tables; -// inlining should mean there is no performance penalty for this -#[inline] + +/// Sample a random number using the Ziggurat method (specifically the +/// ZIGNOR variant from Doornik 2005). Most of the arguments are +/// directly from the paper: +/// +/// * `rng`: source of randomness +/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. +/// * `X`: the $x_i$ abscissae. +/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) +/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ +/// * `pdf`: the probability density function +/// * `zero_case`: manual sampling from the tail when we chose the +/// bottom box (i.e. i == 0) + +// the perf improvement (25-50%) is definitely worth the extra code +// size from force-inlining. +#[inline(always)] fn ziggurat(rng: &mut R, - center_u: bool, + symmetric: bool, X: ziggurat_tables::ZigTable, F: ziggurat_tables::ZigTable, F_DIFF: ziggurat_tables::ZigTable, - pdf: &'static fn(f64) -> f64, // probability density function + pdf: &'static fn(f64) -> f64, zero_case: &'static fn(&mut R, f64) -> f64) -> f64 { + static SCALE: f64 = (1u64 << 53) as f64; loop { - let u = if center_u {2.0 * rng.gen() - 1.0} else {rng.gen()}; - let i: uint = rng.gen::() & 0xff; + // reimplement the f64 generation as an optimisation suggested + // by the Doornik paper: we have a lot of precision-space + // (i.e. there are 11 bits of the 64 of a u64 to use after + // creating a f64), so we might as well reuse some to save + // generating a whole extra random number. (Seems to be 15% + // faster.) + let bits: u64 = rng.gen(); + let i = (bits & 0xff) as uint; + let f = (bits >> 11) as f64 / SCALE; + + // u is either U(-1, 1) or U(0, 1) depending on if this is a + // symmetric distribution or not. + let u = if symmetric {2.0 * f - 1.0} else {f}; let x = u * X[i]; - let test_x = if center_u {num::abs(x)} else {x}; + let test_x = if symmetric {num::abs(x)} else {x}; // algebraically equivalent to |u| < X[i+1]/X[i] (or u < X[i+1]/X[i]) if test_x < X[i + 1] { @@ -87,7 +114,7 @@ fn ziggurat(rng: &mut R, return zero_case(rng, u); } // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 - if F[i+1] + F_DIFF[i+1] * rng.gen() < pdf(x) { + if F[i + 1] + F_DIFF[i + 1] * rng.gen() < pdf(x) { return x; } } @@ -318,3 +345,40 @@ mod tests { Exp::new(-10.0); } } + +#[cfg(test)] +mod bench { + use extra::test::BenchHarness; + use rand::*; + use super::*; + use iter::range; + use option::{Some, None}; + use mem::size_of; + + static N: u64 = 100; + + #[bench] + fn rand_normal(bh: &mut BenchHarness) { + let mut rng = XorShiftRng::new(); + let mut normal = Normal::new(-2.71828, 3.14159); + + do bh.iter { + for _ in range(0, N) { + normal.sample(&mut rng); + } + } + bh.bytes = size_of::() as u64 * N; + } + #[bench] + fn rand_exp(bh: &mut BenchHarness) { + let mut rng = XorShiftRng::new(); + let mut exp = Exp::new(2.71828 * 3.14159); + + do bh.iter { + for _ in range(0, N) { + exp.sample(&mut rng); + } + } + bh.bytes = size_of::() as u64 * N; + } +} From 83aa1abb19ee290655ed03053e26cdb2662242c4 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 11 Oct 2013 22:09:06 +1100 Subject: [PATCH 16/26] std::rand: lengthen the RNG benchmarks. This makes them more representative, as the `bh.iter` is a smaller percentage of the total time. --- src/libstd/rand/mod.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index b94d8d72e372..2d2c6e794f83 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -970,41 +970,53 @@ mod bench { use extra::test::BenchHarness; use rand::*; use mem::size_of; + use iter::range; + use option::{Some, None}; + + static N: u64 = 100; #[bench] fn rand_xorshift(bh: &mut BenchHarness) { let mut rng = XorShiftRng::new(); do bh.iter { - rng.gen::(); + for _ in range(0, N) { + rng.gen::(); + } } - bh.bytes = size_of::() as u64; + bh.bytes = size_of::() as u64 * N; } #[bench] fn rand_isaac(bh: &mut BenchHarness) { let mut rng = IsaacRng::new(); do bh.iter { - rng.gen::(); + for _ in range(0, N) { + rng.gen::(); + } } - bh.bytes = size_of::() as u64; + bh.bytes = size_of::() as u64 * N; } #[bench] fn rand_isaac64(bh: &mut BenchHarness) { let mut rng = Isaac64Rng::new(); do bh.iter { - rng.gen::(); + for _ in range(0, N) { + rng.gen::(); + } } - bh.bytes = size_of::() as u64; + bh.bytes = size_of::() as u64 * N; } #[bench] fn rand_std(bh: &mut BenchHarness) { let mut rng = StdRng::new(); do bh.iter { - rng.gen::(); + for _ in range(0, N) { + rng.gen::(); + } } - bh.bytes = size_of::() as u64; + bh.bytes = size_of::() as u64 * N; } #[bench] From 0bba73c0d156df8f22c64ef4f4c50910fe31cf31 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 12 Oct 2013 02:15:22 +1100 Subject: [PATCH 17/26] std::rand: move Weighted to distributions. A user constructs the WeightedChoice distribution and then samples from it, which allows it to use binary search internally. --- src/libstd/rand/distributions.rs | 208 ++++++++++++++++++++++++++++++- src/libstd/rand/mod.rs | 131 ------------------- 2 files changed, 207 insertions(+), 132 deletions(-) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 4a025ae05d7e..e7bcf8ce5d3a 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -20,8 +20,11 @@ that do not need to record state. */ +use iter::range; +use option::{Some, None}; use num; use rand::{Rng,Rand}; +use clone::Clone; pub use self::range::Range; @@ -61,8 +64,128 @@ impl IndependentSample for RandSample { } } -mod ziggurat_tables; +/// A value with a particular weight for use with `WeightedChoice`. +pub struct Weighted { + /// The numerical weight of this item + weight: uint, + /// The actual item which is being weighted + item: T, +} +/// A distribution that selects from a finite collection of weighted items. +/// +/// Each item has an associated weight that influences how likely it +/// is to be chosen: higher weight is more likely. +/// +/// The `Clone` restriction is a limitation of the `Sample` and +/// `IndepedentSample` traits. Note that `&T` is (cheaply) `Clone` for +/// all `T`, as is `uint`, so one can store references or indices into +/// another vector. +/// +/// # Example +/// +/// ```rust +/// use std::rand; +/// use std::rand::distributions::{Weighted, WeightedChoice, IndepedentSample}; +/// +/// fn main() { +/// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' }, +/// Weighted { weight: 4, item: 'b' }, +/// Weighted { weight: 1, item: 'c' }]); +/// let rng = rand::task_rng(); +/// for _ in range(0, 16) { +/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice. +/// println!("{}", wc.ind_sample(rng)); +/// } +/// } +/// ``` +pub struct WeightedChoice { + priv items: ~[Weighted], + priv weight_range: Range +} + +impl WeightedChoice { + /// Create a new `WeightedChoice`. + /// + /// Fails if: + /// - `v` is empty + /// - the total weight is 0 + /// - the total weight is larger than a `uint` can contain. + pub fn new(mut items: ~[Weighted]) -> WeightedChoice { + // strictly speaking, this is subsumed by the total weight == 0 case + assert!(!items.is_empty(), "WeightedChoice::new called with no items"); + + let mut running_total = 0u; + + // we convert the list from individual weights to cumulative + // weights so we can binary search. This *could* drop elements + // with weight == 0 as an optimisation. + for item in items.mut_iter() { + running_total = running_total.checked_add(&item.weight) + .expect("WeightedChoice::new called with a total weight larger \ + than a uint can contain"); + + item.weight = running_total; + } + assert!(running_total != 0, "WeightedChoice::new called with a total weight of 0"); + + WeightedChoice { + items: items, + // we're likely to be generating numbers in this range + // relatively often, so might as well cache it + weight_range: Range::new(0, running_total) + } + } +} + +impl Sample for WeightedChoice { + fn sample(&mut self, rng: &mut R) -> T { self.ind_sample(rng) } +} + +impl IndependentSample for WeightedChoice { + fn ind_sample(&self, rng: &mut R) -> T { + // we want to find the first element that has cumulative + // weight > sample_weight, which we do by binary since the + // cumulative weights of self.items are sorted. + + // choose a weight in [0, total_weight) + let sample_weight = self.weight_range.ind_sample(rng); + + // short circuit when it's the first item + if sample_weight < self.items[0].weight { + return self.items[0].item.clone(); + } + + let mut idx = 0; + let mut modifier = self.items.len(); + + // now we know that every possibility has an element to the + // left, so we can just search for the last element that has + // cumulative weight <= sample_weight, then the next one will + // be "it". (Note that this greatest element will never be the + // last element of the vector, since sample_weight is chosen + // in [0, total_weight) and the cumulative weight of the last + // one is exactly the total weight.) + while modifier > 1 { + let i = idx + modifier / 2; + if self.items[i].weight <= sample_weight { + // we're small, so look to the right, but allow this + // exact element still. + idx = i; + // we need the `/ 2` to round up otherwise we'll drop + // the trailing elements when `modifier` is odd. + modifier += 1; + } else { + // otherwise we're too big, so go left. (i.e. do + // nothing) + } + modifier /= 2; + } + return self.items[idx + 1].item.clone(); + } +} + +mod ziggurat_tables; /// Sample a random number using the Ziggurat method (specifically the /// ZIGNOR variant from Doornik 2005). Most of the arguments are @@ -302,6 +425,18 @@ mod tests { } } + // 0, 1, 2, 3, ... + struct CountingRng { i: u32 } + impl Rng for CountingRng { + fn next_u32(&mut self) -> u32 { + self.i += 1; + self.i - 1 + } + fn next_u64(&mut self) -> u64 { + self.next_u32() as u64 + } + } + #[test] fn test_rand_sample() { let mut rand_sample = RandSample::; @@ -344,6 +479,77 @@ mod tests { fn test_exp_invalid_lambda_neg() { Exp::new(-10.0); } + + #[test] + fn test_weighted_choice() { + // this makes assumptions about the internal implementation of + // WeightedChoice, specifically: it doesn't reorder the items, + // it doesn't do weird things to the RNG (so 0 maps to 0, 1 to + // 1, internally; modulo a modulo operation). + + macro_rules! t ( + ($items:expr, $expected:expr) => {{ + let wc = WeightedChoice::new($items); + let expected = $expected; + + let mut rng = CountingRng { i: 0 }; + + for &val in expected.iter() { + assert_eq!(wc.ind_sample(&mut rng), val) + } + }} + ); + + t!(~[Weighted { weight: 1, item: 10}], ~[10]); + + // skip some + t!(~[Weighted { weight: 0, item: 20}, + Weighted { weight: 2, item: 21}, + Weighted { weight: 0, item: 22}, + Weighted { weight: 1, item: 23}], + ~[21,21, 23]); + + // different weights + t!(~[Weighted { weight: 4, item: 30}, + Weighted { weight: 3, item: 31}], + ~[30,30,30,30, 31,31,31]); + + // check that we're binary searching + // correctly with some vectors of odd + // length. + t!(~[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}], + ~[40, 41, 42, 43, 44]); + t!(~[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}], + ~[50, 51, 52, 53, 54, 55, 56]); + } + + #[test] #[should_fail] + fn test_weighted_choice_no_items() { + WeightedChoice::::new(~[]); + } + #[test] #[should_fail] + fn test_weighted_choice_zero_weight() { + WeightedChoice::new(~[Weighted { weight: 0, item: 0}, + Weighted { weight: 0, item: 1}]); + } + #[test] #[should_fail] + fn test_weighted_choice_weight_overflows() { + let x = (-1) as uint / 2; // x + x + 2 is the overflow + WeightedChoice::new(~[Weighted { weight: x, item: 0 }, + Weighted { weight: 1, item: 1 }, + Weighted { weight: x, item: 2 }, + Weighted { weight: 1, item: 3 }]); + } } #[cfg(test)] diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 2d2c6e794f83..a372eb1f11ad 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -100,14 +100,6 @@ pub trait Rand { fn rand(rng: &mut R) -> Self; } -/// A value with a particular weight compared to other values -pub struct Weighted { - /// The numerical weight of this item - weight: uint, - /// The actual item which is being weighted - item: T, -} - /// A random number generator pub trait Rng { /// Return the next random u32. This rarely needs to be called @@ -334,91 +326,6 @@ pub trait Rng { } } - /// Choose an item respecting the relative weights, failing if the sum of - /// the weights is 0 - /// - /// # Example - /// - /// ```rust - /// use std::rand; - /// use std::rand::Rng; - /// - /// fn main() { - /// let mut rng = rand::rng(); - /// let x = [rand::Weighted {weight: 4, item: 'a'}, - /// rand::Weighted {weight: 2, item: 'b'}, - /// rand::Weighted {weight: 2, item: 'c'}]; - /// println!("{}", rng.choose_weighted(x)); - /// } - /// ``` - fn choose_weighted(&mut self, v: &[Weighted]) -> T { - self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0") - } - - /// Choose Some(item) respecting the relative weights, returning none if - /// the sum of the weights is 0 - /// - /// # Example - /// - /// ```rust - /// use std::rand; - /// use std::rand::Rng; - /// - /// fn main() { - /// let mut rng = rand::rng(); - /// let x = [rand::Weighted {weight: 4, item: 'a'}, - /// rand::Weighted {weight: 2, item: 'b'}, - /// rand::Weighted {weight: 2, item: 'c'}]; - /// println!("{:?}", rng.choose_weighted_option(x)); - /// } - /// ``` - fn choose_weighted_option(&mut self, v: &[Weighted]) - -> Option { - let mut total = 0u; - for item in v.iter() { - total += item.weight; - } - if total == 0u { - return None; - } - let chosen = self.gen_range(0u, total); - let mut so_far = 0u; - for item in v.iter() { - so_far += item.weight; - if so_far > chosen { - return Some(item.item.clone()); - } - } - unreachable!(); - } - - /// Return a vec containing copies of the items, in order, where - /// the weight of the item determines how many copies there are - /// - /// # Example - /// - /// ```rust - /// use std::rand; - /// use std::rand::Rng; - /// - /// fn main() { - /// let mut rng = rand::rng(); - /// let x = [rand::Weighted {weight: 4, item: 'a'}, - /// rand::Weighted {weight: 2, item: 'b'}, - /// rand::Weighted {weight: 2, item: 'c'}]; - /// println!("{}", rng.weighted_vec(x)); - /// } - /// ``` - fn weighted_vec(&mut self, v: &[Weighted]) -> ~[T] { - let mut r = ~[]; - for item in v.iter() { - for _ in range(0u, item.weight) { - r.push(item.item.clone()); - } - } - r - } - /// Shuffle a vec /// /// # Example @@ -860,44 +767,6 @@ mod test { assert_eq!(r.choose_option(v), Some(&i)); } - #[test] - fn test_choose_weighted() { - let mut r = rng(); - assert!(r.choose_weighted([ - Weighted { weight: 1u, item: 42 }, - ]) == 42); - assert!(r.choose_weighted([ - Weighted { weight: 0u, item: 42 }, - Weighted { weight: 1u, item: 43 }, - ]) == 43); - } - - #[test] - fn test_choose_weighted_option() { - let mut r = rng(); - assert!(r.choose_weighted_option([ - Weighted { weight: 1u, item: 42 }, - ]) == Some(42)); - assert!(r.choose_weighted_option([ - Weighted { weight: 0u, item: 42 }, - Weighted { weight: 1u, item: 43 }, - ]) == Some(43)); - let v: Option = r.choose_weighted_option([]); - assert!(v.is_none()); - } - - #[test] - fn test_weighted_vec() { - let mut r = rng(); - let empty: ~[int] = ~[]; - assert_eq!(r.weighted_vec([]), empty); - assert!(r.weighted_vec([ - Weighted { weight: 0u, item: 3u }, - Weighted { weight: 1u, item: 2u }, - Weighted { weight: 2u, item: 1u }, - ]) == ~[2u, 1u, 1u]); - } - #[test] fn test_shuffle() { let mut r = rng(); From 14a6a62a742e6aa79519dbc4300266df46f858f9 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Tue, 22 Oct 2013 18:28:49 +1100 Subject: [PATCH 18/26] std::rand: simplify/safe-ify the default Rng.fill_bytes. The `&[u8]` -> `&[u64]` and `&[u32]` casts were not nice: they ignored alignment requirements and are generally very unsafe. --- src/libstd/rand/mod.rs | 87 +++++++++++++++++++++--------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index f5c60417bacb..9f611578c6a9 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -52,8 +52,6 @@ fn main () { ``` */ -use mem::size_of; -use unstable::raw::Slice; use cast; use container::Container; use iter::{Iterator, range}; @@ -136,46 +134,26 @@ pub trait Rng { /// } /// ``` fn fill_bytes(&mut self, dest: &mut [u8]) { - let mut slice: Slice = unsafe { cast::transmute_copy(&dest) }; - slice.len /= size_of::(); - let as_u64: &mut [u64] = unsafe { cast::transmute(slice) }; - for dest in as_u64.mut_iter() { - *dest = self.next_u64(); - } - - // the above will have filled up the vector as much as - // possible in multiples of 8 bytes. - let mut remaining = dest.len() % 8; - - // space for a u32 - if remaining >= 4 { - let mut slice: Slice = unsafe { cast::transmute_copy(&dest) }; - slice.len /= size_of::(); - let as_u32: &mut [u32] = unsafe { cast::transmute(slice) }; - as_u32[as_u32.len() - 1] = self.next_u32(); - remaining -= 4; - } - // exactly filled - if remaining == 0 { return } - - // now we know we've either got 1, 2 or 3 spots to go, - // i.e. exactly one u32 is enough. - let rand = self.next_u32(); - let remaining_index = dest.len() - remaining; - match dest.mut_slice_from(remaining_index) { - [ref mut a] => { - *a = rand as u8; + // this could, in theory, be done by transmuting dest to a + // [u64], but this is (1) likely to be undefined behaviour for + // LLVM, (2) has to be very careful about alignment concerns, + // (3) adds more `unsafe` that needs to be checked, (4) + // probably doesn't give much performance gain if + // optimisations are on. + let mut count = 0; + let mut num = 0; + for byte in dest.mut_iter() { + if count == 0 { + // we could micro-optimise here by generating a u32 if + // we only need a few more bytes to fill the vector + // (i.e. at most 4). + num = self.next_u64(); + count = 8; } - [ref mut a, ref mut b] => { - *a = rand as u8; - *b = (rand >> 8) as u8; - } - [ref mut a, ref mut b, ref mut c] => { - *a = rand as u8; - *b = (rand >> 8) as u8; - *c = (rand >> 16) as u8; - } - _ => fail!("Rng.fill_bytes: the impossible occurred: remaining != 1, 2 or 3") + + *byte = (num & 0xff) as u8; + num >>= 8; + count -= 1; } } @@ -749,14 +727,35 @@ pub fn random() -> T { mod test { use iter::{Iterator, range}; use option::{Option, Some}; + use vec; use super::*; + struct ConstRng { i: u64 } + impl Rng for ConstRng { + fn next_u32(&mut self) -> u32 { self.i as u32 } + fn next_u64(&mut self) -> u64 { self.i } + + // no fill_bytes on purpose + } + #[test] fn test_fill_bytes_default() { - let mut r = weak_rng(); + let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 }; - let mut v = [0u8, .. 100]; - r.fill_bytes(v); + // check every remainder mod 8, both in small and big vectors. + let lengths = [0, 1, 2, 3, 4, 5, 6, 7, + 80, 81, 82, 83, 84, 85, 86, 87]; + for &n in lengths.iter() { + let mut v = vec::from_elem(n, 0u8); + r.fill_bytes(v); + + // use this to get nicer error messages. + for (i, &byte) in v.iter().enumerate() { + if byte == 0 { + fail!("byte {} of {} is zero", i, n) + } + } + } } #[test] From b8932c6304599bddec6ac6d916db72a5c4034ada Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Tue, 22 Oct 2013 22:49:51 +1100 Subject: [PATCH 19/26] std::rand: use "nothing up your sleeve numbers" for ISAAC tests. There's no value in using the "random" numbers, when nothing up your sleeve numbers are perfectly serviceable. http://en.wikipedia.org/wiki/Nothing_up_my_sleeve_number --- src/libstd/rand/isaac.rs | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/libstd/rand/isaac.rs b/src/libstd/rand/isaac.rs index 0068b60cfa51..22117eebd29f 100644 --- a/src/libstd/rand/isaac.rs +++ b/src/libstd/rand/isaac.rs @@ -434,14 +434,14 @@ mod test { #[test] fn test_rng_32_seeded() { - let seed = &[2, 32, 4, 32, 51]; + let seed = &[1, 23, 456, 7890, 12345]; let mut ra: IsaacRng = SeedableRng::from_seed(seed); let mut rb: IsaacRng = SeedableRng::from_seed(seed); assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u)); } #[test] fn test_rng_64_seeded() { - let seed = &[2, 32, 4, 32, 51]; + let seed = &[1, 23, 456, 7890, 12345]; let mut ra: Isaac64Rng = SeedableRng::from_seed(seed); let mut rb: Isaac64Rng = SeedableRng::from_seed(seed); assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u)); @@ -472,46 +472,46 @@ mod test { #[test] fn test_rng_32_true_values() { - let seed = &[2, 32, 4, 32, 51]; + let seed = &[1, 23, 456, 7890, 12345]; let mut ra: IsaacRng = SeedableRng::from_seed(seed); // Regression test that isaac is actually using the above vector let v = vec::from_fn(10, |_| ra.next_u32()); assert_eq!(v, - ~[447462228, 2081944040, 3163797308, 2379916134, 2377489184, - 1132373754, 536342443, 2995223415, 1265094839, 345325140]); + ~[2558573138, 873787463, 263499565, 2103644246, 3595684709, + 4203127393, 264982119, 2765226902, 2737944514, 3900253796]); - let seed = &[500, -4000, 123456, 9876543, 1, 1, 1, 1, 1]; + 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(); } let v = vec::from_fn(10, |_| rb.next_u32()); assert_eq!(v, - ~[612373032, 292987903, 1819311337, 3141271980, 422447569, - 310096395, 1083172510, 867909094, 2478664230, 2073577855]); + ~[3676831399, 3183332890, 2834741178, 3854698763, 2717568474, + 1576568959, 3507990155, 179069555, 141456972, 2478885421]); } #[test] fn test_rng_64_true_values() { - let seed = &[2, 32, 4, 32, 51]; + let seed = &[1, 23, 456, 7890, 12345]; let mut ra: Isaac64Rng = SeedableRng::from_seed(seed); // Regression test that isaac is actually using the above vector let v = vec::from_fn(10, |_| ra.next_u64()); assert_eq!(v, - ~[15015576812873463115, 12461067598045625862, 14818626436142668771, - 5562406406765984441, 11813289907965514161, 13443797187798420053, - 6935026941854944442, 7750800609318664042, 14428747036317928637, - 14028894460301215947]); + ~[547121783600835980, 14377643087320773276, 17351601304698403469, + 1238879483818134882, 11952566807690396487, 13970131091560099343, + 4469761996653280935, 15552757044682284409, 6860251611068737823, + 13722198873481261842]); - let seed = &[500, -4000, 123456, 9876543, 1, 1, 1, 1, 1]; + 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(); } let v = vec::from_fn(10, |_| rb.next_u64()); assert_eq!(v, - ~[13557216323596688637, 17060829581390442094, 4927582063811333743, - 2699639759356482270, 4819341314392384881, 6047100822963614452, - 11086255989965979163, 11901890363215659856, 5370800226050011580, - 16496463556025356451]); + ~[18143823860592706164, 8491801882678285927, 2699425367717515619, + 17196852593171130876, 2606123525235546165, 15790932315217671084, + 596345674630742204, 9947027391921273664, 11788097613744130851, + 10391409374914919106]); } } From 6e7bbdacb9bf04c1f5bf2c3aad487122d8377b7f Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Tue, 22 Oct 2013 23:11:17 +1100 Subject: [PATCH 20/26] std::rand: seed ISAAC with no transmutes. Slice transmutes are now (and, really, always were) dangerous, so we avoid them and do the (only?) non-(undefined behaviour in C) pointer cast: casting to *u8. --- src/libstd/rand/isaac.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/libstd/rand/isaac.rs b/src/libstd/rand/isaac.rs index 22117eebd29f..7dc4e5b868b8 100644 --- a/src/libstd/rand/isaac.rs +++ b/src/libstd/rand/isaac.rs @@ -10,10 +10,11 @@ //! The ISAAC random number generator. -use cast; use rand::{Rng, SeedableRng, OSRng}; use iter::{Iterator, range, range_step, Repeat}; use option::{None, Some}; +use vec::raw; +use mem; static RAND_SIZE_LEN: u32 = 8; static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN; @@ -42,9 +43,12 @@ impl IsaacRng { pub fn new() -> IsaacRng { let mut rng = EMPTY; - { - let bytes = unsafe {cast::transmute::<&mut [u32], &mut [u8]>(rng.rsl)}; - OSRng::new().fill_bytes(bytes); + unsafe { + let ptr = raw::to_mut_ptr(rng.rsl); + + do raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl)) |slice| { + OSRng::new().fill_bytes(slice); + } } rng.init(true); @@ -238,10 +242,15 @@ impl Isaac64Rng { /// seed. pub fn new() -> Isaac64Rng { let mut rng = EMPTY_64; - { - let bytes = unsafe {cast::transmute::<&mut [u64], &mut [u8]>(rng.rsl)}; - OSRng::new().fill_bytes(bytes); + + unsafe { + let ptr = raw::to_mut_ptr(rng.rsl); + + do raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl)) |slice| { + OSRng::new().fill_bytes(slice); + } } + rng.init(true); rng } From 5754848f8cd06bd3fc2bb084b5ca7bd41974e1b5 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Sun, 20 Oct 2013 01:55:23 -0400 Subject: [PATCH 21/26] libsyntax/librustc: Allow specifying mut on by-value self. --- src/librustc/metadata/decoder.rs | 2 +- src/librustc/metadata/encoder.rs | 3 +- src/librustc/middle/astencode.rs | 2 +- src/librustc/middle/liveness.rs | 2 +- src/librustc/middle/mem_categorization.rs | 4 +-- src/librustc/middle/moves.rs | 2 +- src/librustc/middle/resolve.rs | 12 +++++--- src/librustc/middle/trans/expr.rs | 2 +- src/librustc/middle/trans/inline.rs | 2 +- src/librustc/middle/trans/meth.rs | 2 +- src/librustc/middle/typeck/astconv.rs | 2 +- src/librustc/middle/typeck/check/method.rs | 8 +++--- src/librustc/middle/typeck/check/mod.rs | 2 +- src/librustc/middle/typeck/check/regionck.rs | 2 +- src/librustdoc/clean.rs | 4 +-- src/libsyntax/ast.rs | 6 ++-- src/libsyntax/ast_util.rs | 2 +- src/libsyntax/ext/deriving/ty.rs | 2 +- src/libsyntax/parse/parser.rs | 30 +++++++++++--------- src/libsyntax/print/pprust.rs | 5 +++- 20 files changed, 53 insertions(+), 43 deletions(-) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index aa1c4c1eb7ec..ca1912c83476 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -975,7 +975,7 @@ fn get_explicit_self(item: ebml::Doc) -> ast::explicit_self_ { let explicit_self_kind = string[0]; match explicit_self_kind as char { 's' => { return ast::sty_static; } - 'v' => { return ast::sty_value; } + 'v' => { return ast::sty_value(get_mutability(string[1])); } '@' => { return ast::sty_box(get_mutability(string[1])); } '~' => { return ast::sty_uniq; } '&' => { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 9f40593a93ae..0f5ce06a7daa 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -662,8 +662,9 @@ fn encode_explicit_self(ebml_w: &mut writer::Encoder, explicit_self: ast::explic sty_static => { ebml_w.writer.write(&[ 's' as u8 ]); } - sty_value => { + sty_value(m) => { ebml_w.writer.write(&[ 'v' as u8 ]); + encode_mutability(ebml_w, m); } sty_region(_, m) => { // FIXME(#4846) encode custom lifetime diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 294bbcb46f7b..3d7f28b8b30b 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -410,7 +410,7 @@ impl tr for ast::Def { ast::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx))) } ast::DefSelfTy(nid) => { ast::DefSelfTy(xcx.tr_id(nid)) } - ast::DefSelf(nid) => { ast::DefSelf(xcx.tr_id(nid)) } + ast::DefSelf(nid, m) => { ast::DefSelf(xcx.tr_id(nid), m) } ast::DefMod(did) => { ast::DefMod(did.tr(xcx)) } ast::DefForeignMod(did) => { ast::DefForeignMod(did.tr(xcx)) } ast::DefStatic(did, m) => { ast::DefStatic(did.tr(xcx), m) } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 6c53fc1602f2..a235d7395a6d 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -392,7 +392,7 @@ fn visit_fn(v: &mut LivenessVisitor, match *fk { visit::fk_method(_, _, method) => { match method.explicit_self.node { - sty_value | sty_region(*) | sty_box(_) | sty_uniq => { + sty_value(_) | sty_region(*) | sty_box(_) | sty_uniq => { fn_maps.add_variable(Arg(method.self_id, special_idents::self_)); } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 37e89e58fa56..eb03027ad71f 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -488,12 +488,12 @@ impl mem_categorization_ctxt { } } - ast::DefSelf(self_id) => { + ast::DefSelf(self_id, mutbl) => { @cmt_ { id:id, span:span, cat:cat_self(self_id), - mutbl: McImmutable, + mutbl: if mutbl { McDeclared } else { McImmutable }, ty:expr_ty } } diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index 1ed517c95129..5001614647a8 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -227,7 +227,7 @@ pub fn moved_variable_node_id_from_def(def: Def) -> Option { DefBinding(nid, _) | DefArg(nid, _) | DefLocal(nid, _) | - DefSelf(nid) => Some(nid), + DefSelf(nid, _) => Some(nid), _ => None } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index b480aaac1acb..4c5d2f86a1b2 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -150,7 +150,7 @@ enum Mutability { enum SelfBinding { NoSelfBinding, - HasSelfBinding(NodeId) + HasSelfBinding(NodeId, explicit_self) } impl Visitor<()> for Resolver { @@ -3799,8 +3799,12 @@ impl Resolver { NoSelfBinding => { // Nothing to do. } - HasSelfBinding(self_node_id) => { - let def_like = DlDef(DefSelf(self_node_id)); + HasSelfBinding(self_node_id, explicit_self) => { + let mutable = match explicit_self.node { + sty_value(m) if m == MutMutable => true, + _ => false + }; + let def_like = DlDef(DefSelf(self_node_id, mutable)); *function_value_rib.self_binding = Some(def_like); } } @@ -3937,7 +3941,7 @@ impl Resolver { // we only have self ty if it is a non static method let self_binding = match method.explicit_self.node { sty_static => { NoSelfBinding } - _ => { HasSelfBinding(method.self_id) } + _ => { HasSelfBinding(method.self_id, method.explicit_self) } }; self.resolve_function(rib_kind, diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 238b15fe5979..56f1e0478410 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -1099,7 +1099,7 @@ pub fn trans_local_var(bcx: @mut Block, def: ast::Def) -> Datum { ast::DefLocal(nid, _) | ast::DefBinding(nid, _) => { take_local(bcx, bcx.fcx.lllocals, nid) } - ast::DefSelf(nid) => { + ast::DefSelf(nid, _) => { let self_info: ValSelfData = match bcx.fcx.llself { Some(ref self_info) => *self_info, None => { diff --git a/src/librustc/middle/trans/inline.rs b/src/librustc/middle/trans/inline.rs index a5be9a3ca5e1..d9f7cdeeb2ef 100644 --- a/src/librustc/middle/trans/inline.rs +++ b/src/librustc/middle/trans/inline.rs @@ -144,7 +144,7 @@ pub fn maybe_instantiate_inline(ccx: @mut CrateContext, fn_id: ast::DefId) debug!("calling inline trans_fn with self_ty {}", ty_to_str(ccx.tcx, self_ty)); match mth.explicit_self.node { - ast::sty_value => impl_self(self_ty, ty::ByRef), + ast::sty_value(_) => impl_self(self_ty, ty::ByRef), _ => impl_self(self_ty, ty::ByCopy), } } diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index a8c18c721671..61384c72efa2 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -120,7 +120,7 @@ pub fn trans_method(ccx: @mut CrateContext, debug!("calling trans_fn with self_ty {}", self_ty.repr(ccx.tcx)); match method.explicit_self.node { - ast::sty_value => impl_self(self_ty, ty::ByRef), + ast::sty_value(_) => impl_self(self_ty, ty::ByRef), _ => impl_self(self_ty, ty::ByCopy), } } diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index ccda6bbaf9d1..e703f6da4168 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -672,7 +672,7 @@ fn ty_of_method_or_bare_fn( { match self_info.explicit_self.node { ast::sty_static => None, - ast::sty_value => { + ast::sty_value(_) => { Some(self_info.untransformed_self_ty) } ast::sty_region(ref lifetime, mutability) => { diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index f6efd3aa5ad1..b48e1f7fcf15 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -1082,7 +1082,7 @@ impl<'self> LookupContext<'self> { ast::sty_static => { self.bug(~"static method for object type receiver"); } - ast::sty_value => { + ast::sty_value(_) => { ty::mk_err() // error reported in `enforce_object_limitations()` } ast::sty_region(*) | ast::sty_box(*) | ast::sty_uniq(*) => { @@ -1141,7 +1141,7 @@ impl<'self> LookupContext<'self> { through an object"); } - ast::sty_value => { // reason (a) above + ast::sty_value(_) => { // reason (a) above self.tcx().sess.span_err( self.expr.span, "cannot call a method with a by-value receiver \ @@ -1198,7 +1198,7 @@ impl<'self> LookupContext<'self> { false } - sty_value => { + sty_value(_) => { rcvr_matches_ty(self.fcx, rcvr_ty, candidate) } @@ -1369,7 +1369,7 @@ impl<'self> LookupContext<'self> { pub fn get_mode_from_explicit_self(explicit_self: ast::explicit_self_) -> SelfMode { match explicit_self { - sty_value => ty::ByRef, + sty_value(_) => ty::ByRef, _ => ty::ByCopy, } } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index eddf8aa51850..4514564ff1f6 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -3254,7 +3254,7 @@ pub fn ty_param_bounds_and_ty_for_def(fcx: @mut FnCtxt, defn: ast::Def) -> ty_param_bounds_and_ty { match defn { - ast::DefArg(nid, _) | ast::DefLocal(nid, _) | ast::DefSelf(nid) | + ast::DefArg(nid, _) | ast::DefLocal(nid, _) | ast::DefSelf(nid, _) | ast::DefBinding(nid, _) => { let typ = fcx.local_ty(sp, nid); return no_params(typ); diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index 06a130594623..09fc7b5c15c3 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -58,7 +58,7 @@ fn encl_region_of_def(fcx: @mut FnCtxt, def: ast::Def) -> ty::Region { let tcx = fcx.tcx(); match def { DefLocal(node_id, _) | DefArg(node_id, _) | - DefSelf(node_id) | DefBinding(node_id, _) => { + DefSelf(node_id, _) | DefBinding(node_id, _) => { tcx.region_maps.encl_region(node_id) } DefUpvar(_, subdef, closure_id, body_id) => { diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index 6ee7f8c17274..90fc71aa8635 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -388,7 +388,7 @@ impl Clean for ast::explicit_self { fn clean(&self) -> SelfTy { match self.node { ast::sty_static => SelfStatic, - ast::sty_value => SelfValue, + ast::sty_value(_) => SelfValue, ast::sty_uniq => SelfOwned, ast::sty_region(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()), ast::sty_box(mt) => SelfManaged(mt.clean()), @@ -1171,7 +1171,7 @@ fn resolve_type(path: Path, tpbs: Option<~[TyParamBound]>, let (def_id, kind) = match *d { ast::DefFn(i, _) => (i, TypeFunction), - ast::DefSelf(i) | ast::DefSelfTy(i) => return Self(i), + ast::DefSelf(i, _) | ast::DefSelfTy(i) => return Self(i), ast::DefTy(i) => (i, TypeEnum), ast::DefTrait(i) => { debug!("saw DefTrait in def_to_id"); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 01033e829f6a..6631924239d3 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -227,7 +227,7 @@ pub enum MethodProvenance { pub enum Def { DefFn(DefId, purity), DefStaticMethod(/* method */ DefId, MethodProvenance, purity), - DefSelf(NodeId), + DefSelf(NodeId, bool /* is_mutbl */), DefSelfTy(/* trait id */ NodeId), DefMod(DefId), DefForeignMod(DefId), @@ -921,8 +921,8 @@ pub enum ret_style { #[deriving(Clone, Eq, Encodable, Decodable, IterBytes)] pub enum explicit_self_ { sty_static, // no self - sty_value, // `self` - sty_region(Option, Mutability), // `&'lt self` + sty_value(Mutability), // `self` + sty_region(Option, Mutability), // `&'lt self` sty_box(Mutability), // `@self` sty_uniq // `~self` } diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index bdebc9872e69..1d9d5512ff42 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -66,7 +66,7 @@ pub fn def_id_of_def(d: Def) -> DefId { DefUse(id) | DefStruct(id) | DefTrait(id) | DefMethod(id, _) => { id } - DefArg(id, _) | DefLocal(id, _) | DefSelf(id) | DefSelfTy(id) + DefArg(id, _) | DefLocal(id, _) | DefSelf(id, _) | DefSelfTy(id) | DefUpvar(id, _, _, _) | DefBinding(id, _) | DefRegion(id) | DefTyParamBinder(id) | DefLabel(id) => { local_def(id) diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index 83c73e3d85f2..a9fdafc80141 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -240,7 +240,7 @@ pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option) let self_path = cx.expr_self(span); match *self_ptr { None => { - (self_path, respan(span, ast::sty_value)) + (self_path, respan(span, ast::sty_value(ast::MutImmutable))) } Some(ref ptr) => { let self_ty = respan( diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ed6019e1a55a..133934a746a1 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3438,15 +3438,11 @@ impl Parser { // parse the argument list and result type of a function // that may have a self type. - fn parse_fn_decl_with_self( - &self, - parse_arg_fn: - &fn(&Parser) -> arg - ) -> (explicit_self, fn_decl) { - fn maybe_parse_explicit_self( - cnstr: &fn(v: Mutability) -> ast::explicit_self_, - p: &Parser - ) -> ast::explicit_self_ { + fn parse_fn_decl_with_self(&self, parse_arg_fn: &fn(&Parser) -> arg) + -> (explicit_self, fn_decl) { + + fn maybe_parse_explicit_self(cnstr: &fn(v: Mutability) -> ast::explicit_self_, + p: &Parser) -> ast::explicit_self_ { // We need to make sure it isn't a type if p.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) || ((p.look_ahead(1, |t| token::is_keyword(keywords::Const, t)) || @@ -3529,20 +3525,26 @@ impl Parser { } token::IDENT(*) if self.is_self_ident() => { self.bump(); - sty_value + sty_value(MutImmutable) } token::BINOP(token::STAR) => { // Possibly "*self" or "*mut self" -- not supported. Try to avoid // emitting cryptic "unexpected token" errors. self.bump(); - if self.token_is_mutability(self.token) { - self.bump(); - } + let mutability = if self.token_is_mutability(self.token) { + self.parse_mutability() + } else { MutImmutable }; if self.is_self_ident() { self.span_err(*self.span, "cannot pass self by unsafe pointer"); self.bump(); } - sty_value + sty_value(mutability) + } + _ if self.token_is_mutability(self.token) && + self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => { + let mutability = self.parse_mutability(); + self.expect_self_ident(); + sty_value(mutability) } _ => { sty_static diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b245bd75ace7..9ce28e4d55a8 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1686,7 +1686,10 @@ pub fn explicit_self_to_str(explicit_self: &ast::explicit_self_, intr: @ident_in pub fn print_explicit_self(s: @ps, explicit_self: ast::explicit_self_) -> bool { match explicit_self { ast::sty_static => { return false; } - ast::sty_value => { word(s.s, "self"); } + ast::sty_value(m) => { + print_mutability(s, m); + word(s.s, "self"); + } ast::sty_uniq => { word(s.s, "~self"); } ast::sty_region(ref lt, m) => { word(s.s, "&"); From af163579ed674c4b1a37f5c8d50bf348722db439 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Sun, 20 Oct 2013 02:34:01 -0400 Subject: [PATCH 22/26] libsyntax/librustc: Allow specifying mut on ~self. --- src/librustc/metadata/decoder.rs | 2 +- src/librustc/metadata/encoder.rs | 3 ++- src/librustc/middle/liveness.rs | 2 +- src/librustc/middle/resolve.rs | 2 +- src/librustc/middle/typeck/astconv.rs | 2 +- src/librustc/middle/typeck/check/method.rs | 2 +- src/librustdoc/clean.rs | 2 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/ext/deriving/ty.rs | 2 +- src/libsyntax/parse/parser.rs | 10 +++++++++- src/libsyntax/print/pprust.rs | 5 ++++- 11 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index ca1912c83476..102327303294 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -977,7 +977,7 @@ fn get_explicit_self(item: ebml::Doc) -> ast::explicit_self_ { 's' => { return ast::sty_static; } 'v' => { return ast::sty_value(get_mutability(string[1])); } '@' => { return ast::sty_box(get_mutability(string[1])); } - '~' => { return ast::sty_uniq; } + '~' => { return ast::sty_uniq(get_mutability(string[1])); } '&' => { // FIXME(#4846) expl. region return ast::sty_region(None, get_mutability(string[1])); diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 0f5ce06a7daa..bae0dcc2a520 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -675,8 +675,9 @@ fn encode_explicit_self(ebml_w: &mut writer::Encoder, explicit_self: ast::explic ebml_w.writer.write(&[ '@' as u8 ]); encode_mutability(ebml_w, m); } - sty_uniq => { + sty_uniq(m) => { ebml_w.writer.write(&[ '~' as u8 ]); + encode_mutability(ebml_w, m); } } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index a235d7395a6d..71934c9f2a7e 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -392,7 +392,7 @@ fn visit_fn(v: &mut LivenessVisitor, match *fk { visit::fk_method(_, _, method) => { match method.explicit_self.node { - sty_value(_) | sty_region(*) | sty_box(_) | sty_uniq => { + sty_value(_) | sty_region(*) | sty_box(_) | sty_uniq(_) => { fn_maps.add_variable(Arg(method.self_id, special_idents::self_)); } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 4c5d2f86a1b2..ee36b807ac79 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -3801,7 +3801,7 @@ impl Resolver { } HasSelfBinding(self_node_id, explicit_self) => { let mutable = match explicit_self.node { - sty_value(m) if m == MutMutable => true, + sty_uniq(m) | sty_value(m) if m == MutMutable => true, _ => false }; let def_like = DlDef(DefSelf(self_node_id, mutable)); diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index e703f6da4168..dd0c6c12a69a 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -689,7 +689,7 @@ fn ty_of_method_or_bare_fn( ty::mt {ty: self_info.untransformed_self_ty, mutbl: mutability})) } - ast::sty_uniq => { + ast::sty_uniq(_) => { Some(ty::mk_uniq(this.tcx(), ty::mt {ty: self_info.untransformed_self_ty, mutbl: ast::MutImmutable})) diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index b48e1f7fcf15..af1d5ce3cc60 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -1236,7 +1236,7 @@ impl<'self> LookupContext<'self> { } } - sty_uniq => { + sty_uniq(_) => { debug!("(is relevant?) explicit self is a unique pointer"); match ty::get(rcvr_ty).sty { ty::ty_uniq(mt) => { diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index 90fc71aa8635..dd1ad8263da8 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -389,7 +389,7 @@ impl Clean for ast::explicit_self { match self.node { ast::sty_static => SelfStatic, ast::sty_value(_) => SelfValue, - ast::sty_uniq => SelfOwned, + ast::sty_uniq(_) => SelfOwned, ast::sty_region(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()), ast::sty_box(mt) => SelfManaged(mt.clean()), } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 6631924239d3..372f1950c1de 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -924,7 +924,7 @@ pub enum explicit_self_ { sty_value(Mutability), // `self` sty_region(Option, Mutability), // `&'lt self` sty_box(Mutability), // `@self` - sty_uniq // `~self` + sty_uniq(Mutability) // `~self` } pub type explicit_self = Spanned; diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index a9fdafc80141..c60259304aef 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -246,7 +246,7 @@ pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option) let self_ty = respan( span, match *ptr { - Send => ast::sty_uniq, + Send => ast::sty_uniq(ast::MutImmutable), Managed(mutbl) => ast::sty_box(mutbl), Borrowed(ref lt, mutbl) => { let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(s))); diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 133934a746a1..605e259cf0c2 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3520,7 +3520,7 @@ impl Parser { self.span_err(*self.last_span, "mutability declaration not allowed here"); } - sty_uniq + sty_uniq(MutImmutable) }, self) } token::IDENT(*) if self.is_self_ident() => { @@ -3546,6 +3546,14 @@ impl Parser { self.expect_self_ident(); sty_value(mutability) } + _ if self.token_is_mutability(self.token) && + self.look_ahead(1, |t| *t == token::TILDE) && + self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => { + let mutability = self.parse_mutability(); + self.bump(); + self.expect_self_ident(); + sty_uniq(mutability) + } _ => { sty_static } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 9ce28e4d55a8..0e330da31e62 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1690,7 +1690,10 @@ pub fn print_explicit_self(s: @ps, explicit_self: ast::explicit_self_) -> bool { print_mutability(s, m); word(s.s, "self"); } - ast::sty_uniq => { word(s.s, "~self"); } + ast::sty_uniq(m) => { + print_mutability(s, m); + word(s.s, "~self"); + } ast::sty_region(ref lt, m) => { word(s.s, "&"); print_opt_lifetime(s, lt); From 03111fb83b8c8c2c04939dfebb2fd3b9053aa462 Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Mon, 21 Oct 2013 03:50:09 -0400 Subject: [PATCH 23/26] Add tests for uniq & by-value self in mut slot. --- .../run-pass/by-value-self-in-mut-slot.rs | 30 +++++++++++++ .../self-in-mut-slot-default-method.rs | 43 +++++++++++++++++++ src/test/run-pass/uniq-self-in-mut-slot.rs | 30 +++++++++++++ 3 files changed, 103 insertions(+) create mode 100644 src/test/run-pass/by-value-self-in-mut-slot.rs create mode 100644 src/test/run-pass/self-in-mut-slot-default-method.rs create mode 100644 src/test/run-pass/uniq-self-in-mut-slot.rs diff --git a/src/test/run-pass/by-value-self-in-mut-slot.rs b/src/test/run-pass/by-value-self-in-mut-slot.rs new file mode 100644 index 000000000000..aa88004cd119 --- /dev/null +++ b/src/test/run-pass/by-value-self-in-mut-slot.rs @@ -0,0 +1,30 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +struct X { + a: int +} + +trait Changer { + fn change(mut self) -> Self; +} + +impl Changer for X { + fn change(mut self) -> X { + self.a = 55; + self + } +} + +pub fn main() { + let x = X { a: 32 }; + let new_x = x.change(); + assert_eq!(new_x.a, 55); +} diff --git a/src/test/run-pass/self-in-mut-slot-default-method.rs b/src/test/run-pass/self-in-mut-slot-default-method.rs new file mode 100644 index 000000000000..08d10fd11703 --- /dev/null +++ b/src/test/run-pass/self-in-mut-slot-default-method.rs @@ -0,0 +1,43 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +struct X { + a: int +} + +trait Changer { + fn change(mut self) -> Self { + self.set_to(55); + self + } + + fn change_again(mut ~self) -> ~Self { + self.set_to(45); + self + } + + fn set_to(&mut self, a: int); +} + +impl Changer for X { + fn set_to(&mut self, a: int) { + self.a = a; + } +} + +pub fn main() { + let x = X { a: 32 }; + let new_x = x.change(); + assert_eq!(new_x.a, 55); + + let x = ~new_x; + let new_x = x.change_again(); + assert_eq!(new_x.a, 45); +} diff --git a/src/test/run-pass/uniq-self-in-mut-slot.rs b/src/test/run-pass/uniq-self-in-mut-slot.rs new file mode 100644 index 000000000000..7c2f52211761 --- /dev/null +++ b/src/test/run-pass/uniq-self-in-mut-slot.rs @@ -0,0 +1,30 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +struct X { + a: int +} + +trait Changer { + fn change(mut ~self) -> ~Self; +} + +impl Changer for X { + fn change(mut ~self) -> ~X { + self.a = 55; + self + } +} + +pub fn main() { + let x = ~X { a: 32 }; + let new_x = x.change(); + assert_eq!(new_x.a, 55); +} From b2b2095eaf2e71b1b60797a96c097572928f001c Mon Sep 17 00:00:00 2001 From: Luqman Aden Date: Tue, 22 Oct 2013 21:37:42 -0400 Subject: [PATCH 24/26] Update the manual. --- doc/rust.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index fd2da43a037f..40a3bc12798f 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -3395,16 +3395,23 @@ a [temporary](#lvalues-rvalues-and-temporaries), or a local variable. A _local variable_ (or *stack-local* allocation) holds a value directly, allocated within the stack's memory. The value is a part of the stack frame. -Local variables are immutable unless declared with `let mut`. The -`mut` keyword applies to all local variables declared within that -declaration (so `let mut (x, y) = ...` declares two mutable variables, `x` and -`y`). +Local variables are immutable unless declared otherwise like: `let mut x = ...`. Function parameters are immutable unless declared with `mut`. The `mut` keyword applies only to the following parameter (so `|mut x, y|` and `fn f(mut x: ~int, y: ~int)` declare one mutable variable `x` and one immutable variable `y`). +Methods that take either `self` or `~self` can optionally place them in a +mutable slot by prefixing them with `mut` (similar to regular arguments): + +~~~ +trait Changer { + fn change(mut self) -> Self; + fn modify(mut ~self) -> ~Self; +} +~~~ + Local variables are not initialized when allocated; the entire frame worth of local variables are allocated at once, on frame-entry, in an uninitialized state. Subsequent statements within a function may or may not initialize the From c97957588b7e26d32e7800072df4c31da56703ef Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Mon, 30 Sep 2013 22:39:50 -0700 Subject: [PATCH 25/26] rustpkg: Support arbitrary dependencies in the install API api::install_pkg now accepts an argument that's a list of (kind, path) dependency pairs. This allows custom package scripts to declare C dependencies, as is demonstrated in rustpkg::tests::test_c_dependency_ok. Closes #6403 --- mk/tests.mk | 1 + src/librustpkg/api.rs | 96 ++++++++++++-- src/librustpkg/conditions.rs | 6 + src/librustpkg/context.rs | 18 +++ src/librustpkg/package_source.rs | 52 ++++++-- src/librustpkg/path_util.rs | 4 +- src/librustpkg/rustpkg.rs | 113 +++++++++------- src/librustpkg/target.rs | 26 +++- src/librustpkg/tests.rs | 121 ++++++++++++++++-- .../testsuite/pass/src/c-dependencies/bar.rs | 13 ++ .../testsuite/pass/src/c-dependencies/foo.rs | 12 ++ .../testsuite/pass/src/c-dependencies/lib.rs | 14 ++ .../testsuite/pass/src/c-dependencies/pkg.rs | 83 ++++++++++++ .../testsuite/pass/src/fancy-lib/lib.rs | 2 +- .../testsuite/pass/src/fancy-lib/pkg.rs | 31 ++--- src/librustpkg/util.rs | 26 +++- 16 files changed, 514 insertions(+), 104 deletions(-) create mode 100644 src/librustpkg/testsuite/pass/src/c-dependencies/bar.rs create mode 100644 src/librustpkg/testsuite/pass/src/c-dependencies/foo.rs create mode 100644 src/librustpkg/testsuite/pass/src/c-dependencies/lib.rs create mode 100644 src/librustpkg/testsuite/pass/src/c-dependencies/pkg.rs diff --git a/mk/tests.mk b/mk/tests.mk index c06c234e951d..d6fc5ecb8e5a 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -370,6 +370,7 @@ $(3)/stage$(1)/test/rustpkgtest-$(2)$$(X_$(2)): \ $$(SREQ$(1)_T_$(2)_H_$(3)) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBSYNTAX_$(2)) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_LIBRUSTC_$(2)) \ + $$(HBIN$(1)_H_$(3))/rustpkg$$(X_$(2)) \ $$(TBIN$(1)_T_$(2)_H_$(3))/rustpkg$$(X_$(2)) \ $$(TBIN$(1)_T_$(2)_H_$(3))/rustc$$(X_$(2)) @$$(call E, compile_and_link: $$@) diff --git a/src/librustpkg/api.rs b/src/librustpkg/api.rs index 1f5802927a64..c67b6f52c7e3 100644 --- a/src/librustpkg/api.rs +++ b/src/librustpkg/api.rs @@ -12,22 +12,35 @@ use context::*; use crate::*; use package_id::*; use package_source::*; +use path_util::{platform_library_name, target_build_dir}; use target::*; use version::Version; +use workspace::pkg_parent_workspaces; use workcache_support::*; +pub use path_util::default_workspace; pub use source_control::{safe_git_clone, git_clone_url}; -use std::os; +use std::{os, run}; use extra::arc::{Arc,RWArc}; use extra::workcache; use extra::workcache::{Database, Logger, FreshnessMap}; use extra::treemap::TreeMap; +// A little sad -- duplicated from rustc::back::* +#[cfg(target_arch = "arm")] +fn cc_args() -> ~[~str] { ~[~"-marm"] } +#[cfg(target_arch = "mips")] +fn cc_args() -> ~[~str] { ~[] } +#[cfg(target_arch = "x86")] +fn cc_args() -> ~[~str] { ~[~"-m32"] } +#[cfg(target_arch = "x86_64")] +fn cc_args() -> ~[~str] { ~[~"-m64"] } + /// Convenience functions intended for calling from pkg.rs /// p is where to put the cache file for dependencies -pub fn default_context(p: Path) -> BuildContext { - new_default_context(new_workcache_context(&p), p) +pub fn default_context(sysroot: Path, p: Path) -> BuildContext { + new_default_context(new_workcache_context(&p), sysroot) } pub fn new_default_context(c: workcache::Context, p: Path) -> BuildContext { @@ -68,7 +81,7 @@ pub fn new_workcache_context(p: &Path) -> workcache::Context { pub fn build_lib(sysroot: Path, root: Path, name: ~str, version: Version, lib: Path) { - let cx = default_context(sysroot); + let cx = default_context(sysroot, root.clone()); let pkg_src = PkgSrc { source_workspace: root.clone(), build_in_destination: false, @@ -81,12 +94,12 @@ pub fn build_lib(sysroot: Path, root: Path, name: ~str, version: Version, tests: ~[], benchs: ~[] }; - pkg_src.build(&cx, ~[]); + pkg_src.build(&cx, ~[], []); } pub fn build_exe(sysroot: Path, root: Path, name: ~str, version: Version, main: Path) { - let cx = default_context(sysroot); + let cx = default_context(sysroot, root.clone()); let pkg_src = PkgSrc { source_workspace: root.clone(), build_in_destination: false, @@ -100,13 +113,76 @@ pub fn build_exe(sysroot: Path, root: Path, name: ~str, version: Version, benchs: ~[] }; - pkg_src.build(&cx, ~[]); + pkg_src.build(&cx, ~[], []); } -pub fn install_pkg(sysroot: Path, workspace: Path, name: ~str, version: Version) { - let cx = default_context(sysroot); +pub fn install_pkg(cx: &BuildContext, + workspace: Path, + name: ~str, + version: Version, + // For now, these inputs are assumed to be inputs to each of the crates + more_inputs: ~[(~str, Path)]) { // pairs of Kind and Path let pkgid = PkgId{ version: version, ..PkgId::new(name)}; - cx.install(PkgSrc::new(workspace.clone(), workspace, false, pkgid), &Everything); + cx.install(PkgSrc::new(workspace.clone(), workspace, false, pkgid), + &WhatToBuild{ build_type: Inferred, + inputs_to_discover: more_inputs, + sources: Everything }); +} + +/// Builds an arbitrary library whose short name is `output`, +/// by invoking `tool` with arguments `args` plus "-o %s", where %s +/// is the platform-specific library name for `output`. +/// Returns that platform-specific name. +pub fn build_library_in_workspace(exec: &mut workcache::Exec, + context: &mut Context, + package_name: &str, + tool: &str, + flags: &[~str], + paths: &[~str], + output: &str) -> ~str { + use command_failed = conditions::command_failed::cond; + + let workspace = my_workspace(context, package_name); + let workspace_build_dir = target_build_dir(&workspace); + let out_name = workspace_build_dir.join_many([package_name.to_str(), + platform_library_name(output)]); + // make paths absolute + let pkgid = PkgId::new(package_name); + let absolute_paths = paths.map(|s| { + let whatever = workspace.join_many([~"src", + pkgid.to_str(), + s.to_owned()]); + whatever.as_str().unwrap().to_owned() + }); + + let cc_args = cc_args(); + + let all_args = flags + absolute_paths + cc_args + + ~[~"-o", out_name.as_str().unwrap().to_owned()]; + let exit_code = run::process_status(tool, all_args); + if exit_code != 0 { + command_failed.raise((tool.to_owned(), all_args, exit_code)) + } + else { + let out_name_str = out_name.as_str().unwrap().to_owned(); + exec.discover_output("binary", + out_name_str, + digest_only_date(&out_name)); + context.add_library_path(out_name.dir_path()); + out_name_str + } +} + +pub fn my_workspace(context: &Context, package_name: &str) -> Path { + use bad_pkg_id = conditions::bad_pkg_id::cond; + + // (this assumes no particular version is requested) + let pkgid = PkgId::new(package_name); + let workspaces = pkg_parent_workspaces(context, &pkgid); + if workspaces.is_empty() { + bad_pkg_id.raise((Path::new(package_name), package_name.to_owned())); + } + workspaces[0] } fn mk_crate(p: Path) -> Crate { diff --git a/src/librustpkg/conditions.rs b/src/librustpkg/conditions.rs index 19b310b45061..046ba405dbb8 100644 --- a/src/librustpkg/conditions.rs +++ b/src/librustpkg/conditions.rs @@ -54,3 +54,9 @@ condition! { condition! { pub git_checkout_failed: (~str, Path) -> (); } + +condition! { + // str is output of applying the command (first component) + // to the args (second component) + pub command_failed: (~str, ~[~str], int) -> ~str; +} diff --git a/src/librustpkg/context.rs b/src/librustpkg/context.rs index 3f1f2a1f59d5..72197219fc5a 100644 --- a/src/librustpkg/context.rs +++ b/src/librustpkg/context.rs @@ -54,6 +54,15 @@ impl BuildContext { pub fn compile_upto(&self) -> StopBefore { self.context.compile_upto() } + + pub fn add_library_path(&mut self, p: Path) { + debug!("Adding library path: {}", p.display()); + self.context.add_library_path(p); + } + + pub fn additional_library_paths(&self) -> ~[Path] { + self.context.rustc_flags.additional_library_paths.clone() + } } /* @@ -85,6 +94,9 @@ pub struct RustcFlags { target: Option<~str>, // Target CPU (defaults to rustc's default target CPU) target_cpu: Option<~str>, + // Additional library directories, which get passed with the -L flag + // This can't be set with a rustpkg flag, only from package scripts + additional_library_paths: ~[Path], // Any -Z features experimental_features: Option<~[~str]> } @@ -99,6 +111,7 @@ impl Clone for RustcFlags { save_temps: self.save_temps, target: self.target.clone(), target_cpu: self.target_cpu.clone(), + additional_library_paths: self.additional_library_paths.clone(), experimental_features: self.experimental_features.clone() } } @@ -148,6 +161,10 @@ impl Context { pub fn compile_upto(&self) -> StopBefore { self.rustc_flags.compile_upto } + + pub fn add_library_path(&mut self, p: Path) { + self.rustc_flags.additional_library_paths.push(p); + } } /// We assume that if ../../rustc exists, then we're running @@ -210,6 +227,7 @@ impl RustcFlags { save_temps: false, target: None, target_cpu: None, + additional_library_paths: ~[], experimental_features: None } } diff --git a/src/librustpkg/package_source.rs b/src/librustpkg/package_source.rs index 68d2d9662e34..17ba79862e0c 100644 --- a/src/librustpkg/package_source.rs +++ b/src/librustpkg/package_source.rs @@ -23,7 +23,7 @@ use path_util::{find_dir_using_rust_path_hack, make_dir_rwx_recursive, default_w use path_util::{target_build_dir, versionize, dir_has_crate_file}; use util::{compile_crate, DepMap}; use workcache_support; -use workcache_support::crate_tag; +use workcache_support::{digest_only_date, digest_file_with_date, crate_tag}; use extra::workcache; use extra::treemap::TreeMap; @@ -390,7 +390,8 @@ impl PkgSrc { deps: &mut DepMap, crates: &[Crate], cfgs: &[~str], - what: OutputType) { + what: OutputType, + inputs_to_discover: &[(~str, Path)]) { for crate in crates.iter() { let path = self.start_dir.join(&crate.file); debug!("build_crates: compiling {}", path.display()); @@ -408,7 +409,19 @@ impl PkgSrc { let sub_dir = self.build_workspace().clone(); let sub_flags = crate.flags.clone(); let sub_deps = deps.clone(); + let inputs = inputs_to_discover.map(|&(ref k, ref p)| + (k.clone(), p.as_str().unwrap().to_owned())); do prep.exec |exec| { + for &(ref kind, ref p) in inputs.iter() { + let pth = Path::new(p.clone()); + exec.discover_input(*kind, *p, if *kind == ~"file" { + digest_file_with_date(&pth) + } else if *kind == ~"binary" { + digest_only_date(&Path::new(p.clone())) + } else { + fail!("Bad kind in build_crates") + }); + } let result = compile_crate(&subcx, exec, &id, @@ -452,22 +465,43 @@ impl PkgSrc { build_context: &BuildContext, // DepMap is a map from str (crate name) to (kind, name) -- // it tracks discovered dependencies per-crate - cfgs: ~[~str]) -> DepMap { + cfgs: ~[~str], + inputs_to_discover: &[(~str, Path)]) -> DepMap { let mut deps = TreeMap::new(); - let libs = self.libs.clone(); let mains = self.mains.clone(); let tests = self.tests.clone(); let benchs = self.benchs.clone(); debug!("Building libs in {}, destination = {}", - self.source_workspace.display(), self.build_workspace().display()); - self.build_crates(build_context, &mut deps, libs, cfgs, Lib); + self.destination_workspace.display(), + self.destination_workspace.display()); + self.build_crates(build_context, + &mut deps, + libs, + cfgs, + Lib, + inputs_to_discover); debug!("Building mains"); - self.build_crates(build_context, &mut deps, mains, cfgs, Main); + self.build_crates(build_context, + &mut deps, + mains, + cfgs, + Main, + inputs_to_discover); debug!("Building tests"); - self.build_crates(build_context, &mut deps, tests, cfgs, Test); + self.build_crates(build_context, + &mut deps, + tests, + cfgs, + Test, + inputs_to_discover); debug!("Building benches"); - self.build_crates(build_context, &mut deps, benchs, cfgs, Bench); + self.build_crates(build_context, + &mut deps, + benchs, + cfgs, + Bench, + inputs_to_discover); deps } diff --git a/src/librustpkg/path_util.rs b/src/librustpkg/path_util.rs index c47c89d777b4..a48ef23115cc 100644 --- a/src/librustpkg/path_util.rs +++ b/src/librustpkg/path_util.rs @@ -461,7 +461,6 @@ pub fn versionize(p: &Path, v: &Version) -> Path { p.with_filename(q) } - #[cfg(target_os = "win32")] pub fn chmod_read_only(p: &Path) -> bool { #[fixed_stack_segment]; @@ -483,3 +482,6 @@ pub fn chmod_read_only(p: &Path) -> bool { } } +pub fn platform_library_name(s: &str) -> ~str { + format!("{}{}{}", os::consts::DLL_PREFIX, s, os::consts::DLL_SUFFIX) +} diff --git a/src/librustpkg/rustpkg.rs b/src/librustpkg/rustpkg.rs index 6c55f7af0c06..37a5a2ea7113 100644 --- a/src/librustpkg/rustpkg.rs +++ b/src/librustpkg/rustpkg.rs @@ -33,7 +33,6 @@ use rustc::metadata::filesearch; use rustc::metadata::filesearch::rust_path; use extra::{getopts}; use syntax::{ast, diagnostic}; -use util::*; use messages::{error, warn, note}; use path_util::{build_pkg_id_in_workspace, built_test_in_workspace}; use path_util::{U_RWX, in_rust_path}; @@ -47,15 +46,16 @@ use context::{Context, BuildContext, LLVMAssemble, LLVMCompileBitcode}; use package_id::PkgId; use package_source::PkgSrc; -use target::{WhatToBuild, Everything, is_lib, is_main, is_test, is_bench, Tests}; +use target::{WhatToBuild, Everything, is_lib, is_main, is_test, is_bench}; +use target::{Tests, MaybeCustom, Inferred, JustOne}; use workcache_support::digest_only_date; use exit_codes::{COPY_FAILED_CODE, BAD_FLAG_CODE}; pub mod api; mod conditions; -mod context; +pub mod context; mod crate; -mod exit_codes; +pub mod exit_codes; mod installed_packages; mod messages; mod package_id; @@ -67,7 +67,7 @@ mod target; #[cfg(test)] mod tests; mod util; -mod version; +pub mod version; pub mod workcache_support; mod workspace; @@ -96,7 +96,7 @@ impl<'self> PkgScript<'self> { /// Given the path name for a package script /// and a package ID, parse the package script into /// a PkgScript that we can then execute - fn parse<'a>(sysroot: @Path, + fn parse<'a>(sysroot: Path, script: Path, workspace: &Path, id: &'a PkgId) -> PkgScript<'a> { @@ -107,7 +107,7 @@ impl<'self> PkgScript<'self> { debug!("pkgscript parse: {}", sysroot.display()); let options = @session::options { binary: binary, - maybe_sysroot: Some(sysroot), + maybe_sysroot: Some(@sysroot), crate_type: session::bin_crate, .. (*session::basic_options()).clone() }; @@ -132,12 +132,7 @@ impl<'self> PkgScript<'self> { } } - /// Run the contents of this package script, where - /// is the command to pass to it (e.g., "build", "clean", "install") - /// Returns a pair of an exit code and list of configs (obtained by - /// calling the package script's configs() function if it exists - fn run_custom(&mut self, exec: &mut workcache::Exec, - sysroot: &Path) -> (~[~str], ExitCode) { + fn build_custom(&mut self, exec: &mut workcache::Exec) -> ~str { let sess = self.sess; debug!("Working directory = {}", self.build_dir.display()); @@ -152,17 +147,28 @@ impl<'self> PkgScript<'self> { &self.build_dir, sess, crate); - debug!("Running program: {} {} {}", exe.display(), - sysroot.display(), "install"); // Discover the output // FIXME (#9639): This needs to handle non-utf8 paths - exec.discover_output("binary", exe.as_str().unwrap(), digest_only_date(&exe)); + // Discover the output + exec.discover_output("binary", exe.as_str().unwrap().to_owned(), digest_only_date(&exe)); + exe.as_str().unwrap().to_owned() + } + + + /// Run the contents of this package script, where + /// is the command to pass to it (e.g., "build", "clean", "install") + /// Returns a pair of an exit code and list of configs (obtained by + /// calling the package script's configs() function if it exists + fn run_custom(exe: &Path, sysroot: &Path) -> (~[~str], int) { + debug!("Running program: {} {} {}", exe.as_str().unwrap().to_owned(), + sysroot.display(), "install"); // FIXME #7401 should support commands besides `install` // FIXME (#9639): This needs to handle non-utf8 paths let status = run::process_status(exe.as_str().unwrap(), [sysroot.as_str().unwrap().to_owned(), ~"install"]); if status != 0 { - return (~[], status); + debug!("run_custom: first pkg command failed with {:?}", status); + (~[], status) } else { debug!("Running program (configs): {} {} {}", @@ -170,6 +176,7 @@ impl<'self> PkgScript<'self> { // FIXME (#9639): This needs to handle non-utf8 paths let output = run::process_output(exe.as_str().unwrap(), [sysroot.as_str().unwrap().to_owned(), ~"configs"]); + debug!("run_custom: second pkg command did {:?}", output.status); // Run the configs() function to get the configs let cfgs = str::from_utf8_slice(output.output).word_iter() .map(|w| w.to_owned()).collect(); @@ -263,7 +270,7 @@ impl CtxMethods for BuildContext { let cwd = os::getcwd(); match cmd { "build" => { - self.build_args(args, &Everything); + self.build_args(args, &WhatToBuild::new(MaybeCustom, Everything)); } "clean" => { if args.len() < 1 { @@ -301,12 +308,14 @@ impl CtxMethods for BuildContext { let inferred_pkgid = PkgId::new(cwd.filename_str().unwrap()); self.install(PkgSrc::new(cwd, default_workspace(), - true, inferred_pkgid), &Everything); + true, inferred_pkgid), + &WhatToBuild::new(MaybeCustom, Everything)); } None => { usage::install(); return; } Some((ws, pkgid)) => { let pkg_src = PkgSrc::new(ws.clone(), ws.clone(), false, pkgid); - self.install(pkg_src, &Everything); + self.install(pkg_src, &WhatToBuild::new(MaybeCustom, + Everything)); } } } @@ -320,7 +329,7 @@ impl CtxMethods for BuildContext { if workspaces.is_empty() { let d = default_workspace(); let src = PkgSrc::new(d.clone(), d, false, pkgid.clone()); - self.install(src, &Everything); + self.install(src, &WhatToBuild::new(MaybeCustom, Everything)); } else { for workspace in workspaces.iter() { @@ -331,7 +340,7 @@ impl CtxMethods for BuildContext { dest, self.context.use_rust_path_hack, pkgid.clone()); - self.install(src, &Everything); + self.install(src, &WhatToBuild::new(MaybeCustom, Everything)); }; } } @@ -354,7 +363,8 @@ impl CtxMethods for BuildContext { } "test" => { // Build the test executable - let maybe_id_and_workspace = self.build_args(args, &Tests); + let maybe_id_and_workspace = self.build_args(args, + &WhatToBuild::new(MaybeCustom, Tests)); match maybe_id_and_workspace { Some((pkg_id, workspace)) => { // Assuming it's built, run the tests @@ -420,6 +430,7 @@ impl CtxMethods for BuildContext { pkgid = {} pkgsrc start_dir = {}", workspace.display(), in_rust_path(&workspace), is_git_dir(&workspace.join(&pkgid.path)), pkgid.to_str(), pkg_src.start_dir.display()); + debug!("build: what to build = {:?}", what_to_build); // If workspace isn't in the RUST_PATH, and it's a git repo, // then clone it into the first entry in RUST_PATH, and repeat @@ -448,27 +459,27 @@ impl CtxMethods for BuildContext { debug!("Package source directory = {}", pkg_src.to_str()); let opt = pkg_src.package_script_option(); debug!("Calling pkg_script_option on {:?}", opt); - let cfgs = match pkg_src.package_script_option() { - Some(package_script_path) => { + let cfgs = match (pkg_src.package_script_option(), what_to_build.build_type) { + (Some(package_script_path), MaybeCustom) => { let sysroot = self.sysroot_to_use(); - // FIXME (#9639): This needs to handle non-utf8 paths - let pkg_script_path_str = package_script_path.as_str().unwrap(); - let (cfgs, hook_result) = - do self.workcache_context.with_prep(pkg_script_path_str) |prep| { - let sub_sysroot = sysroot.clone(); - let package_script_path_clone = package_script_path.clone(); - let sub_ws = workspace.clone(); - let sub_id = pkgid.clone(); - declare_package_script_dependency(prep, &*pkg_src); + // Build the package script if needed + let script_build = format!("build_package_script({})", + package_script_path.display()); + let pkg_exe = do self.workcache_context.with_prep(script_build) |prep| { + let subsysroot = sysroot.clone(); + let psp = package_script_path.clone(); + let ws = workspace.clone(); + let pid = pkgid.clone(); do prep.exec |exec| { - let mut pscript = PkgScript::parse(@sub_sysroot.clone(), - package_script_path_clone.clone(), - &sub_ws, - &sub_id); - - pscript.run_custom(exec, &sub_sysroot) + let mut pscript = PkgScript::parse(subsysroot.clone(), + psp.clone(), + &ws, + &pid); + pscript.build_custom(exec) } }; + // We always *run* the package script + let (cfgs, hook_result) = PkgScript::run_custom(&Path::new(pkg_exe), &sysroot); debug!("Command return code = {:?}", hook_result); if hook_result != 0 { fail!("Error running custom build command") @@ -477,7 +488,11 @@ impl CtxMethods for BuildContext { // otherwise, the package script succeeded cfgs } - None => { + (Some(_), Inferred) => { + debug!("There is a package script, but we're ignoring it"); + ~[] + } + (None, _) => { debug!("No package script, continuing"); ~[] } @@ -486,13 +501,13 @@ impl CtxMethods for BuildContext { // If there was a package script, it should have finished // the build already. Otherwise... if !custom { - match what_to_build { + match what_to_build.sources { // Find crates inside the workspace - &Everything => pkg_src.find_crates(), + Everything => pkg_src.find_crates(), // Find only tests - &Tests => pkg_src.find_crates_with_filter(|s| { is_test(&Path::new(s)) }), + Tests => pkg_src.find_crates_with_filter(|s| { is_test(&Path::new(s)) }), // Don't infer any crates -- just build the one that was requested - &JustOne(ref p) => { + JustOne(ref p) => { // We expect that p is relative to the package source's start directory, // so check that assumption debug!("JustOne: p = {}", p.display()); @@ -512,7 +527,7 @@ impl CtxMethods for BuildContext { } } // Build it! - pkg_src.build(self, cfgs); + pkg_src.build(self, cfgs, []); } } @@ -551,6 +566,8 @@ impl CtxMethods for BuildContext { // just means inferring all the crates in it, then building each one. self.build(&mut pkg_src, what); + debug!("Done building package source {}", pkg_src.to_str()); + let to_do = ~[pkg_src.libs.clone(), pkg_src.mains.clone(), pkg_src.tests.clone(), pkg_src.benchs.clone()]; debug!("In declare inputs for {}", id.to_str()); @@ -823,6 +840,7 @@ pub fn main_args(args: &[~str]) -> int { save_temps: save_temps, target: target, target_cpu: target_cpu, + additional_library_paths: ~[], // No way to set this from the rustpkg command line experimental_features: experimental_features }; @@ -895,7 +913,8 @@ pub fn main_args(args: &[~str]) -> int { use_rust_path_hack: use_rust_path_hack, sysroot: sroot.clone(), // Currently, only tests override this }, - workcache_context: api::default_context(default_workspace()).workcache_context + workcache_context: api::default_context(sroot.clone(), + default_workspace()).workcache_context }.run(sub_cmd, rm_args.clone()) }; // FIXME #9262: This is using the same error code for all errors, diff --git a/src/librustpkg/target.rs b/src/librustpkg/target.rs index b21641a5e53e..9863fd0a89ee 100644 --- a/src/librustpkg/target.rs +++ b/src/librustpkg/target.rs @@ -23,7 +23,31 @@ pub enum Target { } #[deriving(Eq, Clone)] -pub enum WhatToBuild { +pub struct WhatToBuild { + build_type: BuildType, // Whether or not to ignore the pkg.rs file + sources: SourceType, // Which crates to build + inputs_to_discover: ~[(~str, Path)] // Inputs to these crates to be discovered + // (For now all of these inputs will be taken as discovered inputs + // for all of the crates) + // (Paired with their kinds) +} + +impl WhatToBuild { + pub fn new(build_type: BuildType, sources: SourceType) -> WhatToBuild { + WhatToBuild { build_type: build_type, + sources: sources, + inputs_to_discover: ~[] } + } +} + +#[deriving(Eq, Clone)] +pub enum BuildType { + Inferred, // Ignore the pkg.rs file even if one exists + MaybeCustom // Use the pkg.rs file if it exists +} + +#[deriving(Eq, Clone)] +pub enum SourceType { /// Build just one lib.rs file in `path`, which is relative to the active workspace's src/ dir JustOne(Path), /// Build any test.rs files that can be recursively found in the active workspace diff --git a/src/librustpkg/tests.rs b/src/librustpkg/tests.rs index 58c6b4ff81fb..16e13f700921 100644 --- a/src/librustpkg/tests.rs +++ b/src/librustpkg/tests.rs @@ -28,7 +28,7 @@ use path_util::{target_executable_in_workspace, target_test_in_workspace, library_in_workspace, installed_library_in_workspace, built_bench_in_workspace, built_test_in_workspace, built_library_in_workspace, built_executable_in_workspace, target_build_dir, - chmod_read_only}; + chmod_read_only, platform_library_name}; use rustc::back::link::get_cc_prog; use rustc::metadata::filesearch::rust_path; use rustc::driver::driver::{build_session, build_session_options, host_triple, optgroups}; @@ -299,12 +299,6 @@ fn command_line_test_with_env(args: &[~str], cwd: &Path, env: Option<~[(~str, ~s cmd, args, str::from_utf8(output.output), str::from_utf8(output.error), output.status); -/* -By the way, rustpkg *won't* return a nonzero exit code if it fails -- -see #4547 -So tests that use this need to check the existence of a file -to make sure the command succeeded -*/ if output.status != 0 { debug!("Command {} {:?} failed with exit code {:?}; its output was --- {} ---", cmd, args, output.status, @@ -600,7 +594,7 @@ fn test_install_valid() { temp_workspace.clone(), false, temp_pkg_id.clone()); - ctxt.install(src, &Everything); + ctxt.install(src, &WhatToBuild::new(MaybeCustom, Everything)); // Check that all files exist let exec = target_executable_in_workspace(&temp_pkg_id, temp_workspace); debug!("exec = {}", exec.display()); @@ -639,7 +633,7 @@ fn test_install_invalid() { temp_workspace.clone(), false, pkgid.clone()); - ctxt.install(pkg_src, &Everything); + ctxt.install(pkg_src, &WhatToBuild::new(MaybeCustom, Everything)); }; // Not the best test -- doesn't test that we failed in the right way. // Best we can do for now. @@ -897,14 +891,14 @@ fn rustpkg_local_pkg() { } #[test] -#[ignore (reason = "test makes bogus assumptions about build directory layout: issue #8690")] fn package_script_with_default_build() { let dir = create_local_package(&PkgId::new("fancy-lib")); let dir = dir.path(); debug!("dir = {}", dir.display()); let mut source = test_sysroot().dir_path(); source.pop(); source.pop(); - source.push_many(["src", "librustpkg", "testsuite", "pass", "src", "fancy-lib", "pkg.rs"]); + let source = Path::new(file!()).dir_path().join_many( + [~"testsuite", ~"pass", ~"src", ~"fancy-lib", ~"pkg.rs"]); debug!("package_script_with_default_build: {}", source.display()); if !os::copy_file(&source, &dir.join_many(["src", "fancy-lib-0.1", "pkg.rs"])) { @@ -912,7 +906,10 @@ fn package_script_with_default_build() { } command_line_test([~"install", ~"fancy-lib"], dir); assert_lib_exists(dir, &Path::new("fancy-lib"), NoVersion); - assert!(os::path_exists(&target_build_dir(dir).join_many(["fancy-lib", "generated.rs"]))); + assert!(os::path_exists(&target_build_dir(dir).join_many([~"fancy-lib", ~"generated.rs"]))); + let generated_path = target_build_dir(dir).join_many([~"fancy-lib", ~"generated.rs"]); + debug!("generated path = {}", generated_path.display()); + assert!(os::path_exists(&generated_path)); } #[test] @@ -2251,6 +2248,106 @@ fn find_sources_in_cwd() { assert_executable_exists(&source_dir.join(".rust"), "foo"); } +#[test] +fn test_c_dependency_ok() { + // Pkg has a custom build script that adds a single C file as a dependency, and + // registers a hook to build it if it's not fresh + // After running `build`, test that the C library built + + let dir = create_local_package(&PkgId::new("cdep")); + let dir = dir.path(); + writeFile(&dir.join_many(["src", "cdep-0.1", "main.rs"]), + "#[link_args = \"-lfoo\"]\nextern { fn f(); } \ + \n#[fixed_stack_segment]\nfn main() { unsafe { f(); } }"); + writeFile(&dir.join_many(["src", "cdep-0.1", "foo.c"]), "void f() {}"); + + debug!("dir = {}", dir.display()); + let source = Path::new(file!()).dir_path().join_many( + [~"testsuite", ~"pass", ~"src", ~"c-dependencies", ~"pkg.rs"]); + if !os::copy_file(&source, + &dir.join_many([~"src", ~"cdep-0.1", ~"pkg.rs"])) { + fail!("Couldn't copy file"); + } + command_line_test([~"build", ~"cdep"], dir); + assert_executable_exists(dir, "cdep"); + let out_dir = target_build_dir(dir).join("cdep"); + let c_library_path = out_dir.join(platform_library_name("foo")); + debug!("c library path: {}", c_library_path.display()); + assert!(os::path_exists(&c_library_path)); +} + +#[test] +fn test_c_dependency_no_rebuilding() { + let dir = create_local_package(&PkgId::new("cdep")); + let dir = dir.path(); + writeFile(&dir.join_many(["src", "cdep-0.1", "main.rs"]), + "#[link_args = \"-lfoo\"]\nextern { fn f(); } \ + \n#[fixed_stack_segment]\nfn main() { unsafe { f(); } }"); + writeFile(&dir.join_many(["src", "cdep-0.1", "foo.c"]), "void f() {}"); + + debug!("dir = {}", dir.display()); + let source = Path::new(file!()).dir_path().join_many( + [~"testsuite", ~"pass", ~"src", ~"c-dependencies", ~"pkg.rs"]); + if !os::copy_file(&source, + &dir.join_many([~"src", ~"cdep-0.1", ~"pkg.rs"])) { + fail!("Couldn't copy file"); + } + command_line_test([~"build", ~"cdep"], dir); + assert_executable_exists(dir, "cdep"); + let out_dir = target_build_dir(dir).join("cdep"); + let c_library_path = out_dir.join(platform_library_name("foo")); + debug!("c library path: {}", c_library_path.display()); + assert!(os::path_exists(&c_library_path)); + + // Now, make it read-only so rebuilding will fail + assert!(chmod_read_only(&c_library_path)); + + match command_line_test_partial([~"build", ~"cdep"], dir) { + Success(*) => (), // ok + Fail(status) if status == 65 => fail!("test_c_dependency_no_rebuilding failed: \ + it tried to rebuild foo.c"), + Fail(_) => fail!("test_c_dependency_no_rebuilding failed for some other reason") + } +} + +#[test] +fn test_c_dependency_yes_rebuilding() { + let dir = create_local_package(&PkgId::new("cdep")); + let dir = dir.path(); + writeFile(&dir.join_many(["src", "cdep-0.1", "main.rs"]), + "#[link_args = \"-lfoo\"]\nextern { fn f(); } \ + \n#[fixed_stack_segment]\nfn main() { unsafe { f(); } }"); + let c_file_name = dir.join_many(["src", "cdep-0.1", "foo.c"]); + writeFile(&c_file_name, "void f() {}"); + + let source = Path::new(file!()).dir_path().join_many( + [~"testsuite", ~"pass", ~"src", ~"c-dependencies", ~"pkg.rs"]); + let target = dir.join_many([~"src", ~"cdep-0.1", ~"pkg.rs"]); + debug!("Copying {} -> {}", source.display(), target.display()); + if !os::copy_file(&source, &target) { + fail!("Couldn't copy file"); + } + command_line_test([~"build", ~"cdep"], dir); + assert_executable_exists(dir, "cdep"); + let out_dir = target_build_dir(dir).join("cdep"); + let c_library_path = out_dir.join(platform_library_name("foo")); + debug!("c library path: {}", c_library_path.display()); + assert!(os::path_exists(&c_library_path)); + + // Now, make the Rust library read-only so rebuilding will fail + match built_library_in_workspace(&PkgId::new("cdep"), dir) { + Some(ref pth) => assert!(chmod_read_only(pth)), + None => assert_built_library_exists(dir, "cdep") + } + + match command_line_test_partial([~"build", ~"cdep"], dir) { + Success(*) => fail!("test_c_dependency_yes_rebuilding failed: \ + it didn't rebuild and should have"), + Fail(status) if status == 65 => (), + Fail(_) => fail!("test_c_dependency_yes_rebuilding failed for some other reason") + } +} + /// Returns true if p exists and is executable fn is_executable(p: &Path) -> bool { use std::libc::consts::os::posix88::{S_IXUSR}; diff --git a/src/librustpkg/testsuite/pass/src/c-dependencies/bar.rs b/src/librustpkg/testsuite/pass/src/c-dependencies/bar.rs new file mode 100644 index 000000000000..ffbc6e2a7f9b --- /dev/null +++ b/src/librustpkg/testsuite/pass/src/c-dependencies/bar.rs @@ -0,0 +1,13 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub fn assert_true() { + assert!(true); +} diff --git a/src/librustpkg/testsuite/pass/src/c-dependencies/foo.rs b/src/librustpkg/testsuite/pass/src/c-dependencies/foo.rs new file mode 100644 index 000000000000..542a6af402d0 --- /dev/null +++ b/src/librustpkg/testsuite/pass/src/c-dependencies/foo.rs @@ -0,0 +1,12 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub fn do_nothing() { +} \ No newline at end of file diff --git a/src/librustpkg/testsuite/pass/src/c-dependencies/lib.rs b/src/librustpkg/testsuite/pass/src/c-dependencies/lib.rs new file mode 100644 index 000000000000..bd1cb240a34c --- /dev/null +++ b/src/librustpkg/testsuite/pass/src/c-dependencies/lib.rs @@ -0,0 +1,14 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern mod std; + +pub mod foo; +pub mod bar; diff --git a/src/librustpkg/testsuite/pass/src/c-dependencies/pkg.rs b/src/librustpkg/testsuite/pass/src/c-dependencies/pkg.rs new file mode 100644 index 000000000000..b667dc0a576f --- /dev/null +++ b/src/librustpkg/testsuite/pass/src/c-dependencies/pkg.rs @@ -0,0 +1,83 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern mod rustpkg; +extern mod rustc; + +use std::{io, os, task}; +use rustpkg::api; +use rustpkg::version::NoVersion; +use rustpkg::workcache_support::digest_file_with_date; +use rustpkg::exit_codes::COPY_FAILED_CODE; + +pub fn main() { + let args = os::args(); + +// by convention, first arg is sysroot + if args.len() < 2 { + fail!("Package script requires a directory where rustc libraries live as the first \ + argument"); + } + + let path_for_db = api::default_workspace(); + debug!("path_for_db = {}", path_for_db.display()); + + let sysroot_arg = args[1].clone(); + let sysroot = Path::new(sysroot_arg); + if !os::path_exists(&sysroot) { + fail!("Package script requires a sysroot that exists; {} doesn't", sysroot.display()); + } + + if args[2] != ~"install" { + io::println(format!("Warning: I don't know how to {}", args[2])); + return; + } + + let mut context = api::default_context(sysroot, path_for_db); + let my_workspace = api::my_workspace(&context.context, "cdep"); + let foo_c_name = my_workspace.join_many(["src", "cdep-0.1", "foo.c"]); + + let out_lib_path = do context.workcache_context.with_prep("foo.c") |prep| { + let sub_cx = context.context.clone(); + debug!("foo_c_name = {}", foo_c_name.display()); + prep.declare_input("file", + foo_c_name.as_str().unwrap().to_owned(), + digest_file_with_date(&foo_c_name)); + let out_path = do prep.exec |exec| { + let out_path = api::build_library_in_workspace(exec, + &mut sub_cx.clone(), + "cdep", + "gcc", + [~"-c"], + [~"foo.c"], + "foo"); + let out_p = Path::new(out_path); + out_p.as_str().unwrap().to_owned() + }; + out_path + }; + let out_lib_path = Path::new(out_lib_path); + debug!("out_lib_path = {}", out_lib_path.display()); + context.add_library_path(out_lib_path.dir_path()); + + let context_clone = context.clone(); + let task_res = do task::try { + let mut cc = context_clone.clone(); + api::install_pkg(&mut cc, + os::getcwd(), + ~"cdep", + NoVersion, + ~[(~"binary", out_lib_path.clone()), (~"file", foo_c_name.clone())]); + }; + + if task_res.is_err() { + os::set_exit_status(COPY_FAILED_CODE); + } +} diff --git a/src/librustpkg/testsuite/pass/src/fancy-lib/lib.rs b/src/librustpkg/testsuite/pass/src/fancy-lib/lib.rs index dc068eed143e..17386cd03c22 100644 --- a/src/librustpkg/testsuite/pass/src/fancy-lib/lib.rs +++ b/src/librustpkg/testsuite/pass/src/fancy-lib/lib.rs @@ -21,4 +21,4 @@ extern mod std; pub mod foo; pub mod bar; -#[path = "../../build/fancy_lib/generated.rs"] pub mod generated; +#[path = "../../build/fancy-lib/generated.rs"] pub mod generated; diff --git a/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs b/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs index db11ffa0cc64..0b838b3e0f9e 100644 --- a/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs +++ b/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs @@ -15,42 +15,37 @@ use std::{io, os}; use rustpkg::api; use rustpkg::version::NoVersion; -use rustc::metadata::filesearch; - pub fn main() { - use std::libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR}; let args = os::args(); // by convention, first arg is sysroot if args.len() < 2 { + debug!("Failing, arg len"); fail!("Package script requires a directory where rustc libraries live as the first \ argument"); } let sysroot_arg = args[1].clone(); - let sysroot = Path(sysroot_arg); + let sysroot = Path::new(sysroot_arg); if !os::path_exists(&sysroot) { - fail!("Package script requires a sysroot that exists; %s doesn't", sysroot.to_str()); + debug!("Failing, sysroot"); + fail!("Package script requires a sysroot that exists;{} doesn't", sysroot.display()); } if args[2] != ~"install" { + debug!("Failing, weird command"); println!("Warning: I don't know how to {}", args[2]); return; } - let out_path = Path("build/fancy-lib"); - if !os::path_exists(&out_path) { - assert!(os::make_dir(&out_path, (S_IRUSR | S_IWUSR | S_IXUSR) as i32)); - } + debug!("Checking self_exe_path"); + let out_path = os::self_exe_path().expect("Couldn't get self_exe path"); - let file = io::file_writer(&out_path.push("generated.rs"), - [io::Create]).unwrap(); - file.write_str("pub fn wheeeee() { for [1, 2, 3].each() |_| { assert!(true); } }"); + debug!("Writing file"); + let file = io::file_writer(&out_path.join("generated.rs"), [io::Create]).unwrap(); + file.write_str("pub fn wheeeee() { let xs = [1, 2, 3]; \ + for _ in xs.iter() { assert!(true); } }"); - - debug!("api_____install_____lib, my sysroot:"); - debug!(sysroot.to_str()); - - api::install_lib(@sysroot, os::getcwd(), ~"fancy-lib", Path("lib.rs"), - NoVersion); + let context = api::default_context(sysroot, api::default_workspace()); + api::install_pkg(&context, os::getcwd(), ~"fancy-lib", NoVersion, ~[]); } diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index a3a4a07cfc77..0e4fbbf2c10f 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -27,11 +27,13 @@ use context::{in_target, StopBefore, Link, Assemble, BuildContext}; use package_id::PkgId; use package_source::PkgSrc; use workspace::pkg_parent_workspaces; -use path_util::{U_RWX, system_library, target_build_dir}; +use path_util::{system_library, target_build_dir}; use path_util::{default_workspace, built_library_in_workspace}; pub use target::{OutputType, Main, Lib, Bench, Test, JustOne, lib_name_of, lib_crate_filename}; pub use target::{Target, Build, Install}; use extra::treemap::TreeMap; +use path_util::U_RWX; +pub use target::{lib_name_of, lib_crate_filename, WhatToBuild, MaybeCustom, Inferred}; use workcache_support::{digest_file_with_date, digest_only_date}; // It would be nice to have the list of commands in just one place -- for example, @@ -233,12 +235,14 @@ pub fn compile_input(context: &BuildContext, Nothing => link::output_type_exe }; + debug!("Output type = {:?}", output_type); + let options = @session::options { crate_type: crate_type, optimize: if opt { session::Aggressive } else { session::No }, test: what == Test || what == Bench, maybe_sysroot: Some(sysroot_to_use), - addl_lib_search_paths: @mut (~[]), + addl_lib_search_paths: @mut context.additional_library_paths(), output_type: output_type, .. (*driver::build_session_options(binary, &matches, @@ -246,6 +250,8 @@ pub fn compile_input(context: &BuildContext, @diagnostic::Emitter)).clone() }; + debug!("Created options..."); + let addl_lib_search_paths = @mut options.addl_lib_search_paths; // Make sure all the library directories actually exist, since the linker will complain // otherwise @@ -258,16 +264,22 @@ pub fn compile_input(context: &BuildContext, } } + debug!("About to build session..."); + let sess = driver::build_session(options, @diagnostic::DefaultEmitter as @diagnostic::Emitter); + debug!("About to build config..."); + // Infer dependencies that rustpkg needs to build, by scanning for // `extern mod` directives. let cfg = driver::build_configuration(sess); let mut crate = driver::phase_1_parse_input(sess, cfg.clone(), &input); crate = driver::phase_2_configure_and_expand(sess, cfg.clone(), crate); + debug!("About to call find_and_install_dependencies..."); + find_and_install_dependencies(context, pkg_id, in_file, sess, exec, &crate, deps, |p| { debug!("a dependency: {}", p.display()); @@ -377,7 +389,6 @@ pub fn compile_crate_from_input(input: &Path, debug!("Built {}, date = {:?}", outputs.out_filename.display(), datestamp(&outputs.out_filename)); - Some(outputs.out_filename) } @@ -431,7 +442,9 @@ impl<'self> Visitor<()> for ViewItemVisitor<'self> { }; debug!("Finding and installing... {}", lib_name); // Check standard Rust library path first - match system_library(&self.context.sysroot(), lib_name) { + let whatever = system_library(&self.context.sysroot(), lib_name); + debug!("system library returned {:?}", whatever); + match whatever { Some(ref installed_path) => { debug!("It exists: {}", installed_path.display()); // Say that [path for c] has a discovered dependency on @@ -478,7 +491,10 @@ impl<'self> Visitor<()> for ViewItemVisitor<'self> { self.context.context.use_rust_path_hack, pkg_id.clone()); let (outputs_disc, inputs_disc) = - self.context.install(pkg_src, &JustOne(Path::new(lib_crate_filename))); + self.context.install( + pkg_src, + &WhatToBuild::new(Inferred, + JustOne(Path::new(lib_crate_filename)))); debug!("Installed {}, returned {:?} dependencies and \ {:?} transitive dependencies", lib_name, outputs_disc.len(), inputs_disc.len()); From 567a03d19b81aa6cb0e46df5f379db1dc268c983 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 22 Oct 2013 21:04:15 -0700 Subject: [PATCH 26/26] testsuite: Test cases, all except issue-5216 xfailed --- src/test/compile-fail/issue-5216.rs | 20 ++++++++++ src/test/compile-fail/issue-5500-1.rs | 22 +++++++++++ src/test/compile-fail/issue-5500.rs | 13 +++++++ src/test/run-pass/issue-6334.rs | 56 +++++++++++++++++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 src/test/compile-fail/issue-5216.rs create mode 100644 src/test/compile-fail/issue-5500-1.rs create mode 100644 src/test/compile-fail/issue-5500.rs create mode 100644 src/test/run-pass/issue-6334.rs diff --git a/src/test/compile-fail/issue-5216.rs b/src/test/compile-fail/issue-5216.rs new file mode 100644 index 000000000000..9f88ba72f059 --- /dev/null +++ b/src/test/compile-fail/issue-5216.rs @@ -0,0 +1,20 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn f() { } +struct S(&fn()); //~ ERROR Illegal anonymous lifetime +pub static C: S = S(f); //~ ERROR Illegal anonymous lifetime + + +fn g() { } +type T = &fn(); //~ ERROR Illegal anonymous lifetime +pub static D: T = g; //~ ERROR Illegal anonymous lifetime + +fn main() {} diff --git a/src/test/compile-fail/issue-5500-1.rs b/src/test/compile-fail/issue-5500-1.rs new file mode 100644 index 000000000000..f709aadf4ac8 --- /dev/null +++ b/src/test/compile-fail/issue-5500-1.rs @@ -0,0 +1,22 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// xfail-test + +struct TrieMapIterator<'self> { + priv node: &'self uint +} + +fn main() { + let a = 5; + let _iter = TrieMapIterator{node: &a}; //~ ERROR bad + _iter.node = & + fail!() +} diff --git a/src/test/compile-fail/issue-5500.rs b/src/test/compile-fail/issue-5500.rs new file mode 100644 index 000000000000..7bf20037f5ab --- /dev/null +++ b/src/test/compile-fail/issue-5500.rs @@ -0,0 +1,13 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// xfail-test + +fn main() { &fail!() } //~ ERROR bad diff --git a/src/test/run-pass/issue-6334.rs b/src/test/run-pass/issue-6334.rs new file mode 100644 index 000000000000..740a2212726d --- /dev/null +++ b/src/test/run-pass/issue-6334.rs @@ -0,0 +1,56 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// xfail-test + +// Tests that everything still compiles and runs fine even when +// we reorder the bounds. + +trait A { + fn a(&self) -> uint; +} + +trait B { + fn b(&self) -> uint; +} + +trait C { + fn combine(&self, t: &T) -> uint; +} + +struct Foo; + +impl A for Foo { + fn a(&self) -> uint { 1 } +} + +impl B for Foo { + fn b(&self) -> uint { 2 } +} + +struct Bar; + +impl C for Bar { + // Note below: bounds in impl decl are in reverse order. + fn combine(&self, t: &T) -> uint { + (t.a() * 100) + t.b() + } +} + +fn use_c(s: &S, t: &T) -> uint { + s.combine(t) +} + +fn main() { + let foo = Foo; + let bar = Bar; + let r = use_c(&bar, &foo); + assert_eq!(r, 102); +}