Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rustc: implement a #[no_implicit_prelude] attribute. #7844

Closed
wants to merge 7 commits into from
4 changes: 2 additions & 2 deletions src/libextra/smallintmap.rs
Original file line number Diff line number Diff line change
@@ -161,8 +161,8 @@ impl<V> SmallIntMap<V> {
/// Visit all key-value pairs in reverse order
pub fn each_reverse<'a>(&'a self, it: &fn(uint, &'a V) -> bool) -> bool {
for uint::range_rev(self.v.len(), 0) |i| {
match self.v[i - 1] {
Some(ref elt) => if !it(i - 1, elt) { return false; },
match self.v[i] {
Some(ref elt) => if !it(i, elt) { return false; },
None => ()
}
}
20 changes: 19 additions & 1 deletion src/librustc/front/std_inject.rs
Original file line number Diff line number Diff line change
@@ -32,6 +32,9 @@ pub fn maybe_inject_libstd_ref(sess: Session, crate: @ast::crate)
fn use_std(crate: &ast::crate) -> bool {
!attr::attrs_contains_name(crate.node.attrs, "no_std")
}
fn no_prelude(attrs: &[ast::attribute]) -> bool {
attr::attrs_contains_name(attrs, "no_implicit_prelude")
}

fn inject_libstd_ref(sess: Session, crate: &ast::crate) -> @ast::crate {
fn spanned<T:Copy>(x: T) -> codemap::spanned<T> {
@@ -63,7 +66,12 @@ fn inject_libstd_ref(sess: Session, crate: &ast::crate) -> @ast::crate {
view_items: vis,
../*bad*/copy crate.module
};
new_module = fld.fold_mod(&new_module);

if !no_prelude(crate.attrs) {
// only add `use std::prelude::*;` if there wasn't a
// `#[no_implicit_prelude];` at the crate level.
new_module = fld.fold_mod(&new_module);
}

// FIXME #2543: Bad copy.
let new_crate = ast::crate_ {
@@ -72,6 +80,16 @@ fn inject_libstd_ref(sess: Session, crate: &ast::crate) -> @ast::crate {
};
(new_crate, span)
},
fold_item: |item, fld| {
if !no_prelude(item.attrs) {
// only recur if there wasn't `#[no_implicit_prelude];`
// on this item, i.e. this means that the prelude is not
// implicitly imported though the whole subtree
fold::noop_fold_item(item, fld)
} else {
Some(item)
}
},
fold_mod: |module, fld| {
let n2 = sess.next_node_id();

58 changes: 53 additions & 5 deletions src/librustc/middle/const_eval.rs
Original file line number Diff line number Diff line change
@@ -165,10 +165,58 @@ pub fn classify(e: &expr,
pub fn lookup_const(tcx: ty::ctxt, e: &expr) -> Option<@expr> {
match tcx.def_map.find(&e.id) {
Some(&ast::def_static(def_id, false)) => lookup_const_by_id(tcx, def_id),
Some(&ast::def_variant(enum_def, variant_def)) => lookup_variant_by_id(tcx,
enum_def,
variant_def),
_ => None
}
}

pub fn lookup_variant_by_id(tcx: ty::ctxt,
enum_def: ast::def_id,
variant_def: ast::def_id)
-> Option<@expr> {
fn variant_expr(variants: &[ast::variant], id: ast::node_id) -> Option<@expr> {
for variants.iter().advance |variant| {
if variant.node.id == id {
return variant.node.disr_expr;
}
}
None
}

if ast_util::is_local(enum_def) {
match tcx.items.find(&enum_def.node) {
None => None,
Some(&ast_map::node_item(it, _)) => match it.node {
item_enum(ast::enum_def { variants: ref variants }, _) => {
variant_expr(*variants, variant_def.node)
}
_ => None
},
Some(_) => None
}
} else {
let maps = astencode::Maps {
root_map: @mut HashMap::new(),
method_map: @mut HashMap::new(),
vtable_map: @mut HashMap::new(),
write_guard_map: @mut HashSet::new(),
capture_map: @mut HashMap::new()
};
match csearch::maybe_get_item_ast(tcx, enum_def,
|a, b, c, d| astencode::decode_inlined_item(a, b, maps, /*bar*/ copy c, d)) {
csearch::found(ast::ii_item(item)) => match item.node {
item_enum(ast::enum_def { variants: ref variants }, _) => {
variant_expr(*variants, variant_def.node)
}
_ => None
},
_ => None
}
}
}

pub fn lookup_const_by_id(tcx: ty::ctxt,
def_id: ast::def_id)
-> Option<@expr> {
@@ -237,13 +285,13 @@ pub enum const_val {
}

pub fn eval_const_expr(tcx: middle::ty::ctxt, e: &expr) -> const_val {
match eval_const_expr_partial(tcx, e) {
match eval_const_expr_partial(&tcx, e) {
Ok(r) => r,
Err(s) => tcx.sess.span_fatal(e.span, s)
}
}

pub fn eval_const_expr_partial(tcx: middle::ty::ctxt, e: &expr)
pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &expr)
-> Result<const_val, ~str> {
use middle::ty;
fn fromb(b: bool) -> Result<const_val, ~str> { Ok(const_int(b as i64)) }
@@ -360,7 +408,7 @@ pub fn eval_const_expr_partial(tcx: middle::ty::ctxt, e: &expr)
}
}
expr_cast(base, _) => {
let ety = ty::expr_ty(tcx, e);
let ety = tcx.expr_ty(e);
let base = eval_const_expr_partial(tcx, base);
match /*bad*/copy base {
Err(_) => base,
@@ -390,8 +438,8 @@ pub fn eval_const_expr_partial(tcx: middle::ty::ctxt, e: &expr)
}
}
expr_path(_) => {
match lookup_const(tcx, e) {
Some(actual_e) => eval_const_expr_partial(tcx, actual_e),
match lookup_const(tcx.ty_ctxt(), e) {
Some(actual_e) => eval_const_expr_partial(&tcx.ty_ctxt(), actual_e),
None => Err(~"Non-constant path in constant expr")
}
}
2 changes: 1 addition & 1 deletion src/librustc/middle/kind.rs
Original file line number Diff line number Diff line change
@@ -309,7 +309,7 @@ pub fn check_expr(e: @expr, (cx, v): (Context, visit::vt<Context>)) {
"explicit copy requires a copyable argument");
}
expr_repeat(element, count_expr, _) => {
let count = ty::eval_repeat_count(cx.tcx, count_expr);
let count = ty::eval_repeat_count(&cx.tcx, count_expr);
if count > 1 {
let element_ty = ty::expr_ty(cx.tcx, element);
check_copy(cx, element_ty, element.span,
4 changes: 2 additions & 2 deletions src/librustc/middle/trans/tvec.rs
Original file line number Diff line number Diff line change
@@ -417,7 +417,7 @@ pub fn write_content(bcx: block,
return expr::trans_into(bcx, element, Ignore);
}
SaveIn(lldest) => {
let count = ty::eval_repeat_count(bcx.tcx(), count_expr);
let count = ty::eval_repeat_count(&bcx.tcx(), count_expr);
if count == 0 {
return bcx;
}
@@ -509,7 +509,7 @@ pub fn elements_required(bcx: block, content_expr: &ast::expr) -> uint {
},
ast::expr_vec(ref es, _) => es.len(),
ast::expr_repeat(_, count_expr, _) => {
ty::eval_repeat_count(bcx.tcx(), count_expr)
ty::eval_repeat_count(&bcx.tcx(), count_expr)
}
_ => bcx.tcx().sess.span_bug(content_expr.span,
"Unexpected evec content")
47 changes: 31 additions & 16 deletions src/librustc/middle/ty.rs
Original file line number Diff line number Diff line change
@@ -4230,42 +4230,57 @@ pub fn normalize_ty(cx: ctxt, t: t) -> t {
return t_norm;
}

pub trait ExprTyProvider {
pub fn expr_ty(&self, ex: &ast::expr) -> t;
pub fn ty_ctxt(&self) -> ctxt;
}

impl ExprTyProvider for ctxt {
pub fn expr_ty(&self, ex: &ast::expr) -> t {
expr_ty(*self, ex)
}

pub fn ty_ctxt(&self) -> ctxt {
*self
}
}

// Returns the repeat count for a repeating vector expression.
pub fn eval_repeat_count(tcx: ctxt, count_expr: &ast::expr) -> uint {
pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::expr) -> uint {
match const_eval::eval_const_expr_partial(tcx, count_expr) {
Ok(ref const_val) => match *const_val {
const_eval::const_int(count) => if count < 0 {
tcx.sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found negative integer");
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found negative integer");
return 0;
} else {
return count as uint
},
const_eval::const_uint(count) => return count as uint,
const_eval::const_float(count) => {
tcx.sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found float");
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found float");
return count as uint;
}
const_eval::const_str(_) => {
tcx.sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found string");
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found string");
return 0;
}
const_eval::const_bool(_) => {
tcx.sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found boolean");
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found boolean");
return 0;
}
},
Err(*) => {
tcx.sess.span_err(count_expr.span,
"expected constant integer for repeat count \
but found variable");
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected constant integer for repeat count \
but found variable");
return 0;
}
}
2 changes: 1 addition & 1 deletion src/librustc/middle/typeck/astconv.rs
Original file line number Diff line number Diff line change
@@ -479,7 +479,7 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + 'static>(
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
match const_eval::eval_const_expr_partial(&tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
20 changes: 15 additions & 5 deletions src/librustc/middle/typeck/check/mod.rs
Original file line number Diff line number Diff line change
@@ -83,7 +83,7 @@ use middle::pat_util;
use middle::lint::unreachable_code;
use middle::ty::{FnSig, VariantInfo_};
use middle::ty::{ty_param_bounds_and_ty, ty_param_substs_and_ty};
use middle::ty::{substs, param_ty};
use middle::ty::{substs, param_ty, ExprTyProvider};
use middle::ty;
use middle::typeck::astconv::AstConv;
use middle::typeck::astconv::{ast_region_to_region, ast_ty_to_ty};
@@ -290,6 +290,16 @@ pub fn blank_fn_ctxt(ccx: @mut CrateCtxt,
}
}

impl ExprTyProvider for FnCtxt {
pub fn expr_ty(&self, ex: &ast::expr) -> ty::t {
self.expr_ty(ex)
}

pub fn ty_ctxt(&self) -> ty::ctxt {
self.ccx.tcx
}
}

pub fn check_item_types(ccx: @mut CrateCtxt, crate: &ast::crate) {
let visit = visit::mk_simple_visitor(@visit::SimpleVisitor {
visit_item: |a| check_item(ccx, a),
@@ -797,7 +807,7 @@ impl FnCtxt {
pat.repr(self.tcx())
}

pub fn expr_ty(&self, ex: @ast::expr) -> ty::t {
pub fn expr_ty(&self, ex: &ast::expr) -> ty::t {
match self.inh.node_types.find(&ex.id) {
Some(&t) => t,
None => {
@@ -2250,8 +2260,8 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt,
}
}
ast::expr_repeat(element, count_expr, mutbl) => {
let _ = ty::eval_repeat_count(tcx, count_expr);
check_expr_with_hint(fcx, count_expr, ty::mk_uint());
let _ = ty::eval_repeat_count(fcx, count_expr);
let tt = ast_expr_vstore_to_vstore(fcx, ev, vst);
let mutability = match vst {
ast::expr_vstore_mut_box | ast::expr_vstore_mut_slice => {
@@ -2730,8 +2740,8 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt,
fcx.write_ty(id, typ);
}
ast::expr_repeat(element, count_expr, mutbl) => {
let count = ty::eval_repeat_count(tcx, count_expr);
check_expr_with_hint(fcx, count_expr, ty::mk_uint());
let count = ty::eval_repeat_count(fcx, count_expr);
let t: ty::t = fcx.infcx().next_ty_var();
check_expr_has_type(fcx, element, t);
let element_ty = fcx.expr_ty(element);
@@ -3126,7 +3136,7 @@ pub fn check_enum_variants(ccx: @mut CrateCtxt,
// that the expression is in an form that eval_const_expr can
// handle, so we may still get an internal compiler error

match const_eval::eval_const_expr_partial(ccx.tcx, e) {
match const_eval::eval_const_expr_partial(&ccx.tcx, e) {
Ok(const_eval::const_int(val)) => {
*disr_val = val as int;
}
95 changes: 76 additions & 19 deletions src/libstd/num/int_macros.rs
Original file line number Diff line number Diff line change
@@ -29,28 +29,38 @@ pub static bytes : uint = ($bits / 8);
pub static min_value: $T = (-1 as $T) << (bits - 1);
pub static max_value: $T = min_value - 1 as $T;

enum Range { Closed, HalfOpen }

#[inline]
///
/// Iterate over the range [`lo`..`hi`)
/// Iterate through a range with a given step value.
///
/// # Arguments
/// Let `term` denote the closed interval `[stop-step,stop]` if `r` is Closed;
/// otherwise `term` denotes the half-open interval `[stop-step,stop)`.
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// `x_j == start + step*j`, and `x_n` lies in the interval `term`.
///
/// * `lo` - lower bound, inclusive
/// * `hi` - higher bound, exclusive
///
/// # Examples
/// ~~~
/// let mut sum = 0;
/// for int::range(1, 5) |i| {
/// sum += i;
/// }
/// assert!(sum == 10);
/// ~~~
/// If no such nonnegative integer `n` exists, then the iteration range
/// is empty.
///
#[inline]
pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool {
fn range_step_core(start: $T, stop: $T, step: $T, r: Range, it: &fn($T) -> bool) -> bool {
let mut i = start;
if step == 0 {
fail!(~"range_step called with step == 0");
} else if step == (1 as $T) { // elide bounds check to tighten loop
while i < stop {
if !it(i) { return false; }
// no need for overflow check;
// cannot have i + 1 > max_value because i < stop <= max_value
i += (1 as $T);
}
} else if step == (-1 as $T) { // elide bounds check to tighten loop
while i > stop {
if !it(i) { return false; }
// no need for underflow check;
// cannot have i - 1 < min_value because i > stop >= min_value
i -= (1 as $T);
}
} else if step > 0 { // ascending
while i < stop {
if !it(i) { return false; }
@@ -66,19 +76,66 @@ pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool {
i += step;
}
}
return true;
match r {
HalfOpen => return true,
Closed => return (i != stop || it(i))
}
}
#[inline]
///
/// Iterate through the range [`start`..`stop`) with a given step value.
///
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// * `x_i == start + step*i`, and
/// * `n` is the greatest nonnegative integer such that `x_n < stop`
///
/// (If no such `n` exists, then the iteration range is empty.)
///
/// # Arguments
///
/// * `start` - lower bound, inclusive
/// * `stop` - higher bound, exclusive
///
/// # Examples
/// ~~~
/// let mut sum = 0;
/// for int::range(1, 5) |i| {
/// sum += i;
/// }
/// assert!(sum == 10);
/// ~~~
///
pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool {
range_step_core(start, stop, step, HalfOpen, it)
}
#[inline]
///
/// Iterate through a range with a given step value.
///
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// `x_i == start + step*i` and `x_n <= last < step + x_n`.
///
/// (If no such nonnegative integer `n` exists, then the iteration
/// range is empty.)
///
pub fn range_step_inclusive(start: $T, last: $T, step: $T, it: &fn($T) -> bool) -> bool {
range_step_core(start, last, step, Closed, it)
}
#[inline]
/// Iterate over the range [`lo`..`hi`)
pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool {
range_step(lo, hi, 1 as $T, it)
}
#[inline]
/// Iterate over the range [`hi`..`lo`)
/// Iterate over the range (`hi`..`lo`]
pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool {
range_step(hi, lo, -1 as $T, it)
if hi == min_value { return true; }
range_step_inclusive(hi-1, lo, -1 as $T, it)
}
impl Num for $T {}
@@ -841,7 +898,7 @@ mod tests {
for range(0,3) |i| {
l.push(i);
}
for range_rev(13,10) |i| {
for range_rev(14,11) |i| {
l.push(i);
}
for range_step(20,26,2) |i| {
100 changes: 80 additions & 20 deletions src/libstd/num/uint_macros.rs
Original file line number Diff line number Diff line change
@@ -30,40 +30,99 @@ pub static bytes : uint = ($bits / 8);
pub static min_value: $T = 0 as $T;
pub static max_value: $T = 0 as $T - 1 as $T;

enum Range { Closed, HalfOpen }

#[inline]
/**
* Iterate through a range with a given step value.
*
* # Examples
* ~~~ {.rust}
* let nums = [1,2,3,4,5,6,7];
*
* for uint::range_step(0, nums.len() - 1, 2) |i| {
* println(fmt!("%d & %d", nums[i], nums[i+1]));
* }
* ~~~
*/
pub fn range_step(start: $T, stop: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool {
///
/// Iterate through a range with a given step value.
///
/// Let `term` denote the closed interval `[stop-step,stop]` if `r` is Closed;
/// otherwise `term` denotes the half-open interval `[stop-step,stop)`.
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// `x_j == start + step*j`, and `x_n` lies in the interval `term`.
///
/// If no such nonnegative integer `n` exists, then the iteration range
/// is empty.
///
fn range_step_core(start: $T, stop: $T, step: $T_SIGNED, r: Range, it: &fn($T) -> bool) -> bool {
let mut i = start;
if step == 0 {
fail!("range_step called with step == 0");
}
if step >= 0 {
} else if step == (1 as $T_SIGNED) { // elide bounds check to tighten loop
while i < stop {
if !it(i) { return false; }
// no need for overflow check;
// cannot have i + 1 > max_value because i < stop <= max_value
i += (1 as $T);
}
} else if step == (-1 as $T_SIGNED) { // elide bounds check to tighten loop
while i > stop {
if !it(i) { return false; }
// no need for underflow check;
// cannot have i - 1 < min_value because i > stop >= min_value
i -= (1 as $T);
}
} else if step > 0 { // ascending
while i < stop {
if !it(i) { return false; }
// avoiding overflow. break if i + step > max_value
if i > max_value - (step as $T) { return true; }
i += step as $T;
}
} else {
} else { // descending
while i > stop {
if !it(i) { return false; }
// avoiding underflow. break if i + step < min_value
if i < min_value + ((-step) as $T) { return true; }
i -= -step as $T;
}
}
return true;
match r {
HalfOpen => return true,
Closed => return (i != stop || it(i))
}
}

#[inline]
///
/// Iterate through the range [`start`..`stop`) with a given step value.
///
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// - `x_i == start + step*i`, and
/// - `n` is the greatest nonnegative integer such that `x_n < stop`
///
/// (If no such `n` exists, then the iteration range is empty.)
///
/// # Arguments
///
/// * `start` - lower bound, inclusive
/// * `stop` - higher bound, exclusive
///
/// # Examples
/// ~~~ {.rust}
/// let nums = [1,2,3,4,5,6,7];
///
/// for uint::range_step(0, nums.len() - 1, 2) |i| {
/// println(fmt!("%d & %d", nums[i], nums[i+1]));
/// }
/// ~~~
///
pub fn range_step(start: $T, stop: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool {
range_step_core(start, stop, step, HalfOpen, it)
}

#[inline]
///
/// Iterate through a range with a given step value.
///
/// Iterates through the range `[x_0, x_1, ..., x_n]` where
/// `x_i == start + step*i` and `x_n <= last < step + x_n`.
///
/// (If no such nonnegative integer `n` exists, then the iteration
/// range is empty.)
///
pub fn range_step_inclusive(start: $T, last: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool {
range_step_core(start, last, step, Closed, it)
}

#[inline]
@@ -73,9 +132,10 @@ pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool {
}

#[inline]
/// Iterate over the range [`hi`..`lo`)
/// Iterate over the range (`hi`..`lo`]
pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool {
range_step(hi, lo, -1 as $T_SIGNED, it)
if hi == min_value { return true; }
range_step_inclusive(hi-1, lo, -1 as $T_SIGNED, it)
}

impl Num for $T {}
@@ -603,7 +663,7 @@ mod tests {
for range(0,3) |i| {
l.push(i);
}
for range_rev(13,10) |i| {
for range_rev(14,11) |i| {
l.push(i);
}
for range_step(20,26,2) |i| {
2 changes: 1 addition & 1 deletion src/libstd/run.rs
Original file line number Diff line number Diff line change
@@ -669,7 +669,7 @@ fn spawn_process_os(prog: &str, args: &[~str],
fail!("failure in dup3(err_fd, 2): %s", os::last_os_error());
}
// close all other fds
for int::range_rev(getdtablesize() as int - 1, 2) |fd| {
for int::range_rev(getdtablesize() as int, 3) |fd| {
close(fd as c_int);
}

6 changes: 3 additions & 3 deletions src/libstd/trie.rs
Original file line number Diff line number Diff line change
@@ -287,7 +287,7 @@ impl<T> TrieNode<T> {

fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool {
for uint::range_rev(self.children.len(), 0) |idx| {
match self.children[idx - 1] {
match self.children[idx] {
Internal(ref x) => if !x.each_reverse(|i,t| f(i,t)) { return false },
External(k, ref v) => if !f(&k, v) { return false },
Nothing => ()
@@ -488,7 +488,7 @@ mod test_map {
m.insert(x, x / 2);
}

let mut n = uint::max_value - 9999;
let mut n = uint::max_value - 10000;
for m.each |k, v| {
if n == uint::max_value - 5000 { break }
assert!(n < uint::max_value - 5000);
@@ -525,7 +525,7 @@ mod test_map {
m.insert(x, x / 2);
}

let mut n = uint::max_value;
let mut n = uint::max_value - 1;
for m.each_reverse |k, v| {
if n == uint::max_value - 5000 { break }
assert!(n > uint::max_value - 5000);
68 changes: 68 additions & 0 deletions src/test/compile-fail/no-implicit-prelude-nested.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that things from the prelude aren't in scope. Use many of them
// so that renaming some things won't magically make this test fail
// for the wrong reason (e.g. if `Add` changes to `Addition`, and
// `no_implicit_prelude` stops working, then the `impl Add` will still
// fail with the same error message).

#[no_implicit_prelude]
mod foo {
mod baz {
struct Test;
impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait

fn foo() {
print("foo"); //~ ERROR: unresolved name
println("bar"); //~ ERROR: unresolved name
}
}

struct Test;
impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait

fn foo() {
print("foo"); //~ ERROR: unresolved name
println("bar"); //~ ERROR: unresolved name
}
}

fn qux() {
#[no_implicit_prelude]
mod qux_inner {
struct Test;
impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait

fn foo() {
print("foo"); //~ ERROR: unresolved name
println("bar"); //~ ERROR: unresolved name
}
}
}


fn main() {
// these should work fine
print("foo");
println("bar");
}
29 changes: 29 additions & 0 deletions src/test/compile-fail/no-implicit-prelude.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[no_implicit_prelude];

// Test that things from the prelude aren't in scope. Use many of them
// so that renaming some things won't magically make this test fail
// for the wrong reason (e.g. if `Add` changes to `Addition`, and
// `no_implicit_prelude` stops working, then the `impl Add` will still
// fail with the same error message).

struct Test;
impl Add for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Clone for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Iterator for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl ToStr for Test {} //~ ERROR: attempt to implement a nonexistent trait
impl Writer for Test {} //~ ERROR: attempt to implement a nonexistent trait

fn main() {
print("foo"); //~ ERROR: unresolved name
println("bar"); //~ ERROR: unresolved name
}
24 changes: 24 additions & 0 deletions src/test/run-pass/enum-vec-initializer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

enum Flopsy {
Bunny = 2
}

static BAR:uint = Bunny as uint;
static BAR2:uint = BAR;

fn main() {
let v = [0, .. Bunny as uint];
let v = [0, .. BAR];
let v = [0, .. BAR2];
static BAR3:uint = BAR2;
let v = [0, .. BAR3];
}
114 changes: 114 additions & 0 deletions src/test/run-pass/num-range-rev.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::int;
use std::uint;

fn uint_range(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool {
uint::range(lo, hi, it)
}

fn int_range(lo: int, hi: int, it: &fn(int) -> bool) -> bool {
int::range(lo, hi, it)
}

fn uint_range_rev(hi: uint, lo: uint, it: &fn(uint) -> bool) -> bool {
uint::range_rev(hi, lo, it)
}

fn int_range_rev(hi: int, lo: int, it: &fn(int) -> bool) -> bool {
int::range_rev(hi, lo, it)
}

fn int_range_step(a: int, b: int, step: int, it: &fn(int) -> bool) -> bool {
int::range_step(a, b, step, it)
}

fn uint_range_step(a: uint, b: uint, step: int, it: &fn(uint) -> bool) -> bool {
uint::range_step(a, b, step, it)
}


pub fn main() {
// int and uint have same result for
// Sum{100 > i >= 2} == (Sum{1 <= i <= 99} - 1) == n*(n+1)/2 - 1 for n=99
let mut sum = 0u;
for uint_range_rev(100, 2) |i| {
sum += i;
}
assert_eq!(sum, 4949);

let mut sum = 0i;
for int_range_rev(100, 2) |i| {
sum += i;
}
assert_eq!(sum, 4949);


// elements are visited in correct order
let primes = [2,3,5,7,11];
let mut prod = 1i;
for uint_range_rev(5, 0) |i| {
println(fmt!("uint 4 downto 0: %u", i));
prod *= int::pow(primes[i], i);
}
assert_eq!(prod, 11*11*11*11*7*7*7*5*5*3*1);
let mut prod = 1i;
for int_range_rev(5, 0) |i| {
println(fmt!("int 4 downto 0: %d", i));
prod *= int::pow(primes[i], i as uint);
}
assert_eq!(prod, 11*11*11*11*7*7*7*5*5*3*1);


// range and range_rev are symmetric.
let mut sum_up = 0u;
for uint_range(10, 30) |i| {
sum_up += i;
}
let mut sum_down = 0u;
for uint_range_rev(30, 10) |i| {
sum_down += i;
}
assert_eq!(sum_up, sum_down);

let mut sum_up = 0;
for int_range(-20, 10) |i| {
sum_up += i;
}
let mut sum_down = 0;
for int_range_rev(10, -20) |i| {
sum_down += i;
}
assert_eq!(sum_up, sum_down);


// empty ranges
for int_range_rev(10, 10) |_| {
fail!("range should be empty when start == stop");
}

for uint_range_rev(0, 1) |_| {
fail!("range should be empty when start-1 underflows");
}

// range iterations do not wrap/underflow
let mut uflo_loop_visited = ~[];
for int_range_step(int::min_value+15, int::min_value, -4) |x| {
uflo_loop_visited.push(x - int::min_value);
}
assert_eq!(uflo_loop_visited, ~[15, 11, 7, 3]);

let mut uflo_loop_visited = ~[];
for uint_range_step(uint::min_value+15, uint::min_value, -4) |x| {
uflo_loop_visited.push(x - uint::min_value);
}
assert_eq!(uflo_loop_visited, ~[15, 11, 7, 3]);
}
119 changes: 119 additions & 0 deletions src/test/run-pass/num-range.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::int;
use std::uint;

fn uint_range(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool {
uint::range(lo, hi, it)
}

fn int_range(lo: int, hi: int, it: &fn(int) -> bool) -> bool {
int::range(lo, hi, it)
}

fn int_range_step(a: int, b: int, step: int, it: &fn(int) -> bool) -> bool {
int::range_step(a, b, step, it)
}

fn uint_range_step(a: uint, b: uint, s: int, it: &fn(uint) -> bool) -> bool {
uint::range_step(a, b, s, it)
}

pub fn main() {
println(fmt!("num-range start"));
// int and uint have same result for
// Sum{2 <= i < 100} == (Sum{1 <= i <= 99} - 1) == n*(n+1)/2 - 1 for n=99
let mut sum = 0u;
for uint_range(2, 100) |i| {
sum += i;
}
assert_eq!(sum, 4949);

let mut sum = 0i;
for int_range(2, 100) |i| {
sum += i;
}
assert_eq!(sum, 4949);


// elements are visited in correct order
let primes = [2,3,5,7];
let mut prod = 1i;
for uint_range(0, 4) |i| {
prod *= int::pow(primes[i], i);
}
assert_eq!(prod, 1*3*5*5*7*7*7);
let mut prod = 1i;
for int_range(0, 4) |i| {
prod *= int::pow(primes[i], i as uint);
}
assert_eq!(prod, 1*3*5*5*7*7*7);


// empty ranges
for int_range(10, 10) |_| {
fail!("range should be empty when start == stop");
}

for uint_range(10, 10) |_| {
fail!("range should be empty when start == stop");
}


// range iterations do not wrap/overflow
let mut oflo_loop_visited = ~[];
for uint_range_step(uint::max_value-15, uint::max_value, 4) |x| {
oflo_loop_visited.push(uint::max_value - x);
}
assert_eq!(oflo_loop_visited, ~[15, 11, 7, 3]);

let mut oflo_loop_visited = ~[];
for int_range_step(int::max_value-15, int::max_value, 4) |x| {
oflo_loop_visited.push(int::max_value - x);
}
assert_eq!(oflo_loop_visited, ~[15, 11, 7, 3]);


// range_step never passes nor visits the stop element
for int_range_step(0, 21, 3) |x| {
assert!(x < 21);
}

// range_step_inclusive will never pass stop element, and may skip it.
let mut saw21 = false;
for uint::range_step_inclusive(0, 21, 4) |x| {
assert!(x <= 21);
if x == 21 { saw21 = true; }
}
assert!(!saw21);
let mut saw21 = false;
for int::range_step_inclusive(0, 21, 4) |x| {
assert!(x <= 21);
if x == 21 { saw21 = true; }
}
assert!(!saw21);

// range_step_inclusive will never pass stop element, but may visit it.
let mut saw21 = false;
for uint::range_step_inclusive(0, 21, 3) |x| {
assert!(x <= 21);
println(fmt!("saw: %u", x));
if x == 21 { saw21 = true; }
}
assert!(saw21);
let mut saw21 = false;
for int::range_step_inclusive(0, 21, 3) |x| {
assert!(x <= 21);
if x == 21 { saw21 = true; }
}
assert!(saw21);

}