Skip to content

Commit 2cb6974

Browse files
committed
auto merge of #5640 : dbaupp/rust/syntax-generalise-deriving, r=thestinger
This refactors much of the ast generation required for `deriving` instances into a common interface, so that new instances only need to specify what they do with the actual data, rather than worry about naming function arguments and extracting fields from structs and enum. (This all happens in `generic.rs`. I've tried to make sure it was well commented and explained, since it's a little abstract at points, but I'm sure it's still a little confusing.) It makes instances like the comparison traits and `Clone` short and easy to write. Caveats: - Not surprisingly, this slows the expansion pass (in some cases, dramatically, specifically deriving Ord or TotalOrd on enums with many variants). However, this shouldn't be too concerning, since in a more realistic case (compiling `core.rc`) the time increased by 0.01s, which isn't worth mentioning. And, it possibly slows type checking very slightly (about 2% worst case), but I'm having trouble measuring it (and I don't understand why this would happen). I think this could be resolved by using traits and encoding it all in the type system so that monomorphisation handles everything, but that would probably be a little tricky to arrange nicely, reduce flexibility and make compiling rustc take longer. (Maybe some judicious use of `#[inline(always)]` would help too; I'll have a bit of a play with it.) - The abstraction is not currently powerful enough for: - `IterBytes`: doesn't support arguments of type other than `&Self`. - `Encodable`/`Decodable` (#5090): doesn't support traits with parameters. - `Rand` & `FromStr`; doesn't support static functions and arguments of type other than `&Self`. - `ToStr`: I don't think it supports returning `~str` yet, but I haven't actually tried. (The last 3 are traits that might be nice to have: the derived `ToStr`/`FromStr` could just read/write the same format as `fmt!("%?", x)`, like `Show` and `Read` in Haskell.) I have ideas to resolve all of these, but I feel like it would essentially be a simpler version of the `mt` & `ty_` parts of `ast.rs`, and I'm not sure if the simplification is worth having 2 copies of similar code. Also, makes Ord, TotalOrd and TotalEq derivable (closes #4269, #5588 and #5589), although a snapshot is required before they can be used in the rust repo. If there is anything that is unclear (or incorrect) either here or in the code, I'd like to get it pointed out now, so I can explain/fix it while I'm still intimately familiar with the code.
2 parents 8b74efa + 5c376e5 commit 2cb6974

16 files changed

+1608
-791
lines changed

src/libcore/cmp.rs

+27
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,19 @@ totalord_impl!(i64)
116116
totalord_impl!(int)
117117
totalord_impl!(uint)
118118

119+
/**
120+
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
121+
lexical ordering on a type `(int, int)`.
122+
*/
123+
// used in deriving code in libsyntax
124+
#[inline(always)]
125+
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
126+
match o1 {
127+
Equal => o2,
128+
_ => o1
129+
}
130+
}
131+
119132
/**
120133
* Trait for values that can be compared for a sort-order.
121134
*
@@ -184,6 +197,8 @@ pub fn max<T:Ord>(v1: T, v2: T) -> T {
184197

185198
#[cfg(test)]
186199
mod test {
200+
use super::lexical_ordering;
201+
187202
#[test]
188203
fn test_int_totalord() {
189204
assert_eq!(5.cmp(&10), Less);
@@ -204,4 +219,16 @@ mod test {
204219
assert!(Less < Equal);
205220
assert_eq!(Greater.cmp(&Less), Greater);
206221
}
222+
223+
#[test]
224+
fn test_lexical_ordering() {
225+
fn t(o1: Ordering, o2: Ordering, e: Ordering) {
226+
assert_eq!(lexical_ordering(o1, o2), e);
227+
}
228+
for [Less, Equal, Greater].each |&o| {
229+
t(Less, o, Less);
230+
t(Equal, o, o);
231+
t(Greater, o, Greater);
232+
}
233+
}
207234
}

src/libsyntax/ext/deriving/clone.rs

+65-257
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,36 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
use core::prelude::*;
12-
13-
use ast;
14-
use ast::*;
11+
use ast::{meta_item, item, expr};
12+
use codemap::span;
1513
use ext::base::ext_ctxt;
1614
use ext::build;
17-
use ext::deriving::*;
18-
use codemap::{span, spanned};
19-
use ast_util;
20-
use opt_vec;
15+
use ext::deriving::generic::*;
16+
use core::option::{None,Some};
2117

22-
use core::uint;
2318

2419
pub fn expand_deriving_clone(cx: @ext_ctxt,
2520
span: span,
26-
_: @meta_item,
21+
mitem: @meta_item,
2722
in_items: ~[@item])
2823
-> ~[@item] {
29-
expand_deriving(cx,
30-
span,
31-
in_items,
32-
expand_deriving_clone_struct_def,
33-
expand_deriving_clone_enum_def)
24+
let trait_def = TraitDef {
25+
path: ~[~"core", ~"clone", ~"Clone"],
26+
additional_bounds: ~[],
27+
methods: ~[
28+
MethodDef {
29+
name: ~"clone",
30+
nargs: 0,
31+
output_type: None, // return Self
32+
const_nonmatching: false,
33+
combine_substructure: cs_clone
34+
}
35+
]
36+
};
37+
38+
expand_deriving_generic(cx, span,
39+
mitem, in_items,
40+
&trait_def)
3441
}
3542

3643
pub fn expand_deriving_obsolete(cx: @ext_ctxt,
@@ -42,251 +49,52 @@ pub fn expand_deriving_obsolete(cx: @ext_ctxt,
4249
in_items
4350
}
4451

45-
fn create_derived_clone_impl(cx: @ext_ctxt,
46-
span: span,
47-
type_ident: ident,
48-
generics: &Generics,
49-
method: @method)
50-
-> @item {
51-
let methods = [ method ];
52-
let trait_path = ~[
53-
cx.ident_of(~"core"),
54-
cx.ident_of(~"clone"),
55-
cx.ident_of(~"Clone"),
56-
];
57-
let trait_path = build::mk_raw_path_global(span, trait_path);
58-
create_derived_impl(cx, span, type_ident, generics, methods, trait_path, opt_vec::Empty)
59-
}
60-
// Creates a method from the given expression conforming to the signature of
61-
// the `clone` method.
62-
fn create_clone_method(cx: @ext_ctxt,
63-
span: span,
64-
+type_ident: ast::ident,
65-
generics: &Generics,
66-
expr: @ast::expr)
67-
-> @method {
68-
// Create the type parameters of the return value.
69-
let mut output_ty_params = ~[];
70-
for generics.ty_params.each |ty_param| {
71-
let path = build::mk_ty_path(cx, span, ~[ ty_param.ident ]);
72-
output_ty_params.push(path);
73-
}
74-
75-
// Create the type of the return value.
76-
let output_type_path = build::mk_raw_path_(span,
77-
~[ type_ident ],
78-
output_ty_params);
79-
let output_type = ast::ty_path(output_type_path, cx.next_id());
80-
let output_type = @ast::Ty {
81-
id: cx.next_id(),
82-
node: output_type,
83-
span: span
84-
};
85-
86-
// Create the function declaration.
87-
let fn_decl = build::mk_fn_decl(~[], output_type);
88-
89-
// Create the body block.
90-
let body_block = build::mk_simple_block(cx, span, expr);
91-
92-
// Create the self type and method identifier.
93-
let self_ty = spanned { node: sty_region(None, m_imm), span: span };
94-
let method_ident = cx.ident_of(~"clone");
95-
96-
// Create the method.
97-
@ast::method {
98-
ident: method_ident,
99-
attrs: ~[],
100-
generics: ast_util::empty_generics(),
101-
self_ty: self_ty,
102-
purity: impure_fn,
103-
decl: fn_decl,
104-
body: body_block,
105-
id: cx.next_id(),
106-
span: span,
107-
self_id: cx.next_id(),
108-
vis: public,
52+
fn cs_clone(cx: @ext_ctxt, span: span,
53+
substr: &Substructure) -> @expr {
54+
let clone_ident = substr.method_ident;
55+
let ctor_ident;
56+
let all_fields;
57+
let subcall = |field|
58+
build::mk_method_call(cx, span, field, clone_ident, ~[]);
59+
60+
match *substr.fields {
61+
Struct(af) => {
62+
ctor_ident = ~[ substr.type_ident ];
63+
all_fields = af;
64+
}
65+
EnumMatching(_, variant, af) => {
66+
ctor_ident = ~[ variant.node.name ];
67+
all_fields = af;
68+
},
69+
EnumNonMatching(*) => cx.bug("Non-matching enum variants in `deriving(Clone)`")
10970
}
110-
}
111-
112-
fn call_substructure_clone_method(cx: @ext_ctxt,
113-
span: span,
114-
self_field: @expr)
115-
-> @expr {
116-
// Call the substructure method.
117-
let clone_ident = cx.ident_of(~"clone");
118-
build::mk_method_call(cx, span,
119-
self_field, clone_ident,
120-
~[])
121-
}
122-
123-
fn expand_deriving_clone_struct_def(cx: @ext_ctxt,
124-
span: span,
125-
struct_def: &struct_def,
126-
type_ident: ident,
127-
generics: &Generics)
128-
-> @item {
129-
// Create the method.
130-
let method = if !is_struct_tuple(struct_def) {
131-
expand_deriving_clone_struct_method(cx,
132-
span,
133-
struct_def,
134-
type_ident,
135-
generics)
136-
} else {
137-
expand_deriving_clone_tuple_struct_method(cx,
138-
span,
139-
struct_def,
140-
type_ident,
141-
generics)
142-
};
143-
144-
// Create the implementation.
145-
create_derived_clone_impl(cx, span, type_ident, generics, method)
146-
}
147-
148-
fn expand_deriving_clone_enum_def(cx: @ext_ctxt,
149-
span: span,
150-
enum_definition: &enum_def,
151-
type_ident: ident,
152-
generics: &Generics)
153-
-> @item {
154-
// Create the method.
155-
let method = expand_deriving_clone_enum_method(cx,
156-
span,
157-
enum_definition,
158-
type_ident,
159-
generics);
160-
161-
// Create the implementation.
162-
create_derived_clone_impl(cx, span, type_ident, generics, method)
163-
}
164-
165-
fn expand_deriving_clone_struct_method(cx: @ext_ctxt,
166-
span: span,
167-
struct_def: &struct_def,
168-
type_ident: ident,
169-
generics: &Generics)
170-
-> @method {
171-
let self_ident = cx.ident_of(~"self");
172-
173-
// Create the new fields.
174-
let mut fields = ~[];
175-
for struct_def.fields.each |struct_field| {
176-
match struct_field.node.kind {
177-
named_field(ident, _, _) => {
178-
// Create the accessor for this field.
179-
let self_field = build::mk_access(cx,
180-
span,
181-
~[ self_ident ],
182-
ident);
18371

184-
// Call the substructure method.
185-
let call = call_substructure_clone_method(cx,
186-
span,
187-
self_field);
188-
189-
let field = build::Field { ident: ident, ex: call };
190-
fields.push(field);
191-
}
192-
unnamed_field => {
193-
cx.span_bug(span, ~"unnamed fields in `deriving(Clone)`");
72+
match all_fields {
73+
[(None, _, _), .. _] => {
74+
// enum-like
75+
let subcalls = all_fields.map(|&(_, self_f, _)| subcall(self_f));
76+
build::mk_call(cx, span, ctor_ident, subcalls)
77+
},
78+
_ => {
79+
// struct-like
80+
let fields = do all_fields.map |&(o_id, self_f, _)| {
81+
let ident = match o_id {
82+
Some(i) => i,
83+
None => cx.span_bug(span,
84+
~"unnamed field in normal struct \
85+
in `deriving(Clone)`")
86+
};
87+
build::Field { ident: ident, ex: subcall(self_f) }
88+
};
89+
90+
if fields.is_empty() {
91+
// no fields, so construct like `None`
92+
build::mk_path(cx, span, ctor_ident)
93+
} else {
94+
build::mk_struct_e(cx, span,
95+
ctor_ident,
96+
fields)
19497
}
19598
}
19699
}
197-
198-
// Create the struct literal.
199-
let struct_literal = build::mk_struct_e(cx,
200-
span,
201-
~[ type_ident ],
202-
fields);
203-
create_clone_method(cx, span, type_ident, generics, struct_literal)
204-
}
205-
206-
fn expand_deriving_clone_tuple_struct_method(cx: @ext_ctxt,
207-
span: span,
208-
struct_def: &struct_def,
209-
type_ident: ident,
210-
generics: &Generics)
211-
-> @method {
212-
// Create the pattern for the match.
213-
let matching_path = build::mk_raw_path(span, ~[ type_ident ]);
214-
let field_count = struct_def.fields.len();
215-
let subpats = create_subpatterns(cx, span, ~"__self", field_count);
216-
let pat = build::mk_pat_enum(cx, span, matching_path, subpats);
217-
218-
// Create the new fields.
219-
let mut subcalls = ~[];
220-
for uint::range(0, struct_def.fields.len()) |i| {
221-
// Create the expression for this field.
222-
let field_ident = cx.ident_of(~"__self" + i.to_str());
223-
let field = build::mk_path(cx, span, ~[ field_ident ]);
224-
225-
// Call the substructure method.
226-
let subcall = call_substructure_clone_method(cx, span, field);
227-
subcalls.push(subcall);
228-
}
229-
230-
// Create the call to the struct constructor.
231-
let call = build::mk_call(cx, span, ~[ type_ident ], subcalls);
232-
233-
// Create the pattern body.
234-
let match_body_block = build::mk_simple_block(cx, span, call);
235-
236-
// Create the arm.
237-
let arm = ast::arm {
238-
pats: ~[ pat ],
239-
guard: None,
240-
body: match_body_block
241-
};
242-
243-
// Create the method body.
244-
let self_match_expr = expand_enum_or_struct_match(cx, span, ~[ arm ]);
245-
246-
// Create the method.
247-
create_clone_method(cx, span, type_ident, generics, self_match_expr)
248-
}
249-
250-
fn expand_deriving_clone_enum_method(cx: @ext_ctxt,
251-
span: span,
252-
enum_definition: &enum_def,
253-
type_ident: ident,
254-
generics: &Generics)
255-
-> @method {
256-
// Create the arms of the match in the method body.
257-
let arms = do enum_definition.variants.map |variant| {
258-
// Create the matching pattern.
259-
let pat = create_enum_variant_pattern(cx, span, variant, ~"__self");
260-
261-
// Iterate over the variant arguments, creating the subcalls.
262-
let mut subcalls = ~[];
263-
for uint::range(0, variant_arg_count(cx, span, variant)) |j| {
264-
// Create the expression for this field.
265-
let field_ident = cx.ident_of(~"__self" + j.to_str());
266-
let field = build::mk_path(cx, span, ~[ field_ident ]);
267-
268-
// Call the substructure method.
269-
let subcall = call_substructure_clone_method(cx, span, field);
270-
subcalls.push(subcall);
271-
}
272-
273-
// Create the call to the enum variant (if necessary).
274-
let call = if subcalls.len() > 0 {
275-
build::mk_call(cx, span, ~[ variant.node.name ], subcalls)
276-
} else {
277-
build::mk_path(cx, span, ~[ variant.node.name ])
278-
};
279-
280-
// Create the pattern body.
281-
let match_body_block = build::mk_simple_block(cx, span, call);
282-
283-
// Create the arm.
284-
ast::arm { pats: ~[ pat ], guard: None, body: match_body_block }
285-
};
286-
287-
// Create the method body.
288-
let self_match_expr = expand_enum_or_struct_match(cx, span, arms);
289-
290-
// Create the method.
291-
create_clone_method(cx, span, type_ident, generics, self_match_expr)
292100
}

0 commit comments

Comments
 (0)