Skip to content

Commit 86718df

Browse files
committed
---
yaml --- r: 81341 b: refs/heads/snap-stage3 c: 0feaccf h: refs/heads/master i: 81339: 69b96a3 v: v3
1 parent 98f245a commit 86718df

File tree

7 files changed

+191
-1
lines changed

7 files changed

+191
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
refs/heads/master: 4c6bf4872012c010f84dc7fa2cdfe87522533f89
33
refs/heads/snap-stage1: e33de59e47c5076a89eadeb38f4934f58a3618a6
4-
refs/heads/snap-stage3: d9d1dfc1955fabb7ee3a55e9c84cdcd5aad67417
4+
refs/heads/snap-stage3: 0feaccf5260bc59f7ee4294a2ecc875da669ad30
55
refs/heads/try: 70152ff55722878cde684ee6462c14c65f2c4729
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b

branches/snap-stage3/doc/rust.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,7 @@ Supported traits for `deriving` are:
17751775
`obj.to_str()` has similar output as `fmt!("%?", obj)`, but it differs in that
17761776
each constituent field of the type must also implement `ToStr` and will have
17771777
`field.to_str()` invoked to build up the result.
1778+
* `FromPrimitive`, to create an instance from a numeric primitve.
17781779

17791780
### Stability
17801781
One can indicate the stability of an API using the following attributes:

branches/snap-stage3/src/libsyntax/ext/build.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ pub trait AstBuilder {
113113
expr: @ast::Expr, ident: ast::Ident,
114114
args: ~[@ast::Expr]) -> @ast::Expr;
115115
fn expr_block(&self, b: ast::Block) -> @ast::Expr;
116+
fn expr_cast(&self, sp: Span, expr: @ast::Expr, ty: ast::Ty) -> @ast::Expr;
116117

