This is the final commit need to implement [RFC #4](https://github.com/rust-lang/rfcs/blob/master/active/0004-private-fields.md), it makes all tuple struct fields private by default, overridable with the `pub` keyword.
I'll note one divergence from the original RFC which is outlined in the first commit.
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
- pub struct Exp1(f64);
+ pub struct Exp1(pub f64);
// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
impl Rand for Exp1 {
#[bench]
fn rand_exp(bh: &mut BenchHarness) {
- let mut rng = XorShiftRng::new();
+ let mut rng = XorShiftRng::new().unwrap();
let mut exp = Exp::new(2.71828 * 3.14159);
bh.iter(|| {
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
- pub struct StandardNormal(f64);
+ pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
fn rand<R:Rng>(rng: &mut R) -> StandardNormal {
#[bench]
fn rand_normal(bh: &mut BenchHarness) {
- let mut rng = XorShiftRng::new();
+ let mut rng = XorShiftRng::new().unwrap();
let mut normal = Normal::new(-2.71828, 3.14159);
bh.iter(|| {
```
*/
-#![crate_id = "rand#0.10-pre"]
+#![crate_id = "rand#0.10"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, managed_boxes, phase)]
#![allow(visible_private_types)] // NOTE: remove after a stage0 snap
+#![deny(deprecated_owned_vector)]
#[cfg(test)]
#[phase(syntax, link)] extern crate log;
use std::cast;
+use std::io::IoResult;
use std::kinds::marker;
use std::local_data;
use std::str;
-use std::slice;
pub use isaac::{IsaacRng, Isaac64Rng};
pub use os::OSRng;
/// use rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
- /// let x: ~[uint] = rng.gen_vec(10);
- /// println!("{:?}", x);
- /// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
+ /// let x: Vec<uint> = rng.gen_vec(10);
+ /// println!("{}", x);
+ /// println!("{}", rng.gen_vec::<(f64, bool)>(5));
/// ```
- fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
- slice::from_fn(len, |_| self.gen())
+ fn gen_vec<T: Rand>(&mut self, len: uint) -> Vec<T> {
+ Vec::from_fn(len, |_| self.gen())
}
/// Generate a random value in the range [`low`, `high`). Fails if
}
}
- /// Shuffle a vec
- ///
- /// # Example
- ///
- /// ```rust
- /// use rand::{task_rng, Rng};
- ///
- /// println!("{:?}", task_rng().shuffle(~[1,2,3]));
- /// ```
- fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
- let mut v = values;
- self.shuffle_mut(v);
- v
- }
-
- /// Shuffle a mutable vector in place.
+ /// Shuffle a mutable slice in place.
///
/// # Example
///
///
/// let mut rng = task_rng();
/// let mut y = [1,2,3];
- /// rng.shuffle_mut(y);
- /// println!("{:?}", y);
- /// rng.shuffle_mut(y);
- /// println!("{:?}", y);
+ /// rng.shuffle(y);
+ /// println!("{}", y.as_slice());
+ /// rng.shuffle(y);
+ /// println!("{}", y.as_slice());
/// ```
- fn shuffle_mut<T>(&mut self, values: &mut [T]) {
+ fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
}
}
+ /// Shuffle a mutable slice in place.
+ #[deprecated="renamed to `.shuffle`"]
+ fn shuffle_mut<T>(&mut self, values: &mut [T]) {
+ self.shuffle(values)
+ }
+
/// Randomly sample up to `n` elements from an iterator.
///
/// # Example
///
/// let mut rng = task_rng();
/// let sample = rng.sample(range(1, 100), 5);
- /// println!("{:?}", sample);
+ /// println!("{}", sample);
/// ```
- fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
- let mut reservoir : ~[A] = slice::with_capacity(n);
+ fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> Vec<A> {
+ let mut reservoir = Vec::with_capacity(n);
for (i, elem) in iter.enumerate() {
if i < n {
reservoir.push(elem);
let k = self.gen_range(0, i + 1);
if k < reservoir.len() {
- reservoir[k] = elem
+ *reservoir.get_mut(k) = elem
}
}
reservoir
/// appropriate.
#[deprecated="use `task_rng` or `StdRng::new`"]
pub fn rng() -> StdRng {
- StdRng::new()
+ StdRng::new().unwrap()
}
/// The standard RNG. This is designed to be efficient on the current
/// number of random numbers, or doesn't need the utmost speed for
/// generating each number, `task_rng` and/or `random` may be more
/// appropriate.
+ ///
+ /// Reading the randomness from the OS may fail, and any error is
+ /// propagated via the `IoResult` return value.
#[cfg(not(target_word_size="64"))]
- pub fn new() -> StdRng {
- StdRng { rng: IsaacRng::new() }
+ pub fn new() -> IoResult<StdRng> {
+ IsaacRng::new().map(|r| StdRng { rng: r })
}
/// Create a randomly seeded instance of `StdRng`.
///
/// number of random numbers, or doesn't need the utmost speed for
/// generating each number, `task_rng` and/or `random` may be more
/// appropriate.
+ ///
+ /// Reading the randomness from the OS may fail, and any error is
+ /// propagated via the `IoResult` return value.
#[cfg(target_word_size="64")]
- pub fn new() -> StdRng {
- StdRng { rng: Isaac64Rng::new() }
+ pub fn new() -> IoResult<StdRng> {
+ Isaac64Rng::new().map(|r| StdRng { rng: r })
}
}
/// This will read randomness from the operating system to seed the
/// generator.
pub fn weak_rng() -> XorShiftRng {
- XorShiftRng::new()
+ match XorShiftRng::new() {
+ Ok(r) => r,
+ Err(e) => fail!("weak_rng: failed to create seeded RNG: {}", e)
+ }
}
/// An Xorshift[1] random number
impl XorShiftRng {
/// Create an xor shift random number generator with a random seed.
- pub fn new() -> XorShiftRng {
+ pub fn new() -> IoResult<XorShiftRng> {
let mut s = [0u8, ..16];
+ let mut r = try!(OSRng::new());
loop {
- let mut r = OSRng::new();
r.fill_bytes(s);
if !s.iter().all(|x| *x == 0) {
}
}
let s: [u32, ..4] = unsafe { cast::transmute(s) };
- SeedableRng::from_seed(s)
+ Ok(SeedableRng::from_seed(s))
}
}
impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
- *rng = StdRng::new();
+ *rng = match StdRng::new() {
+ Ok(r) => r,
+ Err(e) => fail!("could not reseed task_rng: {}", e)
+ }
}
}
static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
pub fn task_rng() -> TaskRng {
local_data::get_mut(TASK_RNG_KEY, |rng| match rng {
None => {
- let mut rng = ~reseeding::ReseedingRng::new(StdRng::new(),
+ let r = match StdRng::new() {
+ Ok(r) => r,
+ Err(e) => fail!("could not initialize task_rng: {}", e)
+ };
+ let mut rng = ~reseeding::ReseedingRng::new(r,
TASK_RNG_RESEED_THRESHOLD,
TaskRngReseeder);
let ptr = &mut *rng as *mut TaskRngInner;
/// let Open01(val) = random::<Open01<f32>>();
/// println!("f32 from (0,1): {}", val);
/// ```
- pub struct Open01<F>(F);
+ pub struct Open01<F>(pub F);
/// A wrapper for generating floating point numbers uniformly in the
/// closed interval `[0,1]` (including both endpoints).
/// let Closed01(val) = random::<Closed01<f32>>();
/// println!("f32 from [0,1]: {}", val);
/// ```
- pub struct Closed01<F>(F);
+ pub struct Closed01<F>(pub F);
#[cfg(test)]
mod test {
- use std::slice;
- use super::{Rng, task_rng, random, OSRng, SeedableRng, StdRng};
+ use super::{Rng, task_rng, random, SeedableRng, StdRng};
struct ConstRng { i: u64 }
impl Rng for ConstRng {
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 = slice::from_elem(n, 0u8);
- r.fill_bytes(v);
+ let mut v = Vec::from_elem(n, 0u8);
+ r.fill_bytes(v.as_mut_slice());
// use this to get nicer error messages.
for (i, &byte) in v.iter().enumerate() {
#[test]
fn test_shuffle() {
let mut r = task_rng();
- let empty: ~[int] = ~[];
- assert_eq!(r.shuffle(~[]), empty);
- assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
+ let mut empty: &mut [int] = &mut [];
+ r.shuffle(empty);
+ let mut one = [1];
+ r.shuffle(one);
+ assert_eq!(one.as_slice(), &[1]);
+
+ let mut two = [1, 2];
+ r.shuffle(two);
+ assert!(two == [1, 2] || two == [2, 1]);
+
+ let mut x = [1, 1, 1];
+ r.shuffle(x);
+ assert_eq!(x.as_slice(), &[1, 1, 1]);
}
#[test]
fn test_task_rng() {
let mut r = task_rng();
r.gen::<int>();
- assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
+ let mut v = [1, 1, 1];
+ r.shuffle(v);
+ assert_eq!(v.as_slice(), &[1, 1, 1]);
assert_eq!(r.gen_range(0u, 1u), 0u);
}
let max_val = 100;
let mut r = task_rng();
- let vals = range(min_val, max_val).collect::<~[int]>();
+ let vals = range(min_val, max_val).collect::<Vec<int>>();
let small_sample = r.sample(vals.iter(), 5);
let large_sample = r.sample(vals.iter(), vals.len() + 5);
#[test]
fn test_std_rng_seeded() {
- let s = OSRng::new().gen_vec::<uint>(256);
+ let s = task_rng().gen_vec::<uint>(256);
let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
#[test]
fn test_std_rng_reseed() {
- let s = OSRng::new().gen_vec::<uint>(256);
+ let s = task_rng().gen_vec::<uint>(256);
let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
let string1 = r.gen_ascii_str(100);
- r.reseed(s);
+ r.reseed(s.as_slice());
let string2 = r.gen_ascii_str(100);
assert_eq!(string1, string2);
#[bench]
fn rand_xorshift(bh: &mut BenchHarness) {
- let mut rng = XorShiftRng::new();
+ let mut rng = XorShiftRng::new().unwrap();
bh.iter(|| {
for _ in range(0, RAND_BENCH_N) {
rng.gen::<uint>();
#[bench]
fn rand_isaac(bh: &mut BenchHarness) {
- let mut rng = IsaacRng::new();
+ let mut rng = IsaacRng::new().unwrap();
bh.iter(|| {
for _ in range(0, RAND_BENCH_N) {
rng.gen::<uint>();
#[bench]
fn rand_isaac64(bh: &mut BenchHarness) {
- let mut rng = Isaac64Rng::new();
+ let mut rng = Isaac64Rng::new().unwrap();
bh.iter(|| {
for _ in range(0, RAND_BENCH_N) {
rng.gen::<uint>();
#[bench]
fn rand_std(bh: &mut BenchHarness) {
- let mut rng = StdRng::new();
+ let mut rng = StdRng::new().unwrap();
bh.iter(|| {
for _ in range(0, RAND_BENCH_N) {
rng.gen::<uint>();
#[bench]
fn rand_shuffle_100(bh: &mut BenchHarness) {
- let mut rng = XorShiftRng::new();
+ let mut rng = XorShiftRng::new().unwrap();
let x : &mut[uint] = [1,..100];
bh.iter(|| {
- rng.shuffle_mut(x);
+ rng.shuffle(x);
})
}
}
return decoder::get_symbol(cdata, def.node);
}
-pub fn get_type_param_count(cstore: &cstore::CStore, def: ast::DefId)
- -> uint {
- let cdata = cstore.get_crate_data(def.krate).data();
- return decoder::get_type_param_count(cdata, def.node);
-}
-
/// Iterates over all the language items in the given crate.
pub fn each_lang_item(cstore: &cstore::CStore,
cnum: ast::CrateNum,
decoder::get_impl_vtables(cdata, def.node, tcx)
}
-pub fn get_impl_method(cstore: &cstore::CStore,
- def: ast::DefId,
- mname: ast::Ident)
- -> Option<ast::DefId> {
- let cdata = cstore.get_crate_data(def.krate);
- decoder::get_impl_method(cstore.intr.clone(), cdata, def.node, mname)
-}
-
-pub fn get_item_visibility(cstore: &cstore::CStore,
- def_id: ast::DefId)
- -> ast::Visibility {
- let cdata = cstore.get_crate_data(def_id.krate);
- decoder::get_item_visibility(cdata, def_id.node)
-}
-
pub fn get_native_libraries(cstore: &cstore::CStore,
crate_num: ast::CrateNum)
-> Vec<(cstore::NativeLibaryKind, ~str)> {
let cdata = cstore.get_crate_data(crate_num);
decoder::get_exported_macros(cdata)
}
+
+ pub fn get_tuple_struct_definition_if_ctor(cstore: &cstore::CStore,
+ def_id: ast::DefId)
+ -> Option<ast::DefId>
+ {
+ let cdata = cstore.get_crate_data(def_id.krate);
+ decoder::get_tuple_struct_definition_if_ctor(cdata, def_id.node)
+ }
Rc::new(v)
}
-fn item_ty_param_count(item: ebml::Doc) -> uint {
- let mut n = 0u;
- reader::tagged_docs(item, tag_items_data_item_ty_param_bounds,
- |_p| { n += 1u; true } );
- n
-}
-
fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
let mut ids: Vec<ast::DefId> = Vec::new();
let v = tag_items_data_item_variant;
}
}
-pub fn get_type_param_count(data: &[u8], id: ast::NodeId) -> uint {
- item_ty_param_count(lookup_item(id, data))
-}
-
pub fn get_impl_trait(cdata: Cmd,
id: ast::NodeId,
tcx: &ty::ctxt) -> Option<@ty::TraitRef>
}
-pub fn get_impl_method(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
- name: ast::Ident) -> Option<ast::DefId> {
- let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
- let mut found = None;
- reader::tagged_docs(find_item(id, items), tag_item_impl_method, |mid| {
- let m_did = reader::with_doc_data(mid, parse_def_id);
- if item_name(&*intr, find_item(m_did.node, items)) == name {
- found = Some(translate_def_id(cdata, m_did));
- }
- true
- });
- found
-}
-
pub fn get_symbol(data: &[u8], id: ast::NodeId) -> ~str {
return item_symbol(lookup_item(id, data));
}
DlField
}
-pub fn def_like_to_def(def_like: DefLike) -> ast::Def {
- match def_like {
- DlDef(def) => return def,
- DlImpl(..) => fail!("found impl in def_like_to_def"),
- DlField => fail!("found field in def_like_to_def")
- }
-}
-
/// Iterates over the language items in the given crate.
pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
let root = reader::Doc(cdata.data());
/// If node_id is the constructor of a tuple struct, retrieve the NodeId of
/// the actual type definition, otherwise, return None
pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
- node_id: ast::NodeId) -> Option<ast::NodeId> {
+ node_id: ast::NodeId)
+ -> Option<ast::DefId>
+ {
let item = lookup_item(node_id, cdata.data());
let mut ret = None;
reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
false
});
- ret.map(|x| x.node)
+ ret
}
pub fn get_item_attrs(cdata: Cmd,
- node_id: ast::NodeId,
+ orig_node_id: ast::NodeId,
f: |Vec<@ast::MetaItem> |) {
// The attributes for a tuple struct are attached to the definition, not the ctor;
// we assume that someone passing in a tuple struct ctor is actually wanting to
// look at the definition
- let node_id = get_tuple_struct_definition_if_ctor(cdata, node_id).unwrap_or(node_id);
+ let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
+ let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
let item = lookup_item(node_id, cdata.data());
reader::tagged_docs(item, tag_attributes, |attributes| {
reader::tagged_docs(attributes, tag_attribute, |attribute| {
result
}
-pub fn get_item_visibility(cdata: Cmd, id: ast::NodeId)
- -> ast::Visibility {
- item_visibility(lookup_item(id, cdata.data()))
-}
-
fn get_meta_items(md: ebml::Doc) -> Vec<@ast::MetaItem> {
let mut items: Vec<@ast::MetaItem> = Vec::new();
reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
}
pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
- return get_attributes(reader::Doc(data));
+ get_attributes(reader::Doc(data))
}
#[deriving(Clone)]
*/
+#![allow(dead_code)] // still WIP
+
use std::uint;
pub struct Graph<N,E> {
}
#[deriving(Eq)]
- pub struct NodeIndex(uint);
+ pub struct NodeIndex(pub uint);
pub static InvalidNodeIndex: NodeIndex = NodeIndex(uint::MAX);
#[deriving(Eq)]
- pub struct EdgeIndex(uint);
+ pub struct EdgeIndex(pub uint);
pub static InvalidEdgeIndex: EdgeIndex = EdgeIndex(uint::MAX);
// Use a private field here to guarantee no more instances are created:
use syntax::parse::token::InternedString;
use syntax::{ast, ast_map};
use syntax::owned_slice::OwnedSlice;
-use syntax::abi::AbiSet;
+use syntax::abi;
use syntax;
use collections::enum_set::{EnumSet, CLike};
pub fn type_needs_infer(t: t) -> bool {
tbox_has_flag(get(t), needs_infer)
}
-pub fn type_has_regions(t: t) -> bool {
- tbox_has_flag(get(t), has_regions)
-}
pub fn type_id(t: t) -> uint { get(t).id }
#[deriving(Clone, Eq, TotalEq, Hash)]
pub struct BareFnTy {
pub purity: ast::Purity,
- pub abis: AbiSet,
- pub sig: FnSig
+ pub abi: abi::Abi,
+ pub sig: FnSig,
}
#[deriving(Clone, Eq, TotalEq, Hash)]
terr_mismatch,
terr_purity_mismatch(expected_found<Purity>),
terr_onceness_mismatch(expected_found<Onceness>),
- terr_abi_mismatch(expected_found<AbiSet>),
+ terr_abi_mismatch(expected_found<abi::Abi>),
terr_mutability,
terr_sigil_mismatch(expected_found<ast::Sigil>),
terr_box_mutability,
}
#[deriving(Clone, Eq, TotalEq, Hash)]
- pub struct TyVid(uint);
+ pub struct TyVid(pub uint);
#[deriving(Clone, Eq, TotalEq, Hash)]
- pub struct IntVid(uint);
+ pub struct IntVid(pub uint);
#[deriving(Clone, Eq, TotalEq, Hash)]
- pub struct FloatVid(uint);
+ pub struct FloatVid(pub uint);
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct RegionVid {
mk_bare_fn(cx,
BareFnTy {
purity: ast::ImpureFn,
- abis: AbiSet::Rust(),
+ abi: abi::Rust,
sig: FnSig {
binder_id: binder_id,
inputs: input_args,
|t| { fldt(t); t }).fold_ty(ty)
}
-pub fn fold_regions(cx: &ctxt, ty: t, fldr: |r: Region| -> Region) -> t {
- ty_fold::RegionFolder::regions(cx, fldr).fold_ty(ty)
-}
-
// Substitute *only* type parameters. Used in trans where regions are erased.
pub fn subst_tps(tcx: &ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
let mut subst = TpsSubst { tcx: tcx, self_ty_opt: self_ty_opt, tps: tps };
}
}
-pub fn type_is_sequence(ty: t) -> bool {
- match get(ty).sty {
- ty_str(_) | ty_vec(_, _) => true,
- _ => false
- }
-}
-
pub fn type_is_simd(cx: &ctxt, ty: t) -> bool {
match get(ty).sty {
ty_struct(did, _) => lookup_simd(cx, did),
}
}
-pub fn type_is_str(ty: t) -> bool {
- match get(ty).sty {
- ty_str(_) => true,
- _ => false
- }
-}
-
pub fn sequence_element_type(cx: &ctxt, ty: t) -> t {
match get(ty).sty {
ty_str(_) => return mk_mach_uint(ast::TyU8),
}
}
-pub fn get_element_type(ty: t, i: uint) -> t {
- match get(ty).sty {
- ty_tup(ref ts) => return *ts.get(i),
- _ => fail!("get_element_type called on invalid type")
- }
-}
-
-pub fn type_is_box(ty: t) -> bool {
- match get(ty).sty {
- ty_box(_) => return true,
- _ => return false
- }
-}
-
pub fn type_is_boxed(ty: t) -> bool {
match get(ty).sty {
ty_box(_) => true,
}
}
-pub fn type_is_slice(ty: t) -> bool {
- match get(ty).sty {
- ty_vec(_, vstore_slice(_)) | ty_str(vstore_slice(_)) => true,
- _ => return false
- }
-}
-
-pub fn type_is_unique_box(ty: t) -> bool {
- match get(ty).sty {
- ty_uniq(_) => return true,
- _ => return false
- }
-}
-
pub fn type_is_unsafe_ptr(ty: t) -> bool {
match get(ty).sty {
ty_ptr(_) => return true,
}
}
-pub fn type_is_vec(ty: t) -> bool {
- return match get(ty).sty {
- ty_vec(_, _) | ty_unboxed_vec(_) => true,
- ty_str(_) => true,
- _ => false
- };
-}
-
pub fn type_is_unique(ty: t) -> bool {
match get(ty).sty {
ty_uniq(_) | ty_vec(_, vstore_uniq) | ty_str(vstore_uniq) => true,
)
impl TypeContents {
- pub fn meets_bounds(&self, cx: &ctxt, bbs: BuiltinBounds) -> bool {
- bbs.iter().all(|bb| self.meets_bound(cx, bb))
- }
-
pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool {
match bb {
BoundStatic => self.is_static(cx),
v.iter().fold(TC::None, |tc, t| tc | f(t))
}
- pub fn inverse(&self) -> TypeContents {
- TypeContents { bits: !self.bits }
- }
-
pub fn has_dtor(&self) -> bool {
self.intersects(TC::OwnsDtor)
}
}
}
-pub fn type_has_dtor(cx: &ctxt, t: ty::t) -> bool {
- type_contents(cx, t).has_dtor()
-}
-
pub fn type_is_static(cx: &ctxt, t: ty::t) -> bool {
type_contents(cx, t).is_static(cx)
}
}
}
+pub fn type_is_uint(ty: t) -> bool {
+ match get(ty).sty {
+ ty_infer(IntVar(_)) | ty_uint(ast::TyU) => true,
+ _ => false
+ }
+}
+
pub fn type_is_char(ty: t) -> bool {
match get(ty).sty {
ty_char => true,
}
}
-pub fn type_is_enum(ty: t) -> bool {
- match get(ty).sty {
- ty_enum(_, _) => return true,
- _ => return false
- }
-}
-
// Is the type's representation size known at compile time?
+#[allow(dead_code)] // leaving in for DST
pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool {
match get(ty).sty {
// FIXME(#6308) add trait, vec, str, etc here.
}
}
-pub fn type_param(ty: t) -> Option<uint> {
- match get(ty).sty {
- ty_param(p) => return Some(p.idx),
- _ => {/* fall through */ }
- }
- return None;
-}
-
// Returns the type and mutability of *t.
//
// The parameter `explicit` indicates if this is an *explicit* dereference.
}
}
-fn node_id_has_type_params(cx: &ctxt, id: ast::NodeId) -> bool {
- cx.node_type_substs.borrow().contains_key(&id)
-}
-
pub fn fn_is_variadic(fty: t) -> bool {
match get(fty).sty {
ty_bare_fn(ref f) => f.sig.variadic,
}
}
-pub fn ty_fn_purity(fty: t) -> ast::Purity {
- match get(fty).sty {
- ty_bare_fn(ref f) => f.purity,
- ty_closure(ref f) => f.purity,
- ref s => {
- fail!("ty_fn_purity() called on non-fn type: {:?}", s)
- }
- }
-}
-
pub fn ty_fn_ret(fty: t) -> t {
match get(fty).sty {
ty_bare_fn(ref f) => f.sig.output,
}
}
-pub fn ty_vstore(ty: t) -> vstore {
- match get(ty).sty {
- ty_vec(_, vstore) => vstore,
- ty_str(vstore) => vstore,
- ref s => fail!("ty_vstore() called on invalid sty: {:?}", s)
- }
-}
-
pub fn ty_region(tcx: &ctxt,
span: Span,
ty: t) -> Region {
}
}
-pub fn replace_fn_sig(cx: &ctxt, fsty: &sty, new_sig: FnSig) -> t {
- match *fsty {
- ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
- ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..**f}),
- ref s => {
- cx.sess.bug(
- format!("ty_fn_sig() called on non-fn type: {:?}", s));
- }
- }
-}
-
-pub fn replace_closure_return_type(tcx: &ctxt, fn_type: t, ret_type: t) -> t {
- /*!
- *
- * Returns a new function type based on `fn_type` but returning a value of
- * type `ret_type` instead. */
-
- match ty::get(fn_type).sty {
- ty::ty_closure(ref fty) => {
- ty::mk_closure(tcx, ClosureTy {
- sig: FnSig {output: ret_type, ..fty.sig.clone()},
- ..(**fty).clone()
- })
- }
- _ => {
- tcx.sess.bug(format!(
- "replace_fn_ret() invoked with non-fn-type: {}",
- ty_to_str(tcx, fn_type)));
- }
- }
-}
-
-// Returns a vec of all the input and output types of fty.
-pub fn tys_in_fn_sig(sig: &FnSig) -> Vec<t> {
- sig.inputs.iter().map(|a| *a).collect::<Vec<_>>().append_one(sig.output)
-}
-
-// Type accessors for AST nodes
-pub fn block_ty(cx: &ctxt, b: &ast::Block) -> t {
- return node_id_to_type(cx, b.id);
-}
-
-
// Returns the type of a pattern as a monotype. Like @expr_ty, this function
// doesn't provide type parameter substitutions.
pub fn pat_ty(cx: &ctxt, pat: &ast::Pat) -> t {
pub ty: t
}
+#[allow(dead_code)] // this may be useful?
pub fn expr_ty_params_and_ty(cx: &ctxt,
expr: &ast::Expr)
-> ParamsTy {
}
}
-pub fn expr_has_ty_params(cx: &ctxt, expr: &ast::Expr) -> bool {
- return node_id_has_type_params(cx, expr.id);
-}
-
pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin)
-> Rc<Vec<TypeParameterDef>> {
match origin {
}
}
-pub fn field_idx(name: ast::Name, fields: &[field]) -> Option<uint> {
- let mut i = 0u;
- for f in fields.iter() { if f.ident.name == name { return Some(i); } i += 1u; }
- return None;
-}
-
pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
-> uint {
let mut i = 0u;
}
}
-pub fn def_has_ty_params(def: ast::Def) -> bool {
- match def {
- ast::DefFn(_, _) | ast::DefVariant(_, _, _) | ast::DefStruct(_)
- => true,
- _ => false
- }
-}
-
pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
cx.provided_method_sources.borrow().find(&id).map(|x| *x)
}
pub fn ty_to_def_id(ty: t) -> Option<ast::DefId> {
match get(ty).sty {
- ty_trait(~TyTrait { def_id: id, .. }) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
- _ => None
+ ty_trait(~TyTrait { def_id: id, .. }) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
+ _ => None
}
}
}
}
-pub fn lookup_struct_field(cx: &ctxt,
- parent: ast::DefId,
- field_id: ast::DefId)
- -> field_ty {
- let r = lookup_struct_fields(cx, parent);
- match r.iter().find(
- |f| f.id.node == field_id.node) {
- Some(t) => *t,
- None => cx.sess.bug("struct ID not found in parent's fields")
- }
-}
-
fn struct_field_tys(fields: &[StructField]) -> Vec<field_ty> {
fields.iter().map(|field| {
match field.node.kind {
/*bot*/ [t, t, t, t, t, t, t, t],
/*raw ptr*/ [f, f, f, f, t, t, f, f]];
- return tbl[tycat(cx, ty)][opcat(op)];
-}
-
-pub fn ty_params_to_tys(tcx: &ctxt, generics: &ast::Generics) -> Vec<t> {
- Vec::from_fn(generics.ty_params.len(), |i| {
- let id = generics.ty_params.get(i).id;
- ty::mk_param(tcx, i, ast_util::local_def(id))
- })
+ return tbl[tycat(cx, ty) as uint ][opcat(op) as uint];
}
/// Returns an equivalent type with all the typedefs and self regions removed.
return true;
}
-pub fn count_traits_and_supertraits(tcx: &ctxt,
- type_param_defs: &[TypeParameterDef]) -> uint {
- let mut total = 0;
- for type_param_def in type_param_defs.iter() {
- each_bound_trait_and_supertraits(
- tcx, type_param_def.bounds.trait_bounds.as_slice(), |_| {
- total += 1;
- true
- });
- }
- return total;
-}
-
pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, ~str> {
tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
ty_bare_fn(ref b) => {
byte!(14);
hash!(b.purity);
- hash!(b.abis);
+ hash!(b.abi);
}
ty_closure(ref c) => {
byte!(15);
UniqueImmBorrow => "uniquely immutable",
}
}
-
- pub fn to_short_str(&self) -> &'static str {
- match *self {
- MutBorrow => "mut",
- ImmBorrow => "imm",
- UniqueImmBorrow => "own",
- }
- }
}
use middle::typeck::infer::resolve::try_resolve_tvar_shallow;
use util::common::indenter;
+use syntax::abi;
use syntax::ast::MutImmutable;
use syntax::ast;
// Note: Coerce is not actually a combiner, in that it does not
// conform to the same interface, though it performs a similar
// function.
- pub struct Coerce<'f>(CombineFields<'f>);
+ pub struct Coerce<'f>(pub CombineFields<'f>);
impl<'f> Coerce<'f> {
pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> {
debug!("coerce_from_bare_fn(a={}, b={})",
a.inf_str(self.get_ref().infcx), b.inf_str(self.get_ref().infcx));
- if !fn_ty_a.abis.is_rust() || fn_ty_a.purity != ast::ImpureFn {
+ if fn_ty_a.abi != abi::Rust || fn_ty_a.purity != ast::ImpureFn {
return self.subtype(a, b);
}
use syntax::ast::{Onceness, Purity};
use util::ppaux::mt_to_str;
- pub struct Lub<'f>(CombineFields<'f>); // least-upper-bound: common supertype
+ pub struct Lub<'f>(pub CombineFields<'f>); // least-upper-bound: common supertype
impl<'f> Lub<'f> {
pub fn get_ref<'a>(&'a self) -> &'a CombineFields<'f> { let Lub(ref v) = *self; v }
- pub fn bot_ty(&self, b: ty::t) -> cres<ty::t> { Ok(b) }
- pub fn ty_bot(&self, b: ty::t) -> cres<ty::t> {
- self.bot_ty(b) // commutative
- }
}
impl<'f> Combine for Lub<'f> {
}
pub struct GarbageCollector;
- pub struct LocalStorage(Option<local_data::Map>);
+ pub struct LocalStorage(pub Option<local_data::Map>);
/// A handle to a blocked task. Usually this means having the ~Task pointer by
/// ownership, but if the task is killable, a killer can steal it at any time.
#[test]
fn rng() {
use rand::{StdRng, Rng};
- let mut r = StdRng::new();
+ let mut r = StdRng::new().unwrap();
let _ = r.next_u32();
}
// The Rust abstract syntax tree.
use codemap::{Span, Spanned, DUMMY_SP};
-use abi::AbiSet;
+use abi::Abi;
use ast_util;
use owned_slice::OwnedSlice;
use parse::token::{InternedString, special_idents, str_to_ident};
ExprVstore(@Expr, ExprVstore),
// First expr is the place; second expr is the value.
ExprBox(@Expr, @Expr),
- ExprVec(Vec<@Expr> , Mutability),
- ExprCall(@Expr, Vec<@Expr> ),
- ExprMethodCall(Ident, Vec<P<Ty>> , Vec<@Expr> ),
- ExprTup(Vec<@Expr> ),
+ ExprVec(Vec<@Expr>, Mutability),
+ ExprCall(@Expr, Vec<@Expr>),
+ ExprMethodCall(Ident, Vec<P<Ty>>, Vec<@Expr>),
+ ExprTup(Vec<@Expr>),
ExprBinary(BinOp, @Expr, @Expr),
ExprUnary(UnOp, @Expr),
ExprLit(@Lit),
// Conditionless loop (can be exited with break, cont, or ret)
// FIXME #6993: change to Option<Name>
ExprLoop(P<Block>, Option<Ident>),
- ExprMatch(@Expr, Vec<Arm> ),
+ ExprMatch(@Expr, Vec<Arm>),
ExprFnBlock(P<FnDecl>, P<Block>),
ExprProc(P<FnDecl>, P<Block>),
ExprBlock(P<Block>),
ExprAssign(@Expr, @Expr),
ExprAssignOp(BinOp, @Expr, @Expr),
- ExprField(@Expr, Ident, Vec<P<Ty>> ),
+ ExprField(@Expr, Ident, Vec<P<Ty>>),
ExprIndex(@Expr, @Expr),
/// Expression that looks like a "name". For example,
#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct BareFnTy {
pub purity: Purity,
- pub abis: AbiSet,
+ pub abi: Abi,
pub lifetimes: Vec<Lifetime>,
pub decl: P<FnDecl>
}
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct ForeignMod {
- pub abis: AbiSet,
+ pub abi: Abi,
pub view_items: Vec<ViewItem>,
pub items: Vec<@ForeignItem>,
}
#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Item_ {
ItemStatic(P<Ty>, Mutability, @Expr),
- ItemFn(P<FnDecl>, Purity, AbiSet, Generics, P<Block>),
+ ItemFn(P<FnDecl>, Purity, Abi, Generics, P<Block>),
ItemMod(Mod),
ItemForeignMod(ForeignMod),
ItemTy(P<Ty>, Generics),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use abi::AbiSet;
+use abi;
use ast::*;
use ast_util;
use codemap::Span;
// HACK(eddyb) move this into libstd (value wrapper for slice::Items).
#[deriving(Clone)]
- pub struct Values<'a, T>(slice::Items<'a, T>);
+ pub struct Values<'a, T>(pub slice::Items<'a, T>);
impl<'a, T: Copy> Iterator<T> for Values<'a, T> {
fn next(&mut self) -> Option<T> {
}
}
- pub fn get_foreign_abis(&self, id: NodeId) -> AbiSet {
+ pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
let parent = self.get_parent(id);
- let abis = match self.find_entry(parent) {
+ let abi = match self.find_entry(parent) {
Some(EntryItem(_, i)) => match i.node {
- ItemForeignMod(ref nm) => Some(nm.abis),
+ ItemForeignMod(ref nm) => Some(nm.abi),
_ => None
},
// Wrong but OK, because the only inlined foreign items are intrinsics.
- Some(RootInlinedParent(_)) => Some(AbiSet::Intrinsic()),
+ Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
_ => None
};
- match abis {
- Some(abis) => abis,
+ match abi {
+ Some(abi) => abi,
None => fail!("expected foreign mod or inlined parent, found {}",
self.node_to_str(parent))
}