]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/generic/mod.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[rust.git] / src / libsyntax / ext / deriving / generic / mod.rs
1 // Copyright 2013-2014 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 //! Some code that abstracts away much of the boilerplate of writing
12 //! `derive` instances for traits. Among other things it manages getting
13 //! access to the fields of the 4 different sorts of structs and enum
14 //! variants, as well as creating the method and impl ast instances.
15 //!
16 //! Supported features (fairly exhaustive):
17 //!
18 //! - Methods taking any number of parameters of any type, and returning
19 //!   any type, other than vectors, bottom and closures.
20 //! - Generating `impl`s for types with type parameters and lifetimes
21 //!   (e.g. `Option<T>`), the parameters are automatically given the
22 //!   current trait as a bound. (This includes separate type parameters
23 //!   and lifetimes for methods.)
24 //! - Additional bounds on the type parameters (`TraitDef.additional_bounds`)
25 //!
26 //! The most important thing for implementers is the `Substructure` and
27 //! `SubstructureFields` objects. The latter groups 5 possibilities of the
28 //! arguments:
29 //!
30 //! - `Struct`, when `Self` is a struct (including tuple structs, e.g
31 //!   `struct T(i32, char)`).
32 //! - `EnumMatching`, when `Self` is an enum and all the arguments are the
33 //!   same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`)
34 //! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments
35 //!   are not the same variant (e.g. `None`, `Some(1)` and `None`).
36 //! - `StaticEnum` and `StaticStruct` for static methods, where the type
37 //!   being derived upon is either an enum or struct respectively. (Any
38 //!   argument with type Self is just grouped among the non-self
39 //!   arguments.)
40 //!
41 //! In the first two cases, the values from the corresponding fields in
42 //! all the arguments are grouped together. For `EnumNonMatchingCollapsed`
43 //! this isn't possible (different variants have different fields), so the
44 //! fields are inaccessible. (Previous versions of the deriving infrastructure
45 //! had a way to expand into code that could access them, at the cost of
46 //! generating exponential amounts of code; see issue #15375). There are no
47 //! fields with values in the static cases, so these are treated entirely
48 //! differently.
49 //!
50 //! The non-static cases have `Option<ident>` in several places associated
51 //! with field `expr`s. This represents the name of the field it is
52 //! associated with. It is only not `None` when the associated field has
53 //! an identifier in the source code. For example, the `x`s in the
54 //! following snippet
55 //!
56 //! ```rust
57 //! struct A { x : i32 }
58 //!
59 //! struct B(i32);
60 //!
61 //! enum C {
62 //!     C0(i32),
63 //!     C1 { x: i32 }
64 //! }
65 //! ```
66 //!
67 //! The `i32`s in `B` and `C0` don't have an identifier, so the
68 //! `Option<ident>`s would be `None` for them.
69 //!
70 //! In the static cases, the structure is summarised, either into the just
71 //! spans of the fields or a list of spans and the field idents (for tuple
72 //! structs and record structs, respectively), or a list of these, for
73 //! enums (one for each variant). For empty struct and empty enum
74 //! variants, it is represented as a count of 0.
75 //!
76 //! # "`cs`" functions
77 //!
78 //! The `cs_...` functions ("combine substructure) are designed to
79 //! make life easier by providing some pre-made recipes for common
80 //! tasks; mostly calling the function being derived on all the
81 //! arguments and then combining them back together in some way (or
82 //! letting the user chose that). They are not meant to be the only
83 //! way to handle the structures that this code creates.
84 //!
85 //! # Examples
86 //!
87 //! The following simplified `PartialEq` is used for in-code examples:
88 //!
89 //! ```rust
90 //! trait PartialEq {
91 //!     fn eq(&self, other: &Self);
92 //! }
93 //! impl PartialEq for i32 {
94 //!     fn eq(&self, other: &i32) -> bool {
95 //!         *self == *other
96 //!     }
97 //! }
98 //! ```
99 //!
100 //! Some examples of the values of `SubstructureFields` follow, using the
101 //! above `PartialEq`, `A`, `B` and `C`.
102 //!
103 //! ## Structs
104 //!
105 //! When generating the `expr` for the `A` impl, the `SubstructureFields` is
106 //!
107 //! ```{.text}
108 //! Struct(vec![FieldInfo {
109 //!            span: <span of x>
110 //!            name: Some(<ident of x>),
111 //!            self_: <expr for &self.x>,
112 //!            other: vec![<expr for &other.x]
113 //!          }])
114 //! ```
115 //!
116 //! For the `B` impl, called with `B(a)` and `B(b)`,
117 //!
118 //! ```{.text}
119 //! Struct(vec![FieldInfo {
120 //!           span: <span of `i32`>,
121 //!           name: None,
122 //!           self_: <expr for &a>
123 //!           other: vec![<expr for &b>]
124 //!          }])
125 //! ```
126 //!
127 //! ## Enums
128 //!
129 //! When generating the `expr` for a call with `self == C0(a)` and `other
130 //! == C0(b)`, the SubstructureFields is
131 //!
132 //! ```{.text}
133 //! EnumMatching(0, <ast::Variant for C0>,
134 //!              vec![FieldInfo {
135 //!                 span: <span of i32>
136 //!                 name: None,
137 //!                 self_: <expr for &a>,
138 //!                 other: vec![<expr for &b>]
139 //!               }])
140 //! ```
141 //!
142 //! For `C1 {x}` and `C1 {x}`,
143 //!
144 //! ```{.text}
145 //! EnumMatching(1, <ast::Variant for C1>,
146 //!              vec![FieldInfo {
147 //!                 span: <span of x>
148 //!                 name: Some(<ident of x>),
149 //!                 self_: <expr for &self.x>,
150 //!                 other: vec![<expr for &other.x>]
151 //!                }])
152 //! ```
153 //!
154 //! For `C0(a)` and `C1 {x}` ,
155 //!
156 //! ```{.text}
157 //! EnumNonMatchingCollapsed(
158 //!     vec![<ident of self>, <ident of __arg_1>],
159 //!     &[<ast::Variant for C0>, <ast::Variant for C1>],
160 //!     &[<ident for self index value>, <ident of __arg_1 index value>])
161 //! ```
162 //!
163 //! It is the same for when the arguments are flipped to `C1 {x}` and
164 //! `C0(a)`; the only difference is what the values of the identifiers
165 //! <ident for self index value> and <ident of __arg_1 index value> will
166 //! be in the generated code.
167 //!
168 //! `EnumNonMatchingCollapsed` deliberately provides far less information
169 //! than is generally available for a given pair of variants; see #15375
170 //! for discussion.
171 //!
172 //! ## Static
173 //!
174 //! A static method on the types above would result in,
175 //!
176 //! ```{.text}
177 //! StaticStruct(<ast::StructDef of A>, Named(vec![(<ident of x>, <span of x>)]))
178 //!
179 //! StaticStruct(<ast::StructDef of B>, Unnamed(vec![<span of x>]))
180 //!
181 //! StaticEnum(<ast::EnumDef of C>,
182 //!            vec![(<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])),
183 //!                 (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)]))])
184 //! ```
185
186 pub use self::StaticFields::*;
187 pub use self::SubstructureFields::*;
188 use self::StructType::*;
189
190 use std::cell::RefCell;
191 use std::vec;
192
193 use abi::Abi;
194 use abi;
195 use ast;
196 use ast::{EnumDef, Expr, Ident, Generics, StructDef};
197 use ast_util;
198 use attr;
199 use attr::AttrMetaMethods;
200 use ext::base::ExtCtxt;
201 use ext::build::AstBuilder;
202 use codemap::{self, DUMMY_SP};
203 use codemap::Span;
204 use fold::MoveMap;
205 use owned_slice::OwnedSlice;
206 use parse::token::InternedString;
207 use parse::token::special_idents;
208 use ptr::P;
209
210 use self::ty::{LifetimeBounds, Path, Ptr, PtrTy, Self, Ty};
211
212 pub mod ty;
213
214 pub struct TraitDef<'a> {
215     /// The span for the current #[derive(Foo)] header.
216     pub span: Span,
217
218     pub attributes: Vec<ast::Attribute>,
219
220     /// Path of the trait, including any type parameters
221     pub path: Path<'a>,
222
223     /// Additional bounds required of any type parameters of the type,
224     /// other than the current trait
225     pub additional_bounds: Vec<Ty<'a>>,
226
227     /// Any extra lifetimes and/or bounds, e.g. `D: serialize::Decoder`
228     pub generics: LifetimeBounds<'a>,
229
230     pub methods: Vec<MethodDef<'a>>,
231 }
232
233
234 pub struct MethodDef<'a> {
235     /// name of the method
236     pub name: &'a str,
237     /// List of generics, e.g. `R: rand::Rng`
238     pub generics: LifetimeBounds<'a>,
239
240     /// Whether there is a self argument (outer Option) i.e. whether
241     /// this is a static function, and whether it is a pointer (inner
242     /// Option)
243     pub explicit_self: Option<Option<PtrTy<'a>>>,
244
245     /// Arguments other than the self argument
246     pub args: Vec<Ty<'a>>,
247
248     /// Return type
249     pub ret_ty: Ty<'a>,
250
251     pub attributes: Vec<ast::Attribute>,
252
253     pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
254 }
255
256 /// All the data about the data structure/method being derived upon.
257 pub struct Substructure<'a> {
258     /// ident of self
259     pub type_ident: Ident,
260     /// ident of the method
261     pub method_ident: Ident,
262     /// dereferenced access to any `Self` or `Ptr(Self, _)` arguments
263     pub self_args: &'a [P<Expr>],
264     /// verbatim access to any other arguments
265     pub nonself_args: &'a [P<Expr>],
266     pub fields: &'a SubstructureFields<'a>
267 }
268
269 /// Summary of the relevant parts of a struct/enum field.
270 pub struct FieldInfo {
271     pub span: Span,
272     /// None for tuple structs/normal enum variants, Some for normal
273     /// structs/struct enum variants.
274     pub name: Option<Ident>,
275     /// The expression corresponding to this field of `self`
276     /// (specifically, a reference to it).
277     pub self_: P<Expr>,
278     /// The expressions corresponding to references to this field in
279     /// the other `Self` arguments.
280     pub other: Vec<P<Expr>>,
281 }
282
283 /// Fields for a static method
284 pub enum StaticFields {
285     /// Tuple structs/enum variants like this.
286     Unnamed(Vec<Span>),
287     /// Normal structs/struct variants.
288     Named(Vec<(Ident, Span)>),
289 }
290
291 /// A summary of the possible sets of fields.
292 pub enum SubstructureFields<'a> {
293     Struct(Vec<FieldInfo>),
294     /// Matching variants of the enum: variant index, ast::Variant,
295     /// fields: the field name is only non-`None` in the case of a struct
296     /// variant.
297     EnumMatching(usize, &'a ast::Variant, Vec<FieldInfo>),
298
299     /// Non-matching variants of the enum, but with all state hidden from
300     /// the consequent code.  The first component holds `Ident`s for all of
301     /// the `Self` arguments; the second component is a slice of all of the
302     /// variants for the enum itself, and the third component is a list of
303     /// `Ident`s bound to the variant index values for each of the actual
304     /// input `Self` arguments.
305     EnumNonMatchingCollapsed(Vec<Ident>, &'a [P<ast::Variant>], &'a [Ident]),
306
307     /// A static method where `Self` is a struct.
308     StaticStruct(&'a ast::StructDef, StaticFields),
309     /// A static method where `Self` is an enum.
310     StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
311 }
312
313
314
315 /// Combine the values of all the fields together. The last argument is
316 /// all the fields of all the structures.
317 pub type CombineSubstructureFunc<'a> =
318     Box<FnMut(&mut ExtCtxt, Span, &Substructure) -> P<Expr> + 'a>;
319
320 /// Deal with non-matching enum variants.  The tuple is a list of
321 /// identifiers (one for each `Self` argument, which could be any of the
322 /// variants since they have been collapsed together) and the identifiers
323 /// holding the variant index value for each of the `Self` arguments.  The
324 /// last argument is all the non-`Self` args of the method being derived.
325 pub type EnumNonMatchCollapsedFunc<'a> =
326     Box<FnMut(&mut ExtCtxt, Span, (&[Ident], &[Ident]), &[P<Expr>]) -> P<Expr> + 'a>;
327
328 pub fn combine_substructure<'a>(f: CombineSubstructureFunc<'a>)
329     -> RefCell<CombineSubstructureFunc<'a>> {
330     RefCell::new(f)
331 }
332
333
334 impl<'a> TraitDef<'a> {
335     pub fn expand<F>(&self,
336                      cx: &mut ExtCtxt,
337                      mitem: &ast::MetaItem,
338                      item: &ast::Item,
339                      push: F) where
340         F: FnOnce(P<ast::Item>),
341     {
342         let newitem = match item.node {
343             ast::ItemStruct(ref struct_def, ref generics) => {
344                 self.expand_struct_def(cx,
345                                        &**struct_def,
346                                        item.ident,
347                                        generics)
348             }
349             ast::ItemEnum(ref enum_def, ref generics) => {
350                 self.expand_enum_def(cx,
351                                      enum_def,
352                                      item.ident,
353                                      generics)
354             }
355             _ => {
356                 cx.span_err(mitem.span, "`derive` may only be applied to structs and enums");
357                 return;
358             }
359         };
360         // Keep the lint attributes of the previous item to control how the
361         // generated implementations are linted
362         let mut attrs = newitem.attrs.clone();
363         attrs.extend(item.attrs.iter().filter(|a| {
364             match a.name().get() {
365                 "allow" | "warn" | "deny" | "forbid" => true,
366                 _ => false,
367             }
368         }).map(|a| a.clone()));
369         push(P(ast::Item {
370             attrs: attrs,
371             ..(*newitem).clone()
372         }))
373     }
374
375     /// Given that we are deriving a trait `Tr` for a type `T<'a, ...,
376     /// 'z, A, ..., Z>`, creates an impl like:
377     ///
378     /// ```ignore
379     /// impl<'a, ..., 'z, A:Tr B1 B2, ..., Z: Tr B1 B2> Tr for T<A, ..., Z> { ... }
380     /// ```
381     ///
382     /// where B1, B2, ... are the bounds given by `bounds_paths`.'
383     fn create_derived_impl(&self,
384                            cx: &mut ExtCtxt,
385                            type_ident: Ident,
386                            generics: &Generics,
387                            methods: Vec<P<ast::Method>>) -> P<ast::Item> {
388         let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
389
390         let Generics { mut lifetimes, ty_params, mut where_clause } =
391             self.generics.to_generics(cx, self.span, type_ident, generics);
392         let mut ty_params = ty_params.into_vec();
393
394         // Copy the lifetimes
395         lifetimes.extend(generics.lifetimes.iter().map(|l| (*l).clone()));
396
397         // Create the type parameters.
398         ty_params.extend(generics.ty_params.iter().map(|ty_param| {
399             // I don't think this can be moved out of the loop, since
400             // a TyParamBound requires an ast id
401             let mut bounds: Vec<_> =
402                 // extra restrictions on the generics parameters to the type being derived upon
403                 self.additional_bounds.iter().map(|p| {
404                     cx.typarambound(p.to_path(cx, self.span,
405                                                   type_ident, generics))
406                 }).collect();
407
408             // require the current trait
409             bounds.push(cx.typarambound(trait_path.clone()));
410
411             // also add in any bounds from the declaration
412             for declared_bound in ty_param.bounds.iter() {
413                 bounds.push((*declared_bound).clone());
414             }
415
416             cx.typaram(self.span,
417                        ty_param.ident,
418                        OwnedSlice::from_vec(bounds),
419                        None)
420         }));
421
422         // and similarly for where clauses
423         where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
424             match *clause {
425                 ast::WherePredicate::BoundPredicate(ref wb) => {
426                     ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
427                         span: self.span,
428                         bounded_ty: wb.bounded_ty.clone(),
429                         bounds: OwnedSlice::from_vec(wb.bounds.iter().map(|b| b.clone()).collect())
430                     })
431                 }
432                 ast::WherePredicate::RegionPredicate(ref rb) => {
433                     ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
434                         span: self.span,
435                         lifetime: rb.lifetime,
436                         bounds: rb.bounds.iter().map(|b| b.clone()).collect()
437                     })
438                 }
439                 ast::WherePredicate::EqPredicate(ref we) => {
440                     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
441                         id: ast::DUMMY_NODE_ID,
442                         span: self.span,
443                         path: we.path.clone(),
444                         ty: we.ty.clone()
445                     })
446                 }
447             }
448         }));
449
450         let trait_generics = Generics {
451             lifetimes: lifetimes,
452             ty_params: OwnedSlice::from_vec(ty_params),
453             where_clause: where_clause
454         };
455
456         // Create the reference to the trait.
457         let trait_ref = cx.trait_ref(trait_path);
458
459         // Create the type parameters on the `self` path.
460         let self_ty_params = generics.ty_params.map(|ty_param| {
461             cx.ty_ident(self.span, ty_param.ident)
462         });
463
464         let self_lifetimes: Vec<ast::Lifetime> =
465             generics.lifetimes
466             .iter()
467             .map(|ld| ld.lifetime)
468             .collect();
469
470         // Create the type of `self`.
471         let self_type = cx.ty_path(
472             cx.path_all(self.span, false, vec!( type_ident ), self_lifetimes,
473                         self_ty_params.into_vec(), Vec::new()));
474
475         let attr = cx.attribute(
476             self.span,
477             cx.meta_word(self.span,
478                          InternedString::new("automatically_derived")));
479         // Just mark it now since we know that it'll end up used downstream
480         attr::mark_used(&attr);
481         let opt_trait_ref = Some(trait_ref);
482         let ident = ast_util::impl_pretty_name(&opt_trait_ref, &*self_type);
483         let mut a = vec![attr];
484         a.extend(self.attributes.iter().map(|a| a.clone()));
485         cx.item(
486             self.span,
487             ident,
488             a,
489             ast::ItemImpl(ast::Unsafety::Normal,
490                           ast::ImplPolarity::Positive,
491                           trait_generics,
492                           opt_trait_ref,
493                           self_type,
494                           methods.into_iter()
495                                  .map(|method| {
496                                      ast::MethodImplItem(method)
497                                  }).collect()))
498     }
499
500     fn expand_struct_def(&self,
501                          cx: &mut ExtCtxt,
502                          struct_def: &StructDef,
503                          type_ident: Ident,
504                          generics: &Generics) -> P<ast::Item> {
505         let methods = self.methods.iter().map(|method_def| {
506             let (explicit_self, self_args, nonself_args, tys) =
507                 method_def.split_self_nonself_args(
508                     cx, self, type_ident, generics);
509
510             let body = if method_def.is_static() {
511                 method_def.expand_static_struct_method_body(
512                     cx,
513                     self,
514                     struct_def,
515                     type_ident,
516                     &self_args[],
517                     &nonself_args[])
518             } else {
519                 method_def.expand_struct_method_body(cx,
520                                                      self,
521                                                      struct_def,
522                                                      type_ident,
523                                                      &self_args[],
524                                                      &nonself_args[])
525             };
526
527             method_def.create_method(cx,
528                                      self,
529                                      type_ident,
530                                      generics,
531                                      abi::Rust,
532                                      explicit_self,
533                                      tys,
534                                      body)
535         }).collect();
536
537         self.create_derived_impl(cx, type_ident, generics, methods)
538     }
539
540     fn expand_enum_def(&self,
541                        cx: &mut ExtCtxt,
542                        enum_def: &EnumDef,
543                        type_ident: Ident,
544                        generics: &Generics) -> P<ast::Item> {
545         let methods = self.methods.iter().map(|method_def| {
546             let (explicit_self, self_args, nonself_args, tys) =
547                 method_def.split_self_nonself_args(cx, self,
548                                                    type_ident, generics);
549
550             let body = if method_def.is_static() {
551                 method_def.expand_static_enum_method_body(
552                     cx,
553                     self,
554                     enum_def,
555                     type_ident,
556                     &self_args[],
557                     &nonself_args[])
558             } else {
559                 method_def.expand_enum_method_body(cx,
560                                                    self,
561                                                    enum_def,
562                                                    type_ident,
563                                                    self_args,
564                                                    &nonself_args[])
565             };
566
567             method_def.create_method(cx,
568                                      self,
569                                      type_ident,
570                                      generics,
571                                      abi::Rust,
572                                      explicit_self,
573                                      tys,
574                                      body)
575         }).collect();
576
577         self.create_derived_impl(cx, type_ident, generics, methods)
578     }
579 }
580
581 fn variant_to_pat(cx: &mut ExtCtxt, sp: Span, enum_ident: ast::Ident, variant: &ast::Variant)
582                   -> P<ast::Pat> {
583     let path = cx.path(sp, vec![enum_ident, variant.node.name]);
584     cx.pat(sp, match variant.node.kind {
585         ast::TupleVariantKind(..) => ast::PatEnum(path, None),
586         ast::StructVariantKind(..) => ast::PatStruct(path, Vec::new(), true),
587     })
588 }
589
590 impl<'a> MethodDef<'a> {
591     fn call_substructure_method(&self,
592                                 cx: &mut ExtCtxt,
593                                 trait_: &TraitDef,
594                                 type_ident: Ident,
595                                 self_args: &[P<Expr>],
596                                 nonself_args: &[P<Expr>],
597                                 fields: &SubstructureFields)
598         -> P<Expr> {
599         let substructure = Substructure {
600             type_ident: type_ident,
601             method_ident: cx.ident_of(self.name),
602             self_args: self_args,
603             nonself_args: nonself_args,
604             fields: fields
605         };
606         let mut f = self.combine_substructure.borrow_mut();
607         let f: &mut CombineSubstructureFunc = &mut *f;
608         f(cx, trait_.span, &substructure)
609     }
610
611     fn get_ret_ty(&self,
612                   cx: &mut ExtCtxt,
613                   trait_: &TraitDef,
614                   generics: &Generics,
615                   type_ident: Ident)
616                   -> P<ast::Ty> {
617         self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
618     }
619
620     fn is_static(&self) -> bool {
621         self.explicit_self.is_none()
622     }
623
624     fn split_self_nonself_args(&self,
625                                cx: &mut ExtCtxt,
626                                trait_: &TraitDef,
627                                type_ident: Ident,
628                                generics: &Generics)
629         -> (ast::ExplicitSelf, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) {
630
631         let mut self_args = Vec::new();
632         let mut nonself_args = Vec::new();
633         let mut arg_tys = Vec::new();
634         let mut nonstatic = false;
635
636         let ast_explicit_self = match self.explicit_self {
637             Some(ref self_ptr) => {
638                 let (self_expr, explicit_self) =
639                     ty::get_explicit_self(cx, trait_.span, self_ptr);
640
641                 self_args.push(self_expr);
642                 nonstatic = true;
643
644                 explicit_self
645             }
646             None => codemap::respan(trait_.span, ast::SelfStatic),
647         };
648
649         for (i, ty) in self.args.iter().enumerate() {
650             let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics);
651             let ident = cx.ident_of(&format!("__arg_{}", i)[]);
652             arg_tys.push((ident, ast_ty));
653
654             let arg_expr = cx.expr_ident(trait_.span, ident);
655
656             match *ty {
657                 // for static methods, just treat any Self
658                 // arguments as a normal arg
659                 Self if nonstatic  => {
660                     self_args.push(arg_expr);
661                 }
662                 Ptr(box Self, _) if nonstatic => {
663                     self_args.push(cx.expr_deref(trait_.span, arg_expr))
664                 }
665                 _ => {
666                     nonself_args.push(arg_expr);
667                 }
668             }
669         }
670
671         (ast_explicit_self, self_args, nonself_args, arg_tys)
672     }
673
674     fn create_method(&self,
675                      cx: &mut ExtCtxt,
676                      trait_: &TraitDef,
677                      type_ident: Ident,
678                      generics: &Generics,
679                      abi: Abi,
680                      explicit_self: ast::ExplicitSelf,
681                      arg_types: Vec<(Ident, P<ast::Ty>)> ,
682                      body: P<Expr>) -> P<ast::Method> {
683         // create the generics that aren't for Self
684         let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics);
685
686         let self_arg = match explicit_self.node {
687             ast::SelfStatic => None,
688             // creating fresh self id
689             _ => Some(ast::Arg::new_self(trait_.span, ast::MutImmutable, special_idents::self_))
690         };
691         let args = {
692             let args = arg_types.into_iter().map(|(name, ty)| {
693                     cx.arg(trait_.span, name, ty)
694                 });
695             self_arg.into_iter().chain(args).collect()
696         };
697
698         let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
699
700         let method_ident = cx.ident_of(self.name);
701         let fn_decl = cx.fn_decl(args, ret_type);
702         let body_block = cx.block_expr(body);
703
704         // Create the method.
705         P(ast::Method {
706             attrs: self.attributes.clone(),
707             id: ast::DUMMY_NODE_ID,
708             span: trait_.span,
709             node: ast::MethDecl(method_ident,
710                                 fn_generics,
711                                 abi,
712                                 explicit_self,
713                                 ast::Unsafety::Normal,
714                                 fn_decl,
715                                 body_block,
716                                 ast::Inherited)
717         })
718     }
719
720     /// ```
721     /// #[derive(PartialEq)]
722     /// struct A { x: i32, y: i32 }
723     ///
724     /// // equivalent to:
725     /// impl PartialEq for A {
726     ///     fn eq(&self, __arg_1: &A) -> bool {
727     ///         match *self {
728     ///             A {x: ref __self_0_0, y: ref __self_0_1} => {
729     ///                 match *__arg_1 {
730     ///                     A {x: ref __self_1_0, y: ref __self_1_1} => {
731     ///                         __self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1)
732     ///                     }
733     ///                 }
734     ///             }
735     ///         }
736     ///     }
737     /// }
738     /// ```
739     fn expand_struct_method_body(&self,
740                                  cx: &mut ExtCtxt,
741                                  trait_: &TraitDef,
742                                  struct_def: &StructDef,
743                                  type_ident: Ident,
744                                  self_args: &[P<Expr>],
745                                  nonself_args: &[P<Expr>])
746         -> P<Expr> {
747
748         let mut raw_fields = Vec::new(); // ~[[fields of self],
749                                  // [fields of next Self arg], [etc]]
750         let mut patterns = Vec::new();
751         for i in range(0us, self_args.len()) {
752             let struct_path= cx.path(DUMMY_SP, vec!( type_ident ));
753             let (pat, ident_expr) =
754                 trait_.create_struct_pattern(cx,
755                                              struct_path,
756                                              struct_def,
757                                              &format!("__self_{}",
758                                                      i)[],
759                                              ast::MutImmutable);
760             patterns.push(pat);
761             raw_fields.push(ident_expr);
762         }
763
764         // transpose raw_fields
765         let fields = if raw_fields.len() > 0 {
766             let mut raw_fields = raw_fields.into_iter().map(|v| v.into_iter());
767             let first_field = raw_fields.next().unwrap();
768             let mut other_fields: Vec<vec::IntoIter<(Span, Option<Ident>, P<Expr>)>>
769                 = raw_fields.collect();
770             first_field.map(|(span, opt_id, field)| {
771                 FieldInfo {
772                     span: span,
773                     name: opt_id,
774                     self_: field,
775                     other: other_fields.iter_mut().map(|l| {
776                         match l.next().unwrap() {
777                             (_, _, ex) => ex
778                         }
779                     }).collect()
780                 }
781             }).collect()
782         } else {
783             cx.span_bug(trait_.span,
784                         "no self arguments to non-static method in generic \
785                          `derive`")
786         };
787
788         // body of the inner most destructuring match
789         let mut body = self.call_substructure_method(
790             cx,
791             trait_,
792             type_ident,
793             self_args,
794             nonself_args,
795             &Struct(fields));
796
797         // make a series of nested matches, to destructure the
798         // structs. This is actually right-to-left, but it shouldn't
799         // matter.
800         for (arg_expr, pat) in self_args.iter().zip(patterns.iter()) {
801             body = cx.expr_match(trait_.span, arg_expr.clone(),
802                                      vec!( cx.arm(trait_.span, vec!(pat.clone()), body) ))
803         }
804         body
805     }
806
807     fn expand_static_struct_method_body(&self,
808                                         cx: &mut ExtCtxt,
809                                         trait_: &TraitDef,
810                                         struct_def: &StructDef,
811                                         type_ident: Ident,
812                                         self_args: &[P<Expr>],
813                                         nonself_args: &[P<Expr>])
814         -> P<Expr> {
815         let summary = trait_.summarise_struct(cx, struct_def);
816
817         self.call_substructure_method(cx,
818                                       trait_,
819                                       type_ident,
820                                       self_args, nonself_args,
821                                       &StaticStruct(struct_def, summary))
822     }
823
824     /// ```
825     /// #[derive(PartialEq)]
826     /// enum A {
827     ///     A1,
828     ///     A2(i32)
829     /// }
830     ///
831     /// // is equivalent to
832     ///
833     /// impl PartialEq for A {
834     ///     fn eq(&self, __arg_1: &A) -> ::bool {
835     ///         match (&*self, &*__arg_1) {
836     ///             (&A1, &A1) => true,
837     ///             (&A2(ref __self_0),
838     ///              &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)),
839     ///             _ => {
840     ///                 let __self_vi = match *self { A1(..) => 0us, A2(..) => 1us };
841     ///                 let __arg_1_vi = match *__arg_1 { A1(..) => 0us, A2(..) => 1us };
842     ///                 false
843     ///             }
844     ///         }
845     ///     }
846     /// }
847     /// ```
848     ///
849     /// (Of course `__self_vi` and `__arg_1_vi` are unused for
850     /// `PartialEq`, and those subcomputations will hopefully be removed
851     /// as their results are unused.  The point of `__self_vi` and
852     /// `__arg_1_vi` is for `PartialOrd`; see #15503.)
853     fn expand_enum_method_body(&self,
854                                cx: &mut ExtCtxt,
855                                trait_: &TraitDef,
856                                enum_def: &EnumDef,
857                                type_ident: Ident,
858                                self_args: Vec<P<Expr>>,
859                                nonself_args: &[P<Expr>])
860                                -> P<Expr> {
861         self.build_enum_match_tuple(
862             cx, trait_, enum_def, type_ident, self_args, nonself_args)
863     }
864
865
866     /// Creates a match for a tuple of all `self_args`, where either all
867     /// variants match, or it falls into a catch-all for when one variant
868     /// does not match.
869
870     /// There are N + 1 cases because is a case for each of the N
871     /// variants where all of the variants match, and one catch-all for
872     /// when one does not match.
873
874     /// The catch-all handler is provided access the variant index values
875     /// for each of the self-args, carried in precomputed variables. (Nota
876     /// bene: the variant index values are not necessarily the
877     /// discriminant values.  See issue #15523.)
878
879     /// ```{.text}
880     /// match (this, that, ...) {
881     ///   (Variant1, Variant1, Variant1) => ... // delegate Matching on Variant1
882     ///   (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2
883     ///   ...
884     ///   _ => {
885     ///     let __this_vi = match this { Variant1 => 0us, Variant2 => 1us, ... };
886     ///     let __that_vi = match that { Variant1 => 0us, Variant2 => 1us, ... };
887     ///     ... // catch-all remainder can inspect above variant index values.
888     ///   }
889     /// }
890     /// ```
891     fn build_enum_match_tuple(
892         &self,
893         cx: &mut ExtCtxt,
894         trait_: &TraitDef,
895         enum_def: &EnumDef,
896         type_ident: Ident,
897         self_args: Vec<P<Expr>>,
898         nonself_args: &[P<Expr>]) -> P<Expr> {
899
900         let sp = trait_.span;
901         let variants = &enum_def.variants;
902
903         let self_arg_names = self_args.iter().enumerate()
904             .map(|(arg_count, _self_arg)| {
905                 if arg_count == 0 {
906                     "__self".to_string()
907                 } else {
908                     format!("__arg_{}", arg_count)
909                 }
910             })
911             .collect::<Vec<String>>();
912
913         let self_arg_idents = self_arg_names.iter()
914             .map(|name|cx.ident_of(&name[]))
915             .collect::<Vec<ast::Ident>>();
916
917         // The `vi_idents` will be bound, solely in the catch-all, to
918         // a series of let statements mapping each self_arg to a usize
919         // corresponding to its variant index.
920         let vi_idents: Vec<ast::Ident> = self_arg_names.iter()
921             .map(|name| { let vi_suffix = format!("{}_vi", &name[]);
922                           cx.ident_of(&vi_suffix[]) })
923             .collect::<Vec<ast::Ident>>();
924
925         // Builds, via callback to call_substructure_method, the
926         // delegated expression that handles the catch-all case,
927         // using `__variants_tuple` to drive logic if necessary.
928         let catch_all_substructure = EnumNonMatchingCollapsed(
929             self_arg_idents, &variants[], &vi_idents[]);
930
931         // These arms are of the form:
932         // (Variant1, Variant1, ...) => Body1
933         // (Variant2, Variant2, ...) => Body2
934         // ...
935         // where each tuple has length = self_args.len()
936         let mut match_arms: Vec<ast::Arm> = variants.iter().enumerate()
937             .map(|(index, variant)| {
938                 let mk_self_pat = |&: cx: &mut ExtCtxt, self_arg_name: &str| {
939                     let (p, idents) = trait_.create_enum_variant_pattern(cx, type_ident,
940                                                                          &**variant,
941                                                                          self_arg_name,
942                                                                          ast::MutImmutable);
943                     (cx.pat(sp, ast::PatRegion(p, ast::MutImmutable)), idents)
944                 };
945
946                 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
947                 // (see "Final wrinkle" note below for why.)
948                 let mut subpats = Vec::with_capacity(self_arg_names.len());
949                 let mut self_pats_idents = Vec::with_capacity(self_arg_names.len() - 1);
950                 let first_self_pat_idents = {
951                     let (p, idents) = mk_self_pat(cx, &self_arg_names[0][]);
952                     subpats.push(p);
953                     idents
954                 };
955                 for self_arg_name in self_arg_names.tail().iter() {
956                     let (p, idents) = mk_self_pat(cx, &self_arg_name[]);
957                     subpats.push(p);
958                     self_pats_idents.push(idents);
959                 }
960
961                 // Here is the pat = `(&VariantK, &VariantK, ...)`
962                 let single_pat = cx.pat_tuple(sp, subpats);
963
964                 // For the BodyK, we need to delegate to our caller,
965                 // passing it an EnumMatching to indicate which case
966                 // we are in.
967
968                 // All of the Self args have the same variant in these
969                 // cases.  So we transpose the info in self_pats_idents
970                 // to gather the getter expressions together, in the
971                 // form that EnumMatching expects.
972
973                 // The transposition is driven by walking across the
974                 // arg fields of the variant for the first self pat.
975                 let field_tuples = first_self_pat_idents.into_iter().enumerate()
976                     // For each arg field of self, pull out its getter expr ...
977                     .map(|(field_index, (sp, opt_ident, self_getter_expr))| {
978                         // ... but FieldInfo also wants getter expr
979                         // for matching other arguments of Self type;
980                         // so walk across the *other* self_pats_idents
981                         // and pull out getter for same field in each
982                         // of them (using `field_index` tracked above).
983                         // That is the heart of the transposition.
984                         let others = self_pats_idents.iter().map(|fields| {
985                             let (_, _opt_ident, ref other_getter_expr) =
986                                 fields[field_index];
987
988                             // All Self args have same variant, so
989                             // opt_idents are the same.  (Assert
990                             // here to make it self-evident that
991                             // it is okay to ignore `_opt_ident`.)
992                             assert!(opt_ident == _opt_ident);
993
994                             other_getter_expr.clone()
995                         }).collect::<Vec<P<Expr>>>();
996
997                         FieldInfo { span: sp,
998                                     name: opt_ident,
999                                     self_: self_getter_expr,
1000                                     other: others,
1001                         }
1002                     }).collect::<Vec<FieldInfo>>();
1003
1004                 // Now, for some given VariantK, we have built up
1005                 // expressions for referencing every field of every
1006                 // Self arg, assuming all are instances of VariantK.
1007                 // Build up code associated with such a case.
1008                 let substructure = EnumMatching(index,
1009                                                 &**variant,
1010                                                 field_tuples);
1011                 let arm_expr = self.call_substructure_method(
1012                     cx, trait_, type_ident, &self_args[], nonself_args,
1013                     &substructure);
1014
1015                 cx.arm(sp, vec![single_pat], arm_expr)
1016             }).collect();
1017
1018         // We will usually need the catch-all after matching the
1019         // tuples `(VariantK, VariantK, ...)` for each VariantK of the
1020         // enum.  But:
1021         //
1022         // * when there is only one Self arg, the arms above suffice
1023         // (and the deriving we call back into may not be prepared to
1024         // handle EnumNonMatchCollapsed), and,
1025         //
1026         // * when the enum has only one variant, the single arm that
1027         // is already present always suffices.
1028         //
1029         // * In either of the two cases above, if we *did* add a
1030         //   catch-all `_` match, it would trigger the
1031         //   unreachable-pattern error.
1032         //
1033         if variants.len() > 1 && self_args.len() > 1 {
1034             let arms: Vec<ast::Arm> = variants.iter().enumerate()
1035                 .map(|(index, variant)| {
1036                     let pat = variant_to_pat(cx, sp, type_ident, &**variant);
1037                     let lit = ast::LitInt(index as u64, ast::UnsignedIntLit(ast::TyUs(false)));
1038                     cx.arm(sp, vec![pat], cx.expr_lit(sp, lit))
1039                 }).collect();
1040
1041             // Build a series of let statements mapping each self_arg
1042             // to a usize corresponding to its variant index.
1043             // i.e. for `enum E<T> { A, B(1), C(T, T) }`, and a deriving
1044             // with three Self args, builds three statements:
1045             //
1046             // ```
1047             // let __self0_vi = match   self {
1048             //     A => 0us, B(..) => 1us, C(..) => 2us
1049             // };
1050             // let __self1_vi = match __arg1 {
1051             //     A => 0us, B(..) => 1us, C(..) => 2us
1052             // };
1053             // let __self2_vi = match __arg2 {
1054             //     A => 0us, B(..) => 1us, C(..) => 2us
1055             // };
1056             // ```
1057             let mut index_let_stmts: Vec<P<ast::Stmt>> = Vec::new();
1058             for (&ident, self_arg) in vi_idents.iter().zip(self_args.iter()) {
1059                 let variant_idx = cx.expr_match(sp, self_arg.clone(), arms.clone());
1060                 let let_stmt = cx.stmt_let(sp, false, ident, variant_idx);
1061                 index_let_stmts.push(let_stmt);
1062             }
1063
1064             let arm_expr = self.call_substructure_method(
1065                 cx, trait_, type_ident, &self_args[], nonself_args,
1066                 &catch_all_substructure);
1067
1068             // Builds the expression:
1069             // {
1070             //   let __self0_vi = ...;
1071             //   let __self1_vi = ...;
1072             //   ...
1073             //   <delegated expression referring to __self0_vi, et al.>
1074             // }
1075             let arm_expr = cx.expr_block(
1076                 cx.block_all(sp, Vec::new(), index_let_stmts, Some(arm_expr)));
1077
1078             // Builds arm:
1079             // _ => { let __self0_vi = ...;
1080             //        let __self1_vi = ...;
1081             //        ...
1082             //        <delegated expression as above> }
1083             let catch_all_match_arm =
1084                 cx.arm(sp, vec![cx.pat_wild(sp)], arm_expr);
1085
1086             match_arms.push(catch_all_match_arm);
1087
1088         } else if variants.len() == 0 {
1089             // As an additional wrinkle, For a zero-variant enum A,
1090             // currently the compiler
1091             // will accept `fn (a: &Self) { match   *a   { } }`
1092             // but rejects `fn (a: &Self) { match (&*a,) { } }`
1093             // as well as  `fn (a: &Self) { match ( *a,) { } }`
1094             //
1095             // This means that the strategy of building up a tuple of
1096             // all Self arguments fails when Self is a zero variant
1097             // enum: rustc rejects the expanded program, even though
1098             // the actual code tends to be impossible to execute (at
1099             // least safely), according to the type system.
1100             //
1101             // The most expedient fix for this is to just let the
1102             // code fall through to the catch-all.  But even this is
1103             // error-prone, since the catch-all as defined above would
1104             // generate code like this:
1105             //
1106             //     _ => { let __self0 = match *self { };
1107             //            let __self1 = match *__arg_0 { };
1108             //            <catch-all-expr> }
1109             //
1110             // Which is yields bindings for variables which type
1111             // inference cannot resolve to unique types.
1112             //
1113             // One option to the above might be to add explicit type
1114             // annotations.  But the *only* reason to go down that path
1115             // would be to try to make the expanded output consistent
1116             // with the case when the number of enum variants >= 1.
1117             //
1118             // That just isn't worth it.  In fact, trying to generate
1119             // sensible code for *any* deriving on a zero-variant enum
1120             // does not make sense.  But at the same time, for now, we
1121             // do not want to cause a compile failure just because the
1122             // user happened to attach a deriving to their
1123             // zero-variant enum.
1124             //
1125             // Instead, just generate a failing expression for the
1126             // zero variant case, skipping matches and also skipping
1127             // delegating back to the end user code entirely.
1128             //
1129             // (See also #4499 and #12609; note that some of the
1130             // discussions there influence what choice we make here;
1131             // e.g. if we feature-gate `match x { ... }` when x refers
1132             // to an uninhabited type (e.g. a zero-variant enum or a
1133             // type holding such an enum), but do not feature-gate
1134             // zero-variant enums themselves, then attempting to
1135             // derive Show on such a type could here generate code
1136             // that needs the feature gate enabled.)
1137
1138             return cx.expr_unreachable(sp);
1139         }
1140
1141         // Final wrinkle: the self_args are expressions that deref
1142         // down to desired l-values, but we cannot actually deref
1143         // them when they are fed as r-values into a tuple
1144         // expression; here add a layer of borrowing, turning
1145         // `(*self, *__arg_0, ...)` into `(&*self, &*__arg_0, ...)`.
1146         let borrowed_self_args = self_args.move_map(|self_arg| cx.expr_addr_of(sp, self_arg));
1147         let match_arg = cx.expr(sp, ast::ExprTup(borrowed_self_args));
1148         cx.expr_match(sp, match_arg, match_arms)
1149     }
1150
1151     fn expand_static_enum_method_body(&self,
1152                                       cx: &mut ExtCtxt,
1153                                       trait_: &TraitDef,
1154                                       enum_def: &EnumDef,
1155                                       type_ident: Ident,
1156                                       self_args: &[P<Expr>],
1157                                       nonself_args: &[P<Expr>])
1158         -> P<Expr> {
1159         let summary = enum_def.variants.iter().map(|v| {
1160             let ident = v.node.name;
1161             let summary = match v.node.kind {
1162                 ast::TupleVariantKind(ref args) => {
1163                     Unnamed(args.iter().map(|va| trait_.set_expn_info(cx, va.ty.span)).collect())
1164                 }
1165                 ast::StructVariantKind(ref struct_def) => {
1166                     trait_.summarise_struct(cx, &**struct_def)
1167                 }
1168             };
1169             (ident, v.span, summary)
1170         }).collect();
1171         self.call_substructure_method(cx, trait_, type_ident,
1172                                       self_args, nonself_args,
1173                                       &StaticEnum(enum_def, summary))
1174     }
1175 }
1176
1177 #[derive(PartialEq)] // dogfooding!
1178 enum StructType {
1179     Unknown, Record, Tuple
1180 }
1181
1182 // general helper methods.
1183 impl<'a> TraitDef<'a> {
1184     fn set_expn_info(&self,
1185                      cx: &mut ExtCtxt,
1186                      mut to_set: Span) -> Span {
1187         let trait_name = match self.path.path.last() {
1188             None => cx.span_bug(self.span, "trait with empty path in generic `derive`"),
1189             Some(name) => *name
1190         };
1191         to_set.expn_id = cx.codemap().record_expansion(codemap::ExpnInfo {
1192             call_site: to_set,
1193             callee: codemap::NameAndSpan {
1194                 name: format!("derive({})", trait_name),
1195                 format: codemap::MacroAttribute,
1196                 span: Some(self.span)
1197             }
1198         });
1199         to_set
1200     }
1201
1202     fn summarise_struct(&self,
1203                         cx: &mut ExtCtxt,
1204                         struct_def: &StructDef) -> StaticFields {
1205         let mut named_idents = Vec::new();
1206         let mut just_spans = Vec::new();
1207         for field in struct_def.fields.iter(){
1208             let sp = self.set_expn_info(cx, field.span);
1209             match field.node.kind {
1210                 ast::NamedField(ident, _) => named_idents.push((ident, sp)),
1211                 ast::UnnamedField(..) => just_spans.push(sp),
1212             }
1213         }
1214
1215         match (just_spans.is_empty(), named_idents.is_empty()) {
1216             (false, false) => cx.span_bug(self.span,
1217                                           "a struct with named and unnamed \
1218                                           fields in generic `derive`"),
1219             // named fields
1220             (_, false) => Named(named_idents),
1221             // tuple structs (includes empty structs)
1222             (_, _)     => Unnamed(just_spans)
1223         }
1224     }
1225
1226     fn create_subpatterns(&self,
1227                           cx: &mut ExtCtxt,
1228                           field_paths: Vec<ast::SpannedIdent> ,
1229                           mutbl: ast::Mutability)
1230                           -> Vec<P<ast::Pat>> {
1231         field_paths.iter().map(|path| {
1232             cx.pat(path.span,
1233                         ast::PatIdent(ast::BindByRef(mutbl), (*path).clone(), None))
1234         }).collect()
1235     }
1236
1237     fn create_struct_pattern(&self,
1238                              cx: &mut ExtCtxt,
1239                              struct_path: ast::Path,
1240                              struct_def: &StructDef,
1241                              prefix: &str,
1242                              mutbl: ast::Mutability)
1243                              -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>)>) {
1244         if struct_def.fields.is_empty() {
1245             return (cx.pat_enum(self.span, struct_path, vec![]), vec![]);
1246         }
1247
1248         let mut paths = Vec::new();
1249         let mut ident_expr = Vec::new();
1250         let mut struct_type = Unknown;
1251
1252         for (i, struct_field) in struct_def.fields.iter().enumerate() {
1253             let sp = self.set_expn_info(cx, struct_field.span);
1254             let opt_id = match struct_field.node.kind {
1255                 ast::NamedField(ident, _) if (struct_type == Unknown ||
1256                                               struct_type == Record) => {
1257                     struct_type = Record;
1258                     Some(ident)
1259                 }
1260                 ast::UnnamedField(..) if (struct_type == Unknown ||
1261                                           struct_type == Tuple) => {
1262                     struct_type = Tuple;
1263                     None
1264                 }
1265                 _ => {
1266                     cx.span_bug(sp, "a struct with named and unnamed fields in `derive`");
1267                 }
1268             };
1269             let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]);
1270             paths.push(codemap::Spanned{span: sp, node: ident});
1271             let val = cx.expr(
1272                 sp, ast::ExprParen(cx.expr_deref(sp, cx.expr_path(cx.path_ident(sp,ident)))));
1273             ident_expr.push((sp, opt_id, val));
1274         }
1275
1276         let subpats = self.create_subpatterns(cx, paths, mutbl);
1277
1278         // struct_type is definitely not Unknown, since struct_def.fields
1279         // must be nonempty to reach here
1280         let pattern = if struct_type == Record {
1281             let field_pats = subpats.into_iter().zip(ident_expr.iter()).map(|(pat, &(_, id, _))| {
1282                 // id is guaranteed to be Some
1283                 codemap::Spanned {
1284                     span: pat.span,
1285                     node: ast::FieldPat { ident: id.unwrap(), pat: pat, is_shorthand: false },
1286                 }
1287             }).collect();
1288             cx.pat_struct(self.span, struct_path, field_pats)
1289         } else {
1290             cx.pat_enum(self.span, struct_path, subpats)
1291         };
1292
1293         (pattern, ident_expr)
1294     }
1295
1296     fn create_enum_variant_pattern(&self,
1297                                    cx: &mut ExtCtxt,
1298                                    enum_ident: ast::Ident,
1299                                    variant: &ast::Variant,
1300                                    prefix: &str,
1301                                    mutbl: ast::Mutability)
1302         -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>)>) {
1303         let variant_ident = variant.node.name;
1304         let variant_path = cx.path(variant.span, vec![enum_ident, variant_ident]);
1305         match variant.node.kind {
1306             ast::TupleVariantKind(ref variant_args) => {
1307                 if variant_args.is_empty() {
1308                     return (cx.pat_enum(variant.span, variant_path, vec![]), vec![]);
1309                 }
1310
1311                 let mut paths = Vec::new();
1312                 let mut ident_expr = Vec::new();
1313                 for (i, va) in variant_args.iter().enumerate() {
1314                     let sp = self.set_expn_info(cx, va.ty.span);
1315                     let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]);
1316                     let path1 = codemap::Spanned{span: sp, node: ident};
1317                     paths.push(path1);
1318                     let expr_path = cx.expr_path(cx.path_ident(sp, ident));
1319                     let val = cx.expr(sp, ast::ExprParen(cx.expr_deref(sp, expr_path)));
1320                     ident_expr.push((sp, None, val));
1321                 }
1322
1323                 let subpats = self.create_subpatterns(cx, paths, mutbl);
1324
1325                 (cx.pat_enum(variant.span, variant_path, subpats),
1326                  ident_expr)
1327             }
1328             ast::StructVariantKind(ref struct_def) => {
1329                 self.create_struct_pattern(cx, variant_path, &**struct_def,
1330                                            prefix, mutbl)
1331             }
1332         }
1333     }
1334 }
1335
1336 /* helpful premade recipes */
1337
1338 /// Fold the fields. `use_foldl` controls whether this is done
1339 /// left-to-right (`true`) or right-to-left (`false`).
1340 pub fn cs_fold<F>(use_foldl: bool,
1341                   mut f: F,
1342                   base: P<Expr>,
1343                   mut enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1344                   cx: &mut ExtCtxt,
1345                   trait_span: Span,
1346                   substructure: &Substructure)
1347                   -> P<Expr> where
1348     F: FnMut(&mut ExtCtxt, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>,
1349 {
1350     match *substructure.fields {
1351         EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => {
1352             if use_foldl {
1353                 all_fields.iter().fold(base, |old, field| {
1354                     f(cx,
1355                       field.span,
1356                       old,
1357                       field.self_.clone(),
1358                       &field.other[])
1359                 })
1360             } else {
1361                 all_fields.iter().rev().fold(base, |old, field| {
1362                     f(cx,
1363                       field.span,
1364                       old,
1365                       field.self_.clone(),
1366                       &field.other[])
1367                 })
1368             }
1369         },
1370         EnumNonMatchingCollapsed(ref all_args, _, tuple) =>
1371             enum_nonmatch_f(cx, trait_span, (&all_args[], tuple),
1372                             substructure.nonself_args),
1373         StaticEnum(..) | StaticStruct(..) => {
1374             cx.span_bug(trait_span, "static function in `derive`")
1375         }
1376     }
1377 }
1378
1379
1380 /// Call the method that is being derived on all the fields, and then
1381 /// process the collected results. i.e.
1382 ///
1383 /// ```
1384 /// f(cx, span, vec![self_1.method(__arg_1_1, __arg_2_1),
1385 ///                  self_2.method(__arg_1_2, __arg_2_2)])
1386 /// ```
1387 #[inline]
1388 pub fn cs_same_method<F>(f: F,
1389                          mut enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1390                          cx: &mut ExtCtxt,
1391                          trait_span: Span,
1392                          substructure: &Substructure)
1393                          -> P<Expr> where
1394     F: FnOnce(&mut ExtCtxt, Span, Vec<P<Expr>>) -> P<Expr>,
1395 {
1396     match *substructure.fields {
1397         EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => {
1398             // call self_n.method(other_1_n, other_2_n, ...)
1399             let called = all_fields.iter().map(|field| {
1400                 cx.expr_method_call(field.span,
1401                                     field.self_.clone(),
1402                                     substructure.method_ident,
1403                                     field.other.iter()
1404                                                .map(|e| cx.expr_addr_of(field.span, e.clone()))
1405                                                .collect())
1406             }).collect();
1407
1408             f(cx, trait_span, called)
1409         },
1410         EnumNonMatchingCollapsed(ref all_self_args, _, tuple) =>
1411             enum_nonmatch_f(cx, trait_span, (&all_self_args[], tuple),
1412                             substructure.nonself_args),
1413         StaticEnum(..) | StaticStruct(..) => {
1414             cx.span_bug(trait_span, "static function in `derive`")
1415         }
1416     }
1417 }
1418
1419 /// Fold together the results of calling the derived method on all the
1420 /// fields. `use_foldl` controls whether this is done left-to-right
1421 /// (`true`) or right-to-left (`false`).
1422 #[inline]
1423 pub fn cs_same_method_fold<F>(use_foldl: bool,
1424                               mut f: F,
1425                               base: P<Expr>,
1426                               enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1427                               cx: &mut ExtCtxt,
1428                               trait_span: Span,
1429                               substructure: &Substructure)
1430                               -> P<Expr> where
1431     F: FnMut(&mut ExtCtxt, Span, P<Expr>, P<Expr>) -> P<Expr>,
1432 {
1433     cs_same_method(
1434         |cx, span, vals| {
1435             if use_foldl {
1436                 vals.into_iter().fold(base.clone(), |old, new| {
1437                     f(cx, span, old, new)
1438                 })
1439             } else {
1440                 vals.into_iter().rev().fold(base.clone(), |old, new| {
1441                     f(cx, span, old, new)
1442                 })
1443             }
1444         },
1445         enum_nonmatch_f,
1446         cx, trait_span, substructure)
1447 }
1448
1449 /// Use a given binop to combine the result of calling the derived method
1450 /// on all the fields.
1451 #[inline]
1452 pub fn cs_binop(binop: ast::BinOp, base: P<Expr>,
1453                 enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1454                 cx: &mut ExtCtxt, trait_span: Span,
1455                 substructure: &Substructure) -> P<Expr> {
1456     cs_same_method_fold(
1457         true, // foldl is good enough
1458         |cx, span, old, new| {
1459             cx.expr_binary(span,
1460                            binop,
1461                            old, new)
1462
1463         },
1464         base,
1465         enum_nonmatch_f,
1466         cx, trait_span, substructure)
1467 }
1468
1469 /// cs_binop with binop == or
1470 #[inline]
1471 pub fn cs_or(enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1472              cx: &mut ExtCtxt, span: Span,
1473              substructure: &Substructure) -> P<Expr> {
1474     cs_binop(ast::BiOr, cx.expr_bool(span, false),
1475              enum_nonmatch_f,
1476              cx, span, substructure)
1477 }
1478
1479 /// cs_binop with binop == and
1480 #[inline]
1481 pub fn cs_and(enum_nonmatch_f: EnumNonMatchCollapsedFunc,
1482               cx: &mut ExtCtxt, span: Span,
1483               substructure: &Substructure) -> P<Expr> {
1484     cs_binop(ast::BiAnd, cx.expr_bool(span, true),
1485              enum_nonmatch_f,
1486              cx, span, substructure)
1487 }