auto merge of #9250 : erickt/rust/num, r=erickt

This PR solves one of the pain points with c-style enums. Simplifies writing a fn to convert from an int/uint to an enum. It does this through a `#[deriving(FromPrimitive)]` syntax extension.

Before this is committed though, we need to discuss if `ToPrimitive`/`FromPrimitive` has the right design (cc #4819). I've changed all the `.to_int()` and `from_int()` style functions to return `Option<int>` so we can handle partial functions. For this PR though only enums and `extra::num::bigint::*` take advantage of returning None for unrepresentable values. In the long run it'd be better if `i64.to_i8()` returned `None` if the value was too large, but I'll save this for a future PR.

Closes #3868.
This commit is contained in:
bors 2013-10-05 14:26:44 -07:00
commit 2733b189ac
25 changed files with 1632 additions and 394 deletions

View File

@ -1775,6 +1775,7 @@ Supported traits for `deriving` are:
`obj.to_str()` has similar output as `fmt!("%?", obj)`, but it differs in that
each constituent field of the type must also implement `ToStr` and will have
`field.to_str()` invoked to build up the result.
* `FromPrimitive`, to create an instance from a numeric primitve.
### Stability
One can indicate the stability of an API using the following attributes:

File diff suppressed because it is too large Load Diff

View File

@ -306,7 +306,7 @@ impl<T: FromStrRadix + Clone + Integer + Ord>
mod test {
use super::*;
use std::num::{Zero,One,FromStrRadix,IntConvertible};
use std::num::{Zero,One,FromStrRadix,FromPrimitive};
use std::from_str::FromStr;
pub static _0 : Rational = Ratio { numer: 0, denom: 1};
@ -318,8 +318,8 @@ mod test {
pub fn to_big(n: Rational) -> BigRational {
Ratio::new(
IntConvertible::from_int(n.numer),
IntConvertible::from_int(n.denom)
FromPrimitive::from_int(n.numer).unwrap(),
FromPrimitive::from_int(n.denom).unwrap()
)
}

View File

@ -107,7 +107,7 @@ use std::hashmap::HashMap;
use std::libc::{c_uint, c_ulonglong, c_longlong};
use std::ptr;
use std::vec;
use syntax::codemap::Span;
use syntax::codemap::{Span, Pos};
use syntax::{ast, codemap, ast_util, ast_map, opt_vec, visit};
use syntax::parse::token;
use syntax::parse::token::special_idents;

View File

@ -26,7 +26,7 @@ use middle::ty;
use middle::typeck;
use syntax::abi::AbiSet;
use syntax::ast_map;
use syntax::codemap::Span;
use syntax::codemap::{Span, Pos};
use syntax::parse::token;
use syntax::print::pprust;
use syntax::{ast, ast_util};

View File

@ -590,6 +590,9 @@ impl Primitive for f32 {
#[inline]
fn bytes(_: Option<f32>) -> uint { Primitive::bits(Some(0f32)) / 8 }
#[inline]
fn is_signed(_: Option<f32>) -> bool { true }
}
impl Float for f32 {

View File

@ -638,6 +638,9 @@ impl Primitive for f64 {
#[inline]
fn bytes(_: Option<f64>) -> uint { Primitive::bits(Some(0f64)) / 8 }
#[inline]
fn is_signed(_: Option<f64>) -> bool { true }
}
impl Float for f64 {

View File

@ -380,6 +380,9 @@ impl Primitive for $T {
#[inline]
fn bytes(_: Option<$T>) -> uint { bits / 8 }
#[inline]
fn is_signed(_: Option<$T>) -> bool { true }
}
// String conversion functions and impl str -> num

File diff suppressed because it is too large Load Diff

View File

@ -140,7 +140,7 @@ pub fn int_to_str_bytes_common<T:NumCast+Zero+Eq+Ord+Integer+
let _0: T = Zero::zero();
let neg = num < _0;
let radix_gen: T = cast(radix);
let radix_gen: T = cast(radix).unwrap();
let mut deccum = num;
// This is just for integral types, the largest of which is a u64. The
@ -163,7 +163,7 @@ pub fn int_to_str_bytes_common<T:NumCast+Zero+Eq+Ord+Integer+
} else {
current_digit_signed
};
buf[cur] = match current_digit.to_u8() {
buf[cur] = match current_digit.to_u8().unwrap() {
i @ 0..9 => '0' as u8 + i,
i => 'a' as u8 + (i - 10),
};
@ -247,7 +247,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
let mut buf: ~[u8] = ~[];
let radix_gen: T = cast(radix as int);
let radix_gen: T = cast(radix as int).unwrap();
// First emit the non-fractional part, looping at least once to make
// sure at least a `0` gets emitted.
@ -265,7 +265,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
deccum = deccum / radix_gen;
deccum = deccum.trunc();
buf.push(char::from_digit(current_digit.to_int() as uint, radix)
buf.push(char::from_digit(current_digit.to_int().unwrap() as uint, radix)
.unwrap() as u8);
// No more digits to calculate for the non-fractional part -> break
@ -322,7 +322,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
let current_digit = deccum.trunc().abs();
buf.push(char::from_digit(
current_digit.to_int() as uint, radix).unwrap() as u8);
current_digit.to_int().unwrap() as uint, radix).unwrap() as u8);
// Decrease the deccumulator one fractional digit at a time
deccum = deccum.fract();
@ -492,7 +492,7 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Div<T,T>+
let _0: T = Zero::zero();
let _1: T = One::one();
let radix_gen: T = cast(radix as int);
let radix_gen: T = cast(radix as int).unwrap();
let len = buf.len();
@ -543,9 +543,9 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Div<T,T>+
// add/subtract current digit depending on sign
if accum_positive {
accum = accum + cast(digit as int);
accum = accum + cast(digit as int).unwrap();
} else {
accum = accum - cast(digit as int);
accum = accum - cast(digit as int).unwrap();
}
// Detect overflow by comparing to last value, except
@ -556,11 +556,11 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Div<T,T>+
// Detect overflow by reversing the shift-and-add proccess
if accum_positive &&
(last_accum != ((accum - cast(digit as int))/radix_gen.clone())) {
(last_accum != ((accum - cast(digit as int).unwrap())/radix_gen.clone())) {
return NumStrConv::inf();
}
if !accum_positive &&
(last_accum != ((accum + cast(digit as int))/radix_gen.clone())) {
(last_accum != ((accum + cast(digit as int).unwrap())/radix_gen.clone())) {
return NumStrConv::neg_inf();
}
}
@ -596,7 +596,7 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Div<T,T>+
// Decrease power one order of magnitude
power = power / radix_gen;
let digit_t: T = cast(digit);
let digit_t: T = cast(digit).unwrap();
// add/subtract current digit depending on sign
if accum_positive {
@ -654,9 +654,9 @@ pub fn from_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Div<T,T>+
match exp {
Some(exp_pow) => {
multiplier = if exp_pow < 0 {
_1 / pow_with_uint::<T>(base, (-exp_pow.to_int()) as uint)
_1 / pow_with_uint::<T>(base, (-exp_pow.to_int().unwrap()) as uint)
} else {
pow_with_uint::<T>(base, exp_pow.to_int() as uint)
pow_with_uint::<T>(base, exp_pow.to_int().unwrap() as uint)
}
}
None => return None // invalid exponent -> invalid number

View File

@ -306,6 +306,9 @@ impl Primitive for $T {
#[inline]
fn bytes(_: Option<$T>) -> uint { bits / 8 }
#[inline]
fn is_signed(_: Option<$T>) -> bool { false }
}
impl BitCount for $T {

View File

@ -59,7 +59,7 @@ pub use num::{Orderable, Signed, Unsigned, Round};
pub use num::{Algebraic, Trigonometric, Exponential, Hyperbolic};
pub use num::{Integer, Fractional, Real, RealExt};
pub use num::{Bitwise, BitCount, Bounded};
pub use num::{Primitive, Int, Float, ToStrRadix};
pub use num::{Primitive, Int, Float, ToStrRadix, ToPrimitive, FromPrimitive};
pub use path::GenericPath;
pub use path::Path;
pub use path::PosixPath;

View File

@ -317,12 +317,12 @@ pub trait Rng {
/// ```
fn gen_integer_range<T: Rand + Int>(&mut self, low: T, high: T) -> T {
assert!(low < high, "RNG.gen_integer_range called with low >= high");
let range = (high - low).to_u64();
let range = (high - low).to_u64().unwrap();
let accept_zone = u64::max_value - u64::max_value % range;
loop {
let rand = self.gen::<u64>();
if rand < accept_zone {
return low + NumCast::from(rand % range);
return low + NumCast::from(rand % range).unwrap();
}
}
}

View File

@ -113,6 +113,7 @@ pub trait AstBuilder {
expr: @ast::Expr, ident: ast::Ident,
args: ~[@ast::Expr]) -> @ast::Expr;
fn expr_block(&self, b: ast::Block) -> @ast::Expr;
fn expr_cast(&self, sp: Span, expr: @ast::Expr, ty: ast::Ty) -> @ast::Expr;
fn field_imm(&self, span: Span, name: Ident, e: @ast::Expr) -> ast::Field;
fn expr_struct(&self, span: Span, path: ast::Path, fields: ~[ast::Field]) -> @ast::Expr;
@ -132,6 +133,10 @@ pub trait AstBuilder {
fn expr_str(&self, sp: Span, s: @str) -> @ast::Expr;
fn expr_str_uniq(&self, sp: Span, s: @str) -> @ast::Expr;
fn expr_some(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr;
fn expr_none(&self, sp: Span) -> @ast::Expr;
fn expr_fail(&self, span: Span, msg: @str) -> @ast::Expr;
fn expr_unreachable(&self, span: Span) -> @ast::Expr;
fn pat(&self, span: Span, pat: ast::Pat_) -> @ast::Pat;
@ -564,7 +569,30 @@ impl AstBuilder for @ExtCtxt {
}
fn expr_unreachable(&self, span: Span) -> @ast::Expr {
fn expr_cast(&self, sp: Span, expr: @ast::Expr, ty: ast::Ty) -> @ast::Expr {
self.expr(sp, ast::ExprCast(expr, ty))
}
fn expr_some(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr {
let some = ~[
self.ident_of("std"),
self.ident_of("option"),
self.ident_of("Some"),
];
self.expr_call_global(sp, some, ~[expr])
}
fn expr_none(&self, sp: Span) -> @ast::Expr {
let none = self.path_global(sp, ~[
self.ident_of("std"),
self.ident_of("option"),
self.ident_of("None"),
]);
self.expr_path(none)
}
fn expr_fail(&self, span: Span, msg: @str) -> @ast::Expr {
let loc = self.codemap().lookup_char_pos(span.lo);
self.expr_call_global(
span,
@ -575,12 +603,16 @@ impl AstBuilder for @ExtCtxt {
self.ident_of("fail_with"),
],
~[
self.expr_str(span, @"internal error: entered unreachable code"),
self.expr_str(span, msg),
self.expr_str(span, loc.file.name),
self.expr_uint(span, loc.line),
])
}
fn expr_unreachable(&self, span: Span) -> @ast::Expr {
self.expr_fail(span, @"internal error: entered unreachable code")
}
fn pat(&self, span: Span, pat: ast::Pat_) -> @ast::Pat {
@ast::Pat { id: ast::DUMMY_NODE_ID, node: pat, span: span }

View File

@ -1151,6 +1151,7 @@ pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc,
enum_nonmatch_f,
cx, span, substructure)
}
/// cs_binop with binop == and
#[inline]
pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc,

View File

@ -32,6 +32,7 @@ pub mod rand;
pub mod to_str;
pub mod zero;
pub mod default;
pub mod primitive;
#[path="cmp/eq.rs"]
pub mod eq;
@ -97,9 +98,12 @@ pub fn expand_meta_deriving(cx: @ExtCtxt,
"Rand" => expand!(rand::expand_deriving_rand),
"ToStr" => expand!(to_str::expand_deriving_to_str),
"Zero" => expand!(zero::expand_deriving_zero),
"Default" => expand!(default::expand_deriving_default),
"FromPrimitive" => expand!(primitive::expand_deriving_from_primitive),
ref tname => {
cx.span_err(titem.span, format!("unknown \
`deriving` trait: `{}`", *tname));

View File

@ -0,0 +1,127 @@
// Copyright 2012-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 ast::{MetaItem, item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_from_primitive(cx: @ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@item]) -> ~[@item] {
let trait_def = TraitDef {
path: Path::new(~["std", "num", "FromPrimitive"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: ~[
Literal(Path::new(~["i64"])),
],
ret_ty: Literal(Path::new_(~["std", "option", "Option"],
None,
~[~Self],
true)),
const_nonmatching: false,
combine_substructure: |c, s, sub| cs_from("i64", c, s, sub),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: ~[
Literal(Path::new(~["u64"])),
],
ret_ty: Literal(Path::new_(~["std", "option", "Option"],
None,
~[~Self],
true)),
const_nonmatching: false,
combine_substructure: |c, s, sub| cs_from("u64", c, s, sub),
},
]
};
trait_def.expand(cx, span, mitem, in_items)
}
fn cs_from(name: &str, cx: @ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(span, "Incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(*) => {
cx.span_err(span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(span, @"");
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(span, "`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(span, @"");
}
let mut arms = ~[];
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::tuple_variant_kind(ref args) => {
if !args.is_empty() {
cx.span_err(span, "`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(span, @"");
}
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
pats: ~[cx.pat_wild(span)],
guard: Some(guard),
body: cx.block_expr(body),
};
arms.push(arm);
}
ast::struct_variant_kind(_) => {
cx.span_err(span, "`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(span, @"");
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
pats: ~[cx.pat_wild(span)],
guard: None,
body: cx.block_expr(cx.expr_none(span)),
};
arms.push(arm);
cx.expr_match(span, n, arms)
}
_ => cx.bug("expected StaticEnum in deriving(FromPrimitive)")
}
}

View File

@ -0,0 +1,34 @@
// 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::num::FromPrimitive;
use std::int;
#[deriving(FromPrimitive)]
struct A { x: int }
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ ERROR `FromPrimitive` cannot be derived for structs
#[deriving(FromPrimitive)]
struct B(int);
//~^^ ERROR `FromPrimitive` cannot be derived for structs
//~^^^ ERROR `FromPrimitive` cannot be derived for structs
#[deriving(FromPrimitive)]
enum C { Foo(int), Bar(uint) }
//~^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments
//~^^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments
#[deriving(FromPrimitive)]
enum D { Baz { x: int } }
//~^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants
//~^^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants
pub fn main() {}

View File

@ -0,0 +1,37 @@
// 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::num::FromPrimitive;
use std::int;
#[deriving(Eq, FromPrimitive)]
enum A {
Foo = int::max_value,
Bar = 1,
Baz = 3,
Qux,
}
pub fn main() {
let x: Option<A> = FromPrimitive::from_int(int::max_value);
assert_eq!(x, Some(Foo));
let x: Option<A> = FromPrimitive::from_int(1);
assert_eq!(x, Some(Bar));
let x: Option<A> = FromPrimitive::from_int(3);
assert_eq!(x, Some(Baz));
let x: Option<A> = FromPrimitive::from_int(4);
assert_eq!(x, Some(Qux));
let x: Option<A> = FromPrimitive::from_int(5);
assert_eq!(x, None);
}

View File

@ -36,6 +36,6 @@ pub fn main() {
// floats
// num
assert_eq!(10f32.to_int(), 10);
assert_eq!(10f64.to_int(), 10);
assert_eq!(10f32.to_int().unwrap(), 10);
assert_eq!(10f64.to_int().unwrap(), 10);
}

View File

@ -19,7 +19,7 @@ pub trait NumExt: Num + NumCast + Eq + Ord {}
pub trait FloatExt: NumExt + ApproxEq<Self> {}
fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1) }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1) }
fn greater_than_one<T:NumExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
fn greater_than_one_float<T:FloatExt>(n: &T) -> bool { *n > NumCast::from(1).unwrap() }
pub fn main() {}

View File

@ -22,7 +22,7 @@ trait Num {
pub trait NumExt: Num + NumCast { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
n.gt(&NumCast::from(1))
n.gt(&NumCast::from(1).unwrap())
}
pub fn main() {}

View File

@ -14,7 +14,7 @@ use std::num::NumCast;
pub trait NumExt: Num + NumCast + Ord { }
fn greater_than_one<T:NumExt>(n: &T) -> bool {
*n > NumCast::from(1)
*n > NumCast::from(1).unwrap()
}
pub fn main() {}

View File

@ -16,7 +16,7 @@ pub trait NumExt: Eq + Ord + Num + NumCast {}
impl NumExt for f32 {}
fn num_eq_one<T:NumExt>(n: T) {
println!("{}", n == NumCast::from(1))
println!("{}", n == NumCast::from(1).unwrap())
}
pub fn main() {

View File

@ -17,7 +17,7 @@ impl NumExt for f32 {}
impl NumExt for int {}
fn num_eq_one<T:NumExt>() -> T {
NumCast::from(1)
NumCast::from(1).unwrap()
}
pub fn main() {