]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
Rollup merge of #106383 - Manishearth:ast-docs, r=compiler-errors
[rust.git] / compiler / rustc_builtin_macros / src / deriving / generic / mod.rs
1 //! Some code that abstracts away much of the boilerplate of writing
2 //! `derive` instances for traits. Among other things it manages getting
3 //! access to the fields of the 4 different sorts of structs and enum
4 //! variants, as well as creating the method and impl ast instances.
5 //!
6 //! Supported features (fairly exhaustive):
7 //!
8 //! - Methods taking any number of parameters of any type, and returning
9 //!   any type, other than vectors, bottom and closures.
10 //! - Generating `impl`s for types with type parameters and lifetimes
11 //!   (e.g., `Option<T>`), the parameters are automatically given the
12 //!   current trait as a bound. (This includes separate type parameters
13 //!   and lifetimes for methods.)
14 //! - Additional bounds on the type parameters (`TraitDef.additional_bounds`)
15 //!
16 //! The most important thing for implementors is the `Substructure` and
17 //! `SubstructureFields` objects. The latter groups 5 possibilities of the
18 //! arguments:
19 //!
20 //! - `Struct`, when `Self` is a struct (including tuple structs, e.g
21 //!   `struct T(i32, char)`).
22 //! - `EnumMatching`, when `Self` is an enum and all the arguments are the
23 //!   same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`)
24 //! - `EnumTag` when `Self` is an enum, for comparing the enum tags.
25 //! - `StaticEnum` and `StaticStruct` for static methods, where the type
26 //!   being derived upon is either an enum or struct respectively. (Any
27 //!   argument with type Self is just grouped among the non-self
28 //!   arguments.)
29 //!
30 //! In the first two cases, the values from the corresponding fields in
31 //! all the arguments are grouped together.
32 //!
33 //! The non-static cases have `Option<ident>` in several places associated
34 //! with field `expr`s. This represents the name of the field it is
35 //! associated with. It is only not `None` when the associated field has
36 //! an identifier in the source code. For example, the `x`s in the
37 //! following snippet
38 //!
39 //! ```rust
40 //! # #![allow(dead_code)]
41 //! struct A { x : i32 }
42 //!
43 //! struct B(i32);
44 //!
45 //! enum C {
46 //!     C0(i32),
47 //!     C1 { x: i32 }
48 //! }
49 //! ```
50 //!
51 //! The `i32`s in `B` and `C0` don't have an identifier, so the
52 //! `Option<ident>`s would be `None` for them.
53 //!
54 //! In the static cases, the structure is summarized, either into the just
55 //! spans of the fields or a list of spans and the field idents (for tuple
56 //! structs and record structs, respectively), or a list of these, for
57 //! enums (one for each variant). For empty struct and empty enum
58 //! variants, it is represented as a count of 0.
59 //!
60 //! # "`cs`" functions
61 //!
62 //! The `cs_...` functions ("combine substructure") are designed to
63 //! make life easier by providing some pre-made recipes for common
64 //! threads; mostly calling the function being derived on all the
65 //! arguments and then combining them back together in some way (or
66 //! letting the user chose that). They are not meant to be the only
67 //! way to handle the structures that this code creates.
68 //!
69 //! # Examples
70 //!
71 //! The following simplified `PartialEq` is used for in-code examples:
72 //!
73 //! ```rust
74 //! trait PartialEq {
75 //!     fn eq(&self, other: &Self) -> bool;
76 //! }
77 //! impl PartialEq for i32 {
78 //!     fn eq(&self, other: &i32) -> bool {
79 //!         *self == *other
80 //!     }
81 //! }
82 //! ```
83 //!
84 //! Some examples of the values of `SubstructureFields` follow, using the
85 //! above `PartialEq`, `A`, `B` and `C`.
86 //!
87 //! ## Structs
88 //!
89 //! When generating the `expr` for the `A` impl, the `SubstructureFields` is
90 //!
91 //! ```{.text}
92 //! Struct(vec![FieldInfo {
93 //!            span: <span of x>
94 //!            name: Some(<ident of x>),
95 //!            self_: <expr for &self.x>,
96 //!            other: vec![<expr for &other.x]
97 //!          }])
98 //! ```
99 //!
100 //! For the `B` impl, called with `B(a)` and `B(b)`,
101 //!
102 //! ```{.text}
103 //! Struct(vec![FieldInfo {
104 //!           span: <span of `i32`>,
105 //!           name: None,
106 //!           self_: <expr for &a>
107 //!           other: vec![<expr for &b>]
108 //!          }])
109 //! ```
110 //!
111 //! ## Enums
112 //!
113 //! When generating the `expr` for a call with `self == C0(a)` and `other
114 //! == C0(b)`, the SubstructureFields is
115 //!
116 //! ```{.text}
117 //! EnumMatching(0, <ast::Variant for C0>,
118 //!              vec![FieldInfo {
119 //!                 span: <span of i32>
120 //!                 name: None,
121 //!                 self_: <expr for &a>,
122 //!                 other: vec![<expr for &b>]
123 //!               }])
124 //! ```
125 //!
126 //! For `C1 {x}` and `C1 {x}`,
127 //!
128 //! ```{.text}
129 //! EnumMatching(1, <ast::Variant for C1>,
130 //!              vec![FieldInfo {
131 //!                 span: <span of x>
132 //!                 name: Some(<ident of x>),
133 //!                 self_: <expr for &self.x>,
134 //!                 other: vec![<expr for &other.x>]
135 //!                }])
136 //! ```
137 //!
138 //! For the tags,
139 //!
140 //! ```{.text}
141 //! EnumTag(
142 //!     &[<ident of self tag>, <ident of other tag>], <expr to combine with>)
143 //! ```
144 //! Note that this setup doesn't allow for the brute-force "match every variant
145 //! against every other variant" approach, which is bad because it produces a
146 //! quadratic amount of code (see #15375).
147 //!
148 //! ## Static
149 //!
150 //! A static method on the types above would result in,
151 //!
152 //! ```{.text}
153 //! StaticStruct(<ast::VariantData of A>, Named(vec![(<ident of x>, <span of x>)]))
154 //!
155 //! StaticStruct(<ast::VariantData of B>, Unnamed(vec![<span of x>]))
156 //!
157 //! StaticEnum(<ast::EnumDef of C>,
158 //!            vec![(<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])),
159 //!                 (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)]))])
160 //! ```
161
162 pub use StaticFields::*;
163 pub use SubstructureFields::*;
164
165 use crate::deriving;
166 use rustc_ast::ptr::P;
167 use rustc_ast::{
168     self as ast, BindingAnnotation, ByRef, EnumDef, Expr, Generics, Mutability, PatKind,
169 };
170 use rustc_ast::{GenericArg, GenericParamKind, VariantData};
171 use rustc_attr as attr;
172 use rustc_expand::base::{Annotatable, ExtCtxt};
173 use rustc_span::symbol::{kw, sym, Ident, Symbol};
174 use rustc_span::{Span, DUMMY_SP};
175 use std::cell::RefCell;
176 use std::iter;
177 use std::ops::Not;
178 use std::vec;
179 use thin_vec::thin_vec;
180 use ty::{Bounds, Path, Ref, Self_, Ty};
181
182 pub mod ty;
183
184 pub struct TraitDef<'a> {
185     /// The span for the current #[derive(Foo)] header.
186     pub span: Span,
187
188     /// Path of the trait, including any type parameters
189     pub path: Path,
190
191     /// Whether to skip adding the current trait as a bound to the type parameters of the type.
192     pub skip_path_as_bound: bool,
193
194     /// Additional bounds required of any type parameters of the type,
195     /// other than the current trait
196     pub additional_bounds: Vec<Ty>,
197
198     /// Can this trait be derived for unions?
199     pub supports_unions: bool,
200
201     pub methods: Vec<MethodDef<'a>>,
202
203     pub associated_types: Vec<(Ident, Ty)>,
204
205     pub is_const: bool,
206 }
207
208 pub struct MethodDef<'a> {
209     /// name of the method
210     pub name: Symbol,
211     /// List of generics, e.g., `R: rand::Rng`
212     pub generics: Bounds,
213
214     /// Is there is a `&self` argument? If not, it is a static function.
215     pub explicit_self: bool,
216
217     /// Arguments other than the self argument.
218     pub nonself_args: Vec<(Ty, Symbol)>,
219
220     /// Returns type
221     pub ret_ty: Ty,
222
223     pub attributes: ast::AttrVec,
224
225     /// Can we combine fieldless variants for enums into a single match arm?
226     /// If true, indicates that the trait operation uses the enum tag in some
227     /// way.
228     pub unify_fieldless_variants: bool,
229
230     pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
231 }
232
233 /// All the data about the data structure/method being derived upon.
234 pub struct Substructure<'a> {
235     /// ident of self
236     pub type_ident: Ident,
237     /// Verbatim access to any non-selflike arguments, i.e. arguments that
238     /// don't have type `&Self`.
239     pub nonselflike_args: &'a [P<Expr>],
240     pub fields: &'a SubstructureFields<'a>,
241 }
242
243 /// Summary of the relevant parts of a struct/enum field.
244 pub struct FieldInfo {
245     pub span: Span,
246     /// None for tuple structs/normal enum variants, Some for normal
247     /// structs/struct enum variants.
248     pub name: Option<Ident>,
249     /// The expression corresponding to this field of `self`
250     /// (specifically, a reference to it).
251     pub self_expr: P<Expr>,
252     /// The expressions corresponding to references to this field in
253     /// the other selflike arguments.
254     pub other_selflike_exprs: Vec<P<Expr>>,
255 }
256
257 /// Fields for a static method
258 pub enum StaticFields {
259     /// Tuple and unit structs/enum variants like this.
260     Unnamed(Vec<Span>, bool /*is tuple*/),
261     /// Normal structs/struct variants.
262     Named(Vec<(Ident, Span)>),
263 }
264
265 /// A summary of the possible sets of fields.
266 pub enum SubstructureFields<'a> {
267     /// A non-static method with `Self` is a struct.
268     Struct(&'a ast::VariantData, Vec<FieldInfo>),
269
270     /// Matching variants of the enum: variant index, variant count, ast::Variant,
271     /// fields: the field name is only non-`None` in the case of a struct
272     /// variant.
273     EnumMatching(usize, usize, &'a ast::Variant, Vec<FieldInfo>),
274
275     /// The tag of an enum. The first field is a `FieldInfo` for the tags, as
276     /// if they were fields. The second field is the expression to combine the
277     /// tag expression with; it will be `None` if no match is necessary.
278     EnumTag(FieldInfo, Option<P<Expr>>),
279
280     /// A static method where `Self` is a struct.
281     StaticStruct(&'a ast::VariantData, StaticFields),
282
283     /// A static method where `Self` is an enum.
284     StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
285 }
286
287 /// Combine the values of all the fields together. The last argument is
288 /// all the fields of all the structures.
289 pub type CombineSubstructureFunc<'a> =
290     Box<dyn FnMut(&mut ExtCtxt<'_>, Span, &Substructure<'_>) -> BlockOrExpr + 'a>;
291
292 pub fn combine_substructure(
293     f: CombineSubstructureFunc<'_>,
294 ) -> RefCell<CombineSubstructureFunc<'_>> {
295     RefCell::new(f)
296 }
297
298 struct TypeParameter {
299     bound_generic_params: Vec<ast::GenericParam>,
300     ty: P<ast::Ty>,
301 }
302
303 /// The code snippets built up for derived code are sometimes used as blocks
304 /// (e.g. in a function body) and sometimes used as expressions (e.g. in a match
305 /// arm). This structure avoids committing to either form until necessary,
306 /// avoiding the insertion of any unnecessary blocks.
307 ///
308 /// The statements come before the expression.
309 pub struct BlockOrExpr(Vec<ast::Stmt>, Option<P<Expr>>);
310
311 impl BlockOrExpr {
312     pub fn new_stmts(stmts: Vec<ast::Stmt>) -> BlockOrExpr {
313         BlockOrExpr(stmts, None)
314     }
315
316     pub fn new_expr(expr: P<Expr>) -> BlockOrExpr {
317         BlockOrExpr(vec![], Some(expr))
318     }
319
320     pub fn new_mixed(stmts: Vec<ast::Stmt>, expr: Option<P<Expr>>) -> BlockOrExpr {
321         BlockOrExpr(stmts, expr)
322     }
323
324     // Converts it into a block.
325     fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> P<ast::Block> {
326         if let Some(expr) = self.1 {
327             self.0.push(cx.stmt_expr(expr));
328         }
329         cx.block(span, self.0)
330     }
331
332     // Converts it into an expression.
333     fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> P<Expr> {
334         if self.0.is_empty() {
335             match self.1 {
336                 None => cx.expr_block(cx.block(span, vec![])),
337                 Some(expr) => expr,
338             }
339         } else if self.0.len() == 1
340             && let ast::StmtKind::Expr(expr) = &self.0[0].kind
341             && self.1.is_none()
342         {
343             // There's only a single statement expression. Pull it out.
344             expr.clone()
345         } else {
346             // Multiple statements and/or expressions.
347             cx.expr_block(self.into_block(cx, span))
348         }
349     }
350 }
351
352 /// This method helps to extract all the type parameters referenced from a
353 /// type. For a type parameter `<T>`, it looks for either a `TyPath` that
354 /// is not global and starts with `T`, or a `TyQPath`.
355 /// Also include bound generic params from the input type.
356 fn find_type_parameters(
357     ty: &ast::Ty,
358     ty_param_names: &[Symbol],
359     cx: &ExtCtxt<'_>,
360 ) -> Vec<TypeParameter> {
361     use rustc_ast::visit;
362
363     struct Visitor<'a, 'b> {
364         cx: &'a ExtCtxt<'b>,
365         ty_param_names: &'a [Symbol],
366         bound_generic_params_stack: Vec<ast::GenericParam>,
367         type_params: Vec<TypeParameter>,
368     }
369
370     impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
371         fn visit_ty(&mut self, ty: &'a ast::Ty) {
372             if let ast::TyKind::Path(_, path) = &ty.kind
373                 && let Some(segment) = path.segments.first()
374                 && self.ty_param_names.contains(&segment.ident.name)
375             {
376                 self.type_params.push(TypeParameter {
377                     bound_generic_params: self.bound_generic_params_stack.clone(),
378                     ty: P(ty.clone()),
379                 });
380             }
381
382             visit::walk_ty(self, ty)
383         }
384
385         // Place bound generic params on a stack, to extract them when a type is encountered.
386         fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
387             let stack_len = self.bound_generic_params_stack.len();
388             self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
389
390             visit::walk_poly_trait_ref(self, trait_ref);
391
392             self.bound_generic_params_stack.truncate(stack_len);
393         }
394
395         fn visit_mac_call(&mut self, mac: &ast::MacCall) {
396             self.cx.span_err(mac.span(), "`derive` cannot be used on items with type macros");
397         }
398     }
399
400     let mut visitor = Visitor {
401         cx,
402         ty_param_names,
403         bound_generic_params_stack: Vec::new(),
404         type_params: Vec::new(),
405     };
406     visit::Visitor::visit_ty(&mut visitor, ty);
407
408     visitor.type_params
409 }
410
411 impl<'a> TraitDef<'a> {
412     pub fn expand(
413         self,
414         cx: &mut ExtCtxt<'_>,
415         mitem: &ast::MetaItem,
416         item: &'a Annotatable,
417         push: &mut dyn FnMut(Annotatable),
418     ) {
419         self.expand_ext(cx, mitem, item, push, false);
420     }
421
422     pub fn expand_ext(
423         self,
424         cx: &mut ExtCtxt<'_>,
425         mitem: &ast::MetaItem,
426         item: &'a Annotatable,
427         push: &mut dyn FnMut(Annotatable),
428         from_scratch: bool,
429     ) {
430         match item {
431             Annotatable::Item(item) => {
432                 let is_packed = item.attrs.iter().any(|attr| {
433                     for r in attr::find_repr_attrs(&cx.sess, attr) {
434                         if let attr::ReprPacked(_) = r {
435                             return true;
436                         }
437                     }
438                     false
439                 });
440                 let has_no_type_params = match &item.kind {
441                     ast::ItemKind::Struct(_, generics)
442                     | ast::ItemKind::Enum(_, generics)
443                     | ast::ItemKind::Union(_, generics) => !generics
444                         .params
445                         .iter()
446                         .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. })),
447                     _ => unreachable!(),
448                 };
449                 let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
450                 let copy_fields =
451                     is_packed && has_no_type_params && cx.resolver.has_derive_copy(container_id);
452
453                 let newitem = match &item.kind {
454                     ast::ItemKind::Struct(struct_def, generics) => self.expand_struct_def(
455                         cx,
456                         &struct_def,
457                         item.ident,
458                         generics,
459                         from_scratch,
460                         copy_fields,
461                     ),
462                     ast::ItemKind::Enum(enum_def, generics) => {
463                         // We ignore `is_packed` here, because `repr(packed)`
464                         // enums cause an error later on.
465                         //
466                         // This can only cause further compilation errors
467                         // downstream in blatantly illegal code, so it is fine.
468                         self.expand_enum_def(cx, enum_def, item.ident, generics, from_scratch)
469                     }
470                     ast::ItemKind::Union(struct_def, generics) => {
471                         if self.supports_unions {
472                             self.expand_struct_def(
473                                 cx,
474                                 &struct_def,
475                                 item.ident,
476                                 generics,
477                                 from_scratch,
478                                 copy_fields,
479                             )
480                         } else {
481                             cx.span_err(mitem.span, "this trait cannot be derived for unions");
482                             return;
483                         }
484                     }
485                     _ => unreachable!(),
486                 };
487                 // Keep the lint attributes of the previous item to control how the
488                 // generated implementations are linted
489                 let mut attrs = newitem.attrs.clone();
490                 attrs.extend(
491                     item.attrs
492                         .iter()
493                         .filter(|a| {
494                             [
495                                 sym::allow,
496                                 sym::warn,
497                                 sym::deny,
498                                 sym::forbid,
499                                 sym::stable,
500                                 sym::unstable,
501                             ]
502                             .contains(&a.name_or_empty())
503                         })
504                         .cloned(),
505                 );
506                 push(Annotatable::Item(P(ast::Item { attrs, ..(*newitem).clone() })))
507             }
508             _ => unreachable!(),
509         }
510     }
511
512     /// Given that we are deriving a trait `DerivedTrait` for a type like:
513     ///
514     /// ```ignore (only-for-syntax-highlight)
515     /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z> where C: WhereTrait {
516     ///     a: A,
517     ///     b: B::Item,
518     ///     b1: <B as DeclaredTrait>::Item,
519     ///     c1: <C as WhereTrait>::Item,
520     ///     c2: Option<<C as WhereTrait>::Item>,
521     ///     ...
522     /// }
523     /// ```
524     ///
525     /// create an impl like:
526     ///
527     /// ```ignore (only-for-syntax-highlight)
528     /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ... Z> where
529     ///     C:                       WhereTrait,
530     ///     A: DerivedTrait + B1 + ... + BN,
531     ///     B: DerivedTrait + B1 + ... + BN,
532     ///     C: DerivedTrait + B1 + ... + BN,
533     ///     B::Item:                 DerivedTrait + B1 + ... + BN,
534     ///     <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
535     ///     ...
536     /// {
537     ///     ...
538     /// }
539     /// ```
540     ///
541     /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
542     /// therefore does not get bound by the derived trait.
543     fn create_derived_impl(
544         &self,
545         cx: &mut ExtCtxt<'_>,
546         type_ident: Ident,
547         generics: &Generics,
548         field_tys: Vec<P<ast::Ty>>,
549         methods: Vec<P<ast::AssocItem>>,
550     ) -> P<ast::Item> {
551         let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
552
553         // Transform associated types from `deriving::ty::Ty` into `ast::AssocItem`
554         let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
555             P(ast::AssocItem {
556                 id: ast::DUMMY_NODE_ID,
557                 span: self.span,
558                 ident,
559                 vis: ast::Visibility {
560                     span: self.span.shrink_to_lo(),
561                     kind: ast::VisibilityKind::Inherited,
562                     tokens: None,
563                 },
564                 attrs: ast::AttrVec::new(),
565                 kind: ast::AssocItemKind::Type(Box::new(ast::TyAlias {
566                     defaultness: ast::Defaultness::Final,
567                     generics: Generics::default(),
568                     where_clauses: (
569                         ast::TyAliasWhereClause::default(),
570                         ast::TyAliasWhereClause::default(),
571                     ),
572                     where_predicates_split: 0,
573                     bounds: Vec::new(),
574                     ty: Some(type_def.to_ty(cx, self.span, type_ident, generics)),
575                 })),
576                 tokens: None,
577             })
578         });
579
580         let mut where_clause = ast::WhereClause::default();
581         where_clause.span = generics.where_clause.span;
582         let ctxt = self.span.ctxt();
583         let span = generics.span.with_ctxt(ctxt);
584
585         // Create the generic parameters
586         let params: Vec<_> = generics
587             .params
588             .iter()
589             .map(|param| match &param.kind {
590                 GenericParamKind::Lifetime { .. } => param.clone(),
591                 GenericParamKind::Type { .. } => {
592                     // I don't think this can be moved out of the loop, since
593                     // a GenericBound requires an ast id
594                     let bounds: Vec<_> =
595                     // extra restrictions on the generics parameters to the
596                     // type being derived upon
597                     self.additional_bounds.iter().map(|p| {
598                         cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))
599                     }).chain(
600                         // require the current trait
601                         self.skip_path_as_bound.not().then(|| cx.trait_bound(trait_path.clone()))
602                     ).chain(
603                         // also add in any bounds from the declaration
604                         param.bounds.iter().cloned()
605                     ).collect();
606
607                     cx.typaram(param.ident.span.with_ctxt(ctxt), param.ident, bounds, None)
608                 }
609                 GenericParamKind::Const { ty, kw_span, .. } => {
610                     let const_nodefault_kind = GenericParamKind::Const {
611                         ty: ty.clone(),
612                         kw_span: kw_span.with_ctxt(ctxt),
613
614                         // We can't have default values inside impl block
615                         default: None,
616                     };
617                     let mut param_clone = param.clone();
618                     param_clone.kind = const_nodefault_kind;
619                     param_clone
620                 }
621             })
622             .collect();
623
624         // and similarly for where clauses
625         where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
626             match clause {
627                 ast::WherePredicate::BoundPredicate(wb) => {
628                     let span = wb.span.with_ctxt(ctxt);
629                     ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
630                         span,
631                         ..wb.clone()
632                     })
633                 }
634                 ast::WherePredicate::RegionPredicate(wr) => {
635                     let span = wr.span.with_ctxt(ctxt);
636                     ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
637                         span,
638                         ..wr.clone()
639                     })
640                 }
641                 ast::WherePredicate::EqPredicate(we) => {
642                     let span = we.span.with_ctxt(ctxt);
643                     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { span, ..we.clone() })
644                 }
645             }
646         }));
647
648         {
649             // Extra scope required here so ty_params goes out of scope before params is moved
650
651             let mut ty_params = params
652                 .iter()
653                 .filter(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
654                 .peekable();
655
656             if ty_params.peek().is_some() {
657                 let ty_param_names: Vec<Symbol> =
658                     ty_params.map(|ty_param| ty_param.ident.name).collect();
659
660                 for field_ty in field_tys {
661                     let field_ty_params = find_type_parameters(&field_ty, &ty_param_names, cx);
662
663                     for field_ty_param in field_ty_params {
664                         // if we have already handled this type, skip it
665                         if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
666                             && let [sole_segment] = &*p.segments
667                             && ty_param_names.contains(&sole_segment.ident.name)
668                         {
669                             continue;
670                         }
671                         let mut bounds: Vec<_> = self
672                             .additional_bounds
673                             .iter()
674                             .map(|p| cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)))
675                             .collect();
676
677                         // require the current trait
678                         bounds.push(cx.trait_bound(trait_path.clone()));
679
680                         let predicate = ast::WhereBoundPredicate {
681                             span: self.span,
682                             bound_generic_params: field_ty_param.bound_generic_params,
683                             bounded_ty: field_ty_param.ty,
684                             bounds,
685                         };
686
687                         let predicate = ast::WherePredicate::BoundPredicate(predicate);
688                         where_clause.predicates.push(predicate);
689                     }
690                 }
691             }
692         }
693
694         let trait_generics = Generics { params, where_clause, span };
695
696         // Create the reference to the trait.
697         let trait_ref = cx.trait_ref(trait_path);
698
699         let self_params: Vec<_> = generics
700             .params
701             .iter()
702             .map(|param| match param.kind {
703                 GenericParamKind::Lifetime { .. } => {
704                     GenericArg::Lifetime(cx.lifetime(param.ident.span.with_ctxt(ctxt), param.ident))
705                 }
706                 GenericParamKind::Type { .. } => {
707                     GenericArg::Type(cx.ty_ident(param.ident.span.with_ctxt(ctxt), param.ident))
708                 }
709                 GenericParamKind::Const { .. } => {
710                     GenericArg::Const(cx.const_ident(param.ident.span.with_ctxt(ctxt), param.ident))
711                 }
712             })
713             .collect();
714
715         // Create the type of `self`.
716         let path = cx.path_all(self.span, false, vec![type_ident], self_params);
717         let self_type = cx.ty_path(path);
718
719         let attr = cx.attr_word(sym::automatically_derived, self.span);
720         let attrs = thin_vec![attr];
721         let opt_trait_ref = Some(trait_ref);
722
723         cx.item(
724             self.span,
725             Ident::empty(),
726             attrs,
727             ast::ItemKind::Impl(Box::new(ast::Impl {
728                 unsafety: ast::Unsafe::No,
729                 polarity: ast::ImplPolarity::Positive,
730                 defaultness: ast::Defaultness::Final,
731                 constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },
732                 generics: trait_generics,
733                 of_trait: opt_trait_ref,
734                 self_ty: self_type,
735                 items: methods.into_iter().chain(associated_types).collect(),
736             })),
737         )
738     }
739
740     fn expand_struct_def(
741         &self,
742         cx: &mut ExtCtxt<'_>,
743         struct_def: &'a VariantData,
744         type_ident: Ident,
745         generics: &Generics,
746         from_scratch: bool,
747         copy_fields: bool,
748     ) -> P<ast::Item> {
749         let field_tys: Vec<P<ast::Ty>> =
750             struct_def.fields().iter().map(|field| field.ty.clone()).collect();
751
752         let methods = self
753             .methods
754             .iter()
755             .map(|method_def| {
756                 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
757                     method_def.extract_arg_details(cx, self, type_ident, generics);
758
759                 let body = if from_scratch || method_def.is_static() {
760                     method_def.expand_static_struct_method_body(
761                         cx,
762                         self,
763                         struct_def,
764                         type_ident,
765                         &nonselflike_args,
766                     )
767                 } else {
768                     method_def.expand_struct_method_body(
769                         cx,
770                         self,
771                         struct_def,
772                         type_ident,
773                         &selflike_args,
774                         &nonselflike_args,
775                         copy_fields,
776                     )
777                 };
778
779                 method_def.create_method(
780                     cx,
781                     self,
782                     type_ident,
783                     generics,
784                     explicit_self,
785                     nonself_arg_tys,
786                     body,
787                 )
788             })
789             .collect();
790
791         self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
792     }
793
794     fn expand_enum_def(
795         &self,
796         cx: &mut ExtCtxt<'_>,
797         enum_def: &'a EnumDef,
798         type_ident: Ident,
799         generics: &Generics,
800         from_scratch: bool,
801     ) -> P<ast::Item> {
802         let mut field_tys = Vec::new();
803
804         for variant in &enum_def.variants {
805             field_tys.extend(variant.data.fields().iter().map(|field| field.ty.clone()));
806         }
807
808         let methods = self
809             .methods
810             .iter()
811             .map(|method_def| {
812                 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
813                     method_def.extract_arg_details(cx, self, type_ident, generics);
814
815                 let body = if from_scratch || method_def.is_static() {
816                     method_def.expand_static_enum_method_body(
817                         cx,
818                         self,
819                         enum_def,
820                         type_ident,
821                         &nonselflike_args,
822                     )
823                 } else {
824                     method_def.expand_enum_method_body(
825                         cx,
826                         self,
827                         enum_def,
828                         type_ident,
829                         selflike_args,
830                         &nonselflike_args,
831                     )
832                 };
833
834                 method_def.create_method(
835                     cx,
836                     self,
837                     type_ident,
838                     generics,
839                     explicit_self,
840                     nonself_arg_tys,
841                     body,
842                 )
843             })
844             .collect();
845
846         self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
847     }
848 }
849
850 impl<'a> MethodDef<'a> {
851     fn call_substructure_method(
852         &self,
853         cx: &mut ExtCtxt<'_>,
854         trait_: &TraitDef<'_>,
855         type_ident: Ident,
856         nonselflike_args: &[P<Expr>],
857         fields: &SubstructureFields<'_>,
858     ) -> BlockOrExpr {
859         let span = trait_.span;
860         let substructure = Substructure { type_ident, nonselflike_args, fields };
861         let mut f = self.combine_substructure.borrow_mut();
862         let f: &mut CombineSubstructureFunc<'_> = &mut *f;
863         f(cx, span, &substructure)
864     }
865
866     fn get_ret_ty(
867         &self,
868         cx: &mut ExtCtxt<'_>,
869         trait_: &TraitDef<'_>,
870         generics: &Generics,
871         type_ident: Ident,
872     ) -> P<ast::Ty> {
873         self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
874     }
875
876     fn is_static(&self) -> bool {
877         !self.explicit_self
878     }
879
880     // The return value includes:
881     // - explicit_self: The `&self` arg, if present.
882     // - selflike_args: Expressions for `&self` (if present) and also any other
883     //   args with the same type (e.g. the `other` arg in `PartialEq::eq`).
884     // - nonselflike_args: Expressions for all the remaining args.
885     // - nonself_arg_tys: Additional information about all the args other than
886     //   `&self`.
887     fn extract_arg_details(
888         &self,
889         cx: &mut ExtCtxt<'_>,
890         trait_: &TraitDef<'_>,
891         type_ident: Ident,
892         generics: &Generics,
893     ) -> (Option<ast::ExplicitSelf>, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) {
894         let mut selflike_args = Vec::new();
895         let mut nonselflike_args = Vec::new();
896         let mut nonself_arg_tys = Vec::new();
897         let span = trait_.span;
898
899         let explicit_self = if self.explicit_self {
900             let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
901             selflike_args.push(self_expr);
902             Some(explicit_self)
903         } else {
904             None
905         };
906
907         for (ty, name) in self.nonself_args.iter() {
908             let ast_ty = ty.to_ty(cx, span, type_ident, generics);
909             let ident = Ident::new(*name, span);
910             nonself_arg_tys.push((ident, ast_ty));
911
912             let arg_expr = cx.expr_ident(span, ident);
913
914             match ty {
915                 // Selflike (`&Self`) arguments only occur in non-static methods.
916                 Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
917                 Self_ => cx.span_bug(span, "`Self` in non-return position"),
918                 _ => nonselflike_args.push(arg_expr),
919             }
920         }
921
922         (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys)
923     }
924
925     fn create_method(
926         &self,
927         cx: &mut ExtCtxt<'_>,
928         trait_: &TraitDef<'_>,
929         type_ident: Ident,
930         generics: &Generics,
931         explicit_self: Option<ast::ExplicitSelf>,
932         nonself_arg_tys: Vec<(Ident, P<ast::Ty>)>,
933         body: BlockOrExpr,
934     ) -> P<ast::AssocItem> {
935         let span = trait_.span;
936         // Create the generics that aren't for `Self`.
937         let fn_generics = self.generics.to_generics(cx, span, type_ident, generics);
938
939         let args = {
940             let self_arg = explicit_self.map(|explicit_self| {
941                 let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(span);
942                 ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident)
943             });
944             let nonself_args =
945                 nonself_arg_tys.into_iter().map(|(name, ty)| cx.param(span, name, ty));
946             self_arg.into_iter().chain(nonself_args).collect()
947         };
948
949         let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
950
951         let method_ident = Ident::new(self.name, span);
952         let fn_decl = cx.fn_decl(args, ast::FnRetTy::Ty(ret_type));
953         let body_block = body.into_block(cx, span);
954
955         let trait_lo_sp = span.shrink_to_lo();
956
957         let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
958         let defaultness = ast::Defaultness::Final;
959
960         // Create the method.
961         P(ast::AssocItem {
962             id: ast::DUMMY_NODE_ID,
963             attrs: self.attributes.clone(),
964             span,
965             vis: ast::Visibility {
966                 span: trait_lo_sp,
967                 kind: ast::VisibilityKind::Inherited,
968                 tokens: None,
969             },
970             ident: method_ident,
971             kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
972                 defaultness,
973                 sig,
974                 generics: fn_generics,
975                 body: Some(body_block),
976             })),
977             tokens: None,
978         })
979     }
980
981     /// The normal case uses field access.
982     /// ```
983     /// #[derive(PartialEq)]
984     /// # struct Dummy;
985     /// struct A { x: u8, y: u8 }
986     ///
987     /// // equivalent to:
988     /// impl PartialEq for A {
989     ///     fn eq(&self, other: &A) -> bool {
990     ///         self.x == other.x && self.y == other.y
991     ///     }
992     /// }
993     /// ```
994     /// But if the struct is `repr(packed)`, we can't use something like
995     /// `&self.x` because that might cause an unaligned ref. So for any trait
996     /// method that takes a reference, if the struct impls `Copy` then we use a
997     /// local block to force a copy:
998     /// ```
999     /// # struct A { x: u8, y: u8 }
1000     /// impl PartialEq for A {
1001     ///     fn eq(&self, other: &A) -> bool {
1002     ///         // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
1003     ///         { self.x } == { other.y } && { self.y } == { other.y }
1004     ///     }
1005     /// }
1006     /// impl Hash for A {
1007     ///     fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
1008     ///         ::core::hash::Hash::hash(&{ self.x }, state);
1009     ///         ::core::hash::Hash::hash(&{ self.y }, state)
1010     ///     }
1011     /// }
1012     /// ```
1013     /// If the struct doesn't impl `Copy`, we use the normal `&self.x`. This
1014     /// only works if the fields match the alignment required by the
1015     /// `packed(N)` attribute. (We'll get errors later on if not.)
1016     fn expand_struct_method_body<'b>(
1017         &self,
1018         cx: &mut ExtCtxt<'_>,
1019         trait_: &TraitDef<'b>,
1020         struct_def: &'b VariantData,
1021         type_ident: Ident,
1022         selflike_args: &[P<Expr>],
1023         nonselflike_args: &[P<Expr>],
1024         copy_fields: bool,
1025     ) -> BlockOrExpr {
1026         assert!(selflike_args.len() == 1 || selflike_args.len() == 2);
1027
1028         let selflike_fields =
1029             trait_.create_struct_field_access_fields(cx, selflike_args, struct_def, copy_fields);
1030         self.call_substructure_method(
1031             cx,
1032             trait_,
1033             type_ident,
1034             nonselflike_args,
1035             &Struct(struct_def, selflike_fields),
1036         )
1037     }
1038
1039     fn expand_static_struct_method_body(
1040         &self,
1041         cx: &mut ExtCtxt<'_>,
1042         trait_: &TraitDef<'_>,
1043         struct_def: &VariantData,
1044         type_ident: Ident,
1045         nonselflike_args: &[P<Expr>],
1046     ) -> BlockOrExpr {
1047         let summary = trait_.summarise_struct(cx, struct_def);
1048
1049         self.call_substructure_method(
1050             cx,
1051             trait_,
1052             type_ident,
1053             nonselflike_args,
1054             &StaticStruct(struct_def, summary),
1055         )
1056     }
1057
1058     /// ```
1059     /// #[derive(PartialEq)]
1060     /// # struct Dummy;
1061     /// enum A {
1062     ///     A1,
1063     ///     A2(i32)
1064     /// }
1065     /// ```
1066     /// is equivalent to:
1067     /// ```
1068     /// #![feature(core_intrinsics)]
1069     /// enum A {
1070     ///     A1,
1071     ///     A2(i32)
1072     /// }
1073     /// impl ::core::cmp::PartialEq for A {
1074     ///     #[inline]
1075     ///     fn eq(&self, other: &A) -> bool {
1076     ///         let __self_tag = ::core::intrinsics::discriminant_value(self);
1077     ///         let __arg1_tag = ::core::intrinsics::discriminant_value(other);
1078     ///         __self_tag == __arg1_tag &&
1079     ///             match (self, other) {
1080     ///                 (A::A2(__self_0), A::A2(__arg1_0)) =>
1081     ///                     *__self_0 == *__arg1_0,
1082     ///                 _ => true,
1083     ///             }
1084     ///     }
1085     /// }
1086     /// ```
1087     /// Creates a tag check combined with a match for a tuple of all
1088     /// `selflike_args`, with an arm for each variant with fields, possibly an
1089     /// arm for each fieldless variant (if `!unify_fieldless_variants` is not
1090     /// true), and possibly a default arm.
1091     fn expand_enum_method_body<'b>(
1092         &self,
1093         cx: &mut ExtCtxt<'_>,
1094         trait_: &TraitDef<'b>,
1095         enum_def: &'b EnumDef,
1096         type_ident: Ident,
1097         selflike_args: Vec<P<Expr>>,
1098         nonselflike_args: &[P<Expr>],
1099     ) -> BlockOrExpr {
1100         let span = trait_.span;
1101         let variants = &enum_def.variants;
1102
1103         // Traits that unify fieldless variants always use the tag(s).
1104         let uses_tags = self.unify_fieldless_variants;
1105
1106         // There is no sensible code to be generated for *any* deriving on a
1107         // zero-variant enum. So we just generate a failing expression.
1108         if variants.is_empty() {
1109             return BlockOrExpr(vec![], Some(deriving::call_unreachable(cx, span)));
1110         }
1111
1112         let prefixes = iter::once("__self".to_string())
1113             .chain(
1114                 selflike_args
1115                     .iter()
1116                     .enumerate()
1117                     .skip(1)
1118                     .map(|(arg_count, _selflike_arg)| format!("__arg{}", arg_count)),
1119             )
1120             .collect::<Vec<String>>();
1121
1122         // Build a series of let statements mapping each selflike_arg
1123         // to its discriminant value.
1124         //
1125         // e.g. for `PartialEq::eq` builds two statements:
1126         // ```
1127         // let __self_tag = ::core::intrinsics::discriminant_value(self);
1128         // let __arg1_tag = ::core::intrinsics::discriminant_value(other);
1129         // ```
1130         let get_tag_pieces = |cx: &ExtCtxt<'_>| {
1131             let tag_idents: Vec<_> = prefixes
1132                 .iter()
1133                 .map(|name| Ident::from_str_and_span(&format!("{}_tag", name), span))
1134                 .collect();
1135
1136             let mut tag_exprs: Vec<_> = tag_idents
1137                 .iter()
1138                 .map(|&ident| cx.expr_addr_of(span, cx.expr_ident(span, ident)))
1139                 .collect();
1140
1141             let self_expr = tag_exprs.remove(0);
1142             let other_selflike_exprs = tag_exprs;
1143             let tag_field = FieldInfo { span, name: None, self_expr, other_selflike_exprs };
1144
1145             let tag_let_stmts: Vec<_> = iter::zip(&tag_idents, &selflike_args)
1146                 .map(|(&ident, selflike_arg)| {
1147                     let variant_value = deriving::call_intrinsic(
1148                         cx,
1149                         span,
1150                         sym::discriminant_value,
1151                         vec![selflike_arg.clone()],
1152                     );
1153                     cx.stmt_let(span, false, ident, variant_value)
1154                 })
1155                 .collect();
1156
1157             (tag_field, tag_let_stmts)
1158         };
1159
1160         // There are some special cases involving fieldless enums where no
1161         // match is necessary.
1162         let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
1163         if all_fieldless {
1164             if uses_tags && variants.len() > 1 {
1165                 // If the type is fieldless and the trait uses the tag and
1166                 // there are multiple variants, we need just an operation on
1167                 // the tag(s).
1168                 let (tag_field, mut tag_let_stmts) = get_tag_pieces(cx);
1169                 let mut tag_check = self.call_substructure_method(
1170                     cx,
1171                     trait_,
1172                     type_ident,
1173                     nonselflike_args,
1174                     &EnumTag(tag_field, None),
1175                 );
1176                 tag_let_stmts.append(&mut tag_check.0);
1177                 return BlockOrExpr(tag_let_stmts, tag_check.1);
1178             }
1179
1180             if variants.len() == 1 {
1181                 // If there is a single variant, we don't need an operation on
1182                 // the tag(s). Just use the most degenerate result.
1183                 return self.call_substructure_method(
1184                     cx,
1185                     trait_,
1186                     type_ident,
1187                     nonselflike_args,
1188                     &EnumMatching(0, 1, &variants[0], Vec::new()),
1189                 );
1190             };
1191         }
1192
1193         // These arms are of the form:
1194         // (Variant1, Variant1, ...) => Body1
1195         // (Variant2, Variant2, ...) => Body2
1196         // ...
1197         // where each tuple has length = selflike_args.len()
1198         let mut match_arms: Vec<ast::Arm> = variants
1199             .iter()
1200             .enumerate()
1201             .filter(|&(_, v)| !(self.unify_fieldless_variants && v.data.fields().is_empty()))
1202             .map(|(index, variant)| {
1203                 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
1204                 // (see "Final wrinkle" note below for why.)
1205
1206                 let fields = trait_.create_struct_pattern_fields(cx, &variant.data, &prefixes);
1207
1208                 let sp = variant.span.with_ctxt(trait_.span.ctxt());
1209                 let variant_path = cx.path(sp, vec![type_ident, variant.ident]);
1210                 let by_ref = ByRef::No; // because enums can't be repr(packed)
1211                 let mut subpats: Vec<_> = trait_.create_struct_patterns(
1212                     cx,
1213                     variant_path,
1214                     &variant.data,
1215                     &prefixes,
1216                     by_ref,
1217                 );
1218
1219                 // `(VariantK, VariantK, ...)` or just `VariantK`.
1220                 let single_pat = if subpats.len() == 1 {
1221                     subpats.pop().unwrap()
1222                 } else {
1223                     cx.pat_tuple(span, subpats)
1224                 };
1225
1226                 // For the BodyK, we need to delegate to our caller,
1227                 // passing it an EnumMatching to indicate which case
1228                 // we are in.
1229                 //
1230                 // Now, for some given VariantK, we have built up
1231                 // expressions for referencing every field of every
1232                 // Self arg, assuming all are instances of VariantK.
1233                 // Build up code associated with such a case.
1234                 let substructure = EnumMatching(index, variants.len(), variant, fields);
1235                 let arm_expr = self
1236                     .call_substructure_method(
1237                         cx,
1238                         trait_,
1239                         type_ident,
1240                         nonselflike_args,
1241                         &substructure,
1242                     )
1243                     .into_expr(cx, span);
1244
1245                 cx.arm(span, single_pat, arm_expr)
1246             })
1247             .collect();
1248
1249         // Add a default arm to the match, if necessary.
1250         let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1251         let default = match first_fieldless {
1252             Some(v) if self.unify_fieldless_variants => {
1253                 // We need a default case that handles all the fieldless
1254                 // variants. The index and actual variant aren't meaningful in
1255                 // this case, so just use dummy values.
1256                 Some(
1257                     self.call_substructure_method(
1258                         cx,
1259                         trait_,
1260                         type_ident,
1261                         nonselflike_args,
1262                         &EnumMatching(0, variants.len(), v, Vec::new()),
1263                     )
1264                     .into_expr(cx, span),
1265                 )
1266             }
1267             _ if variants.len() > 1 && selflike_args.len() > 1 => {
1268                 // Because we know that all the arguments will match if we reach
1269                 // the match expression we add the unreachable intrinsics as the
1270                 // result of the default which should help llvm in optimizing it.
1271                 Some(deriving::call_unreachable(cx, span))
1272             }
1273             _ => None,
1274         };
1275         if let Some(arm) = default {
1276             match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
1277         }
1278
1279         // Create a match expression with one arm per discriminant plus
1280         // possibly a default arm, e.g.:
1281         //      match (self, other) {
1282         //          (Variant1, Variant1, ...) => Body1
1283         //          (Variant2, Variant2, ...) => Body2,
1284         //          ...
1285         //          _ => ::core::intrinsics::unreachable()
1286         //      }
1287         let get_match_expr = |mut selflike_args: Vec<P<Expr>>| {
1288             let match_arg = if selflike_args.len() == 1 {
1289                 selflike_args.pop().unwrap()
1290             } else {
1291                 cx.expr(span, ast::ExprKind::Tup(selflike_args))
1292             };
1293             cx.expr_match(span, match_arg, match_arms)
1294         };
1295
1296         // If the trait uses the tag and there are multiple variants, we need
1297         // to add a tag check operation before the match. Otherwise, the match
1298         // is enough.
1299         if uses_tags && variants.len() > 1 {
1300             let (tag_field, mut tag_let_stmts) = get_tag_pieces(cx);
1301
1302             // Combine a tag check with the match.
1303             let mut tag_check_plus_match = self.call_substructure_method(
1304                 cx,
1305                 trait_,
1306                 type_ident,
1307                 nonselflike_args,
1308                 &EnumTag(tag_field, Some(get_match_expr(selflike_args))),
1309             );
1310             tag_let_stmts.append(&mut tag_check_plus_match.0);
1311             BlockOrExpr(tag_let_stmts, tag_check_plus_match.1)
1312         } else {
1313             BlockOrExpr(vec![], Some(get_match_expr(selflike_args)))
1314         }
1315     }
1316
1317     fn expand_static_enum_method_body(
1318         &self,
1319         cx: &mut ExtCtxt<'_>,
1320         trait_: &TraitDef<'_>,
1321         enum_def: &EnumDef,
1322         type_ident: Ident,
1323         nonselflike_args: &[P<Expr>],
1324     ) -> BlockOrExpr {
1325         let summary = enum_def
1326             .variants
1327             .iter()
1328             .map(|v| {
1329                 let sp = v.span.with_ctxt(trait_.span.ctxt());
1330                 let summary = trait_.summarise_struct(cx, &v.data);
1331                 (v.ident, sp, summary)
1332             })
1333             .collect();
1334         self.call_substructure_method(
1335             cx,
1336             trait_,
1337             type_ident,
1338             nonselflike_args,
1339             &StaticEnum(enum_def, summary),
1340         )
1341     }
1342 }
1343
1344 // general helper methods.
1345 impl<'a> TraitDef<'a> {
1346     fn summarise_struct(&self, cx: &mut ExtCtxt<'_>, struct_def: &VariantData) -> StaticFields {
1347         let mut named_idents = Vec::new();
1348         let mut just_spans = Vec::new();
1349         for field in struct_def.fields() {
1350             let sp = field.span.with_ctxt(self.span.ctxt());
1351             match field.ident {
1352                 Some(ident) => named_idents.push((ident, sp)),
1353                 _ => just_spans.push(sp),
1354             }
1355         }
1356
1357         let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..));
1358         match (just_spans.is_empty(), named_idents.is_empty()) {
1359             (false, false) => {
1360                 cx.span_bug(self.span, "a struct with named and unnamed fields in generic `derive`")
1361             }
1362             // named fields
1363             (_, false) => Named(named_idents),
1364             // unnamed fields
1365             (false, _) => Unnamed(just_spans, is_tuple),
1366             // empty
1367             _ => Named(Vec::new()),
1368         }
1369     }
1370
1371     fn create_struct_patterns(
1372         &self,
1373         cx: &mut ExtCtxt<'_>,
1374         struct_path: ast::Path,
1375         struct_def: &'a VariantData,
1376         prefixes: &[String],
1377         by_ref: ByRef,
1378     ) -> Vec<P<ast::Pat>> {
1379         prefixes
1380             .iter()
1381             .map(|prefix| {
1382                 let pieces_iter =
1383                     struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1384                         let sp = struct_field.span.with_ctxt(self.span.ctxt());
1385                         let ident = self.mk_pattern_ident(prefix, i);
1386                         let path = ident.with_span_pos(sp);
1387                         (
1388                             sp,
1389                             struct_field.ident,
1390                             cx.pat(
1391                                 path.span,
1392                                 PatKind::Ident(
1393                                     BindingAnnotation(by_ref, Mutability::Not),
1394                                     path,
1395                                     None,
1396                                 ),
1397                             ),
1398                         )
1399                     });
1400
1401                 let struct_path = struct_path.clone();
1402                 match *struct_def {
1403                     VariantData::Struct(..) => {
1404                         let field_pats = pieces_iter
1405                             .map(|(sp, ident, pat)| {
1406                                 if ident.is_none() {
1407                                     cx.span_bug(
1408                                         sp,
1409                                         "a braced struct with unnamed fields in `derive`",
1410                                     );
1411                                 }
1412                                 ast::PatField {
1413                                     ident: ident.unwrap(),
1414                                     is_shorthand: false,
1415                                     attrs: ast::AttrVec::new(),
1416                                     id: ast::DUMMY_NODE_ID,
1417                                     span: pat.span.with_ctxt(self.span.ctxt()),
1418                                     pat,
1419                                     is_placeholder: false,
1420                                 }
1421                             })
1422                             .collect();
1423                         cx.pat_struct(self.span, struct_path, field_pats)
1424                     }
1425                     VariantData::Tuple(..) => {
1426                         let subpats = pieces_iter.map(|(_, _, subpat)| subpat).collect();
1427                         cx.pat_tuple_struct(self.span, struct_path, subpats)
1428                     }
1429                     VariantData::Unit(..) => cx.pat_path(self.span, struct_path),
1430                 }
1431             })
1432             .collect()
1433     }
1434
1435     fn create_fields<F>(&self, struct_def: &'a VariantData, mk_exprs: F) -> Vec<FieldInfo>
1436     where
1437         F: Fn(usize, &ast::FieldDef, Span) -> Vec<P<ast::Expr>>,
1438     {
1439         struct_def
1440             .fields()
1441             .iter()
1442             .enumerate()
1443             .map(|(i, struct_field)| {
1444                 // For this field, get an expr for each selflike_arg. E.g. for
1445                 // `PartialEq::eq`, one for each of `&self` and `other`.
1446                 let sp = struct_field.span.with_ctxt(self.span.ctxt());
1447                 let mut exprs: Vec<_> = mk_exprs(i, struct_field, sp);
1448                 let self_expr = exprs.remove(0);
1449                 let other_selflike_exprs = exprs;
1450                 FieldInfo {
1451                     span: sp.with_ctxt(self.span.ctxt()),
1452                     name: struct_field.ident,
1453                     self_expr,
1454                     other_selflike_exprs,
1455                 }
1456             })
1457             .collect()
1458     }
1459
1460     fn mk_pattern_ident(&self, prefix: &str, i: usize) -> Ident {
1461         Ident::from_str_and_span(&format!("{}_{}", prefix, i), self.span)
1462     }
1463
1464     fn create_struct_pattern_fields(
1465         &self,
1466         cx: &mut ExtCtxt<'_>,
1467         struct_def: &'a VariantData,
1468         prefixes: &[String],
1469     ) -> Vec<FieldInfo> {
1470         self.create_fields(struct_def, |i, _struct_field, sp| {
1471             prefixes
1472                 .iter()
1473                 .map(|prefix| {
1474                     let ident = self.mk_pattern_ident(prefix, i);
1475                     cx.expr_path(cx.path_ident(sp, ident))
1476                 })
1477                 .collect()
1478         })
1479     }
1480
1481     fn create_struct_field_access_fields(
1482         &self,
1483         cx: &mut ExtCtxt<'_>,
1484         selflike_args: &[P<Expr>],
1485         struct_def: &'a VariantData,
1486         copy_fields: bool,
1487     ) -> Vec<FieldInfo> {
1488         self.create_fields(struct_def, |i, struct_field, sp| {
1489             selflike_args
1490                 .iter()
1491                 .map(|selflike_arg| {
1492                     // Note: we must use `struct_field.span` rather than `sp` in the
1493                     // `unwrap_or_else` case otherwise the hygiene is wrong and we get
1494                     // "field `0` of struct `Point` is private" errors on tuple
1495                     // structs.
1496                     let mut field_expr = cx.expr(
1497                         sp,
1498                         ast::ExprKind::Field(
1499                             selflike_arg.clone(),
1500                             struct_field.ident.unwrap_or_else(|| {
1501                                 Ident::from_str_and_span(&i.to_string(), struct_field.span)
1502                             }),
1503                         ),
1504                     );
1505                     if copy_fields {
1506                         field_expr = cx.expr_block(
1507                             cx.block(struct_field.span, vec![cx.stmt_expr(field_expr)]),
1508                         );
1509                     }
1510                     cx.expr_addr_of(sp, field_expr)
1511                 })
1512                 .collect()
1513         })
1514     }
1515 }
1516
1517 /// The function passed to `cs_fold` is called repeatedly with a value of this
1518 /// type. It describes one part of the code generation. The result is always an
1519 /// expression.
1520 pub enum CsFold<'a> {
1521     /// The basic case: a field expression for one or more selflike args. E.g.
1522     /// for `PartialEq::eq` this is something like `self.x == other.x`.
1523     Single(&'a FieldInfo),
1524
1525     /// The combination of two field expressions. E.g. for `PartialEq::eq` this
1526     /// is something like `<field1 equality> && <field2 equality>`.
1527     Combine(Span, P<Expr>, P<Expr>),
1528
1529     // The fallback case for a struct or enum variant with no fields.
1530     Fieldless,
1531 }
1532
1533 /// Folds over fields, combining the expressions for each field in a sequence.
1534 /// Statics may not be folded over.
1535 pub fn cs_fold<F>(
1536     use_foldl: bool,
1537     cx: &mut ExtCtxt<'_>,
1538     trait_span: Span,
1539     substructure: &Substructure<'_>,
1540     mut f: F,
1541 ) -> P<Expr>
1542 where
1543     F: FnMut(&mut ExtCtxt<'_>, CsFold<'_>) -> P<Expr>,
1544 {
1545     match substructure.fields {
1546         EnumMatching(.., all_fields) | Struct(_, all_fields) => {
1547             if all_fields.is_empty() {
1548                 return f(cx, CsFold::Fieldless);
1549             }
1550
1551             let (base_field, rest) = if use_foldl {
1552                 all_fields.split_first().unwrap()
1553             } else {
1554                 all_fields.split_last().unwrap()
1555             };
1556
1557             let base_expr = f(cx, CsFold::Single(base_field));
1558
1559             let op = |old, field: &FieldInfo| {
1560                 let new = f(cx, CsFold::Single(field));
1561                 f(cx, CsFold::Combine(field.span, old, new))
1562             };
1563
1564             if use_foldl {
1565                 rest.iter().fold(base_expr, op)
1566             } else {
1567                 rest.iter().rfold(base_expr, op)
1568             }
1569         }
1570         EnumTag(tag_field, match_expr) => {
1571             let tag_check_expr = f(cx, CsFold::Single(tag_field));
1572             if let Some(match_expr) = match_expr {
1573                 if use_foldl {
1574                     f(cx, CsFold::Combine(trait_span, tag_check_expr, match_expr.clone()))
1575                 } else {
1576                     f(cx, CsFold::Combine(trait_span, match_expr.clone(), tag_check_expr))
1577                 }
1578             } else {
1579                 tag_check_expr
1580             }
1581         }
1582         StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span, "static function in `derive`"),
1583     }
1584 }