117118
fn field_imm(&self, span: Span, name: Ident, e: @ast::Expr) -> ast::Field;
118119
fn expr_struct(&self, span: Span, path: ast::Path, fields: ~[ast::Field]) -> @ast::Expr;
@@ -132,6 +133,9 @@ pub trait AstBuilder {
132133
fn expr_str(&self, sp: Span, s: @str) -> @ast::Expr;
133134
fn expr_str_uniq(&self, sp: Span, s: @str) -> @ast::Expr;
134135

136+
fn expr_some(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr;
137+
fn expr_none(&self, sp: Span) -> @ast::Expr;
138+
135139
fn expr_unreachable(&self, span: Span) -> @ast::Expr;
136140

137141
fn pat(&self, span: Span, pat: ast::Pat_) -> @ast::Pat;
@@ -564,6 +568,29 @@ impl AstBuilder for @ExtCtxt {
564568
}
565569

566570

571+
fn expr_cast(&self, sp: Span, expr: @ast::Expr, ty: ast::Ty) -> @ast::Expr {
572+
self.expr(sp, ast::ExprCast(expr, ty))
573+
}
574+
575+
576+
fn expr_some(&self, sp: Span, expr: @ast::Expr) -> @ast::Expr {
577+
let some = ~[
578+
self.ident_of("std"),
579+
self.ident_of("option"),
580+
self.ident_of("Some"),
581+
];
582+
self.expr_call_global(sp, some, ~[expr])
583+
}
584+
585+
fn expr_none(&self, sp: Span) -> @ast::Expr {
586+
let none = self.path_global(sp, ~[
587+
self.ident_of("std"),
588+
self.ident_of("option"),
589+
self.ident_of("None"),
590+
]);
591+
self.expr_path(none)
592+
}
593+
567594
fn expr_unreachable(&self, span: Span) -> @ast::Expr {
568595
let loc = self.codemap().lookup_char_pos(span.lo);
569596
self.expr_call_global(

branches/snap-stage3/src/libsyntax/ext/deriving/generic.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,6 +1151,7 @@ pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc,
11511151
enum_nonmatch_f,
11521152
cx, span, substructure)
11531153
}
1154+
11541155
/// cs_binop with binop == and
11551156
#[inline]
11561157
pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc,

branches/snap-stage3/src/libsyntax/ext/deriving/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub mod rand;
3232
pub mod to_str;
3333
pub mod zero;
3434
pub mod default;
35+
pub mod primitive;
3536

3637
#[path="cmp/eq.rs"]
3738
pub mod eq;
@@ -97,9 +98,12 @@ pub fn expand_meta_deriving(cx: @ExtCtxt,
9798
"Rand" => expand!(rand::expand_deriving_rand),
9899

99100
"ToStr" => expand!(to_str::expand_deriving_to_str),
101+
100102
"Zero" => expand!(zero::expand_deriving_zero),
101103
"Default" => expand!(default::expand_deriving_default),
102104

105+
"FromPrimitive" => expand!(primitive::expand_deriving_from_primitive),
106+
103107
ref tname => {
104108
cx.span_err(titem.span, format!("unknown \
105109
`deriving` trait: `{}`", *tname));
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use ast::{MetaItem, item, Expr};
12+
use ast;
13+
use codemap::Span;
14+
use ext::base::ExtCtxt;
15+
use ext::build::AstBuilder;
16+
use ext::deriving::generic::*;
17+
18+
pub fn expand_deriving_from_primitive(cx: @ExtCtxt,
19+
span: Span,
20+
mitem: @MetaItem,
21+
in_items: ~[@item]) -> ~[@item] {
22+
let trait_def = TraitDef {
23+
path: Path::new(~["std", "num", "FromPrimitive"]),
24+
additional_bounds: ~[],
25+
generics: LifetimeBounds::empty(),
26+
methods: ~[
27+
MethodDef {
28+
name: "from_int",
29+
generics: LifetimeBounds::empty(),
30+
explicit_self: None,
31+
args: ~[
32+
Literal(Path::new(~["int"])),
33+
],
34+
ret_ty: Literal(Path::new_(~["std", "option", "Option"],
35+
None,
36+
~[~Self],
37+
true)),
38+
const_nonmatching: false,
39+
combine_substructure: |c, s, sub| cs_from("int", c, s, sub),
40+
},
41+
MethodDef {
42+
name: "from_uint",
43+
generics: LifetimeBounds::empty(),
44+
explicit_self: None,
45+
args: ~[
46+
Literal(Path::new(~["uint"])),
47+
],
48+
ret_ty: Literal(Path::new_(~["std", "option", "Option"],
49+
None,
50+
~[~Self],
51+
true)),
52+
const_nonmatching: false,
53+
combine_substructure: |c, s, sub| cs_from("uint", c, s, sub),
54+
},
55+
]
56+
};
57+
58+
trait_def.expand(cx, span, mitem, in_items)
59+
}
60+
61+
fn cs_from(name: &str, cx: @ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
62+
let n = match substr.nonself_args {
63+
[n] => n,
64+
_ => cx.span_bug(span, "Incorrect number of arguments in `deriving(FromPrimitive)`")
65+
};
66+
67+
return match *substr.fields {
68+
StaticEnum(enum_def, _) => {
69+
if enum_def.variants.is_empty() {
70+
cx.span_fatal(span, "`FromPrimitive` cannot be derived for enums with no variants");
71+
}
72+
73+
let mut arms = ~[];
74+
75+
for variant in enum_def.variants.iter() {
76+
match variant.node.kind {
77+
ast::tuple_variant_kind(ref args) => {
78+
if !args.is_empty() {
79+
cx.span_fatal(span, "`FromPrimitive` cannot be derived for \
80+
enum variants with arguments");
81+
}
82+
83+
// expr for `$n == $variant as $name`
84+
let variant = cx.expr_ident(span, variant.node.name);
85+
let ty = cx.ty_ident(span, cx.ident_of(name));
86+
let cast = cx.expr_cast(span, variant, ty);
87+
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
88+
89+
// expr for `Some($variant)`
90+
let body = cx.expr_some(span, variant);
91+
92+
// arm for `_ if $guard => $body`
93+
let arm = ast::Arm {
94+
pats: ~[cx.pat_wild(span)],
95+
guard: Some(guard),
96+
body: cx.block_expr(body),
97+
};
98+
99+
arms.push(arm);
100+
}
101+
ast::struct_variant_kind(_) => {
102+
cx.span_fatal(span, "`FromPrimitive` cannot be derived for enums \
103+
with struct variants");
104+
}
105+
}
106+
}
107+
108+
// arm for `_ => None`
109+
let arm = ast::Arm {
110+
pats: ~[cx.pat_wild(span)],
111+
guard: None,
112+
body: cx.block_expr(cx.expr_none(span)),
113+
};
114+
arms.push(arm);
115+
116+
cx.expr_match(span, n, arms)
117+
}
118+
_ => cx.bug("expected StaticEnum in deriving(FromPrimitive)")
119+
};
120+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use std::num::FromPrimitive;
12+
use std::int;
13+
14+
#[deriving(Eq, FromPrimitive)]
15+
enum A {
16+
Foo = int::max_value,
17+
Bar = 1,
18+
Baz = 3,
19+
Qux,
20+
}
21+
22+
fn main() {
23+
let x: Option<A> = FromPrimitive::from_int(int::max_value);
24+
assert_eq!(x, Some(Foo));
25+
26+
let x: Option<A> = FromPrimitive::from_int(1);
27+
assert_eq!(x, Some(Bar));
28+
29+
let x: Option<A> = FromPrimitive::from_int(3);
30+
assert_eq!(x, Some(Baz));
31+
32+
let x: Option<A> = FromPrimitive::from_int(4);
33+
assert_eq!(x, Some(Qux));
34+
35+
let x: Option<A> = FromPrimitive::from_int(5);
36+
assert_eq!(x, None);
37+
}

0 commit comments

Comments
 (0)