]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
Rollup merge of #76891 - lcnr:less-ref, r=ecstatic-morse
[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 //! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments
25 //!   are not the same variant (e.g., `None`, `Some(1)` and `None`).
26 //! - `StaticEnum` and `StaticStruct` for static methods, where the type
27 //!   being derived upon is either an enum or struct respectively. (Any
28 //!   argument with type Self is just grouped among the non-self
29 //!   arguments.)
30 //!
31 //! In the first two cases, the values from the corresponding fields in
32 //! all the arguments are grouped together. For `EnumNonMatchingCollapsed`
33 //! this isn't possible (different variants have different fields), so the
34 //! fields are inaccessible. (Previous versions of the deriving infrastructure
35 //! had a way to expand into code that could access them, at the cost of
36 //! generating exponential amounts of code; see issue #15375). There are no
37 //! fields with values in the static cases, so these are treated entirely
38 //! differently.
39 //!
40 //! The non-static cases have `Option<ident>` in several places associated
41 //! with field `expr`s. This represents the name of the field it is
42 //! associated with. It is only not `None` when the associated field has
43 //! an identifier in the source code. For example, the `x`s in the
44 //! following snippet
45 //!
46 //! ```rust
47 //! # #![allow(dead_code)]
48 //! struct A { x : i32 }
49 //!
50 //! struct B(i32);
51 //!
52 //! enum C {
53 //!     C0(i32),
54 //!     C1 { x: i32 }
55 //! }
56 //! ```
57 //!
58 //! The `i32`s in `B` and `C0` don't have an identifier, so the
59 //! `Option<ident>`s would be `None` for them.
60 //!
61 //! In the static cases, the structure is summarized, either into the just
62 //! spans of the fields or a list of spans and the field idents (for tuple
63 //! structs and record structs, respectively), or a list of these, for
64 //! enums (one for each variant). For empty struct and empty enum
65 //! variants, it is represented as a count of 0.
66 //!
67 //! # "`cs`" functions
68 //!
69 //! The `cs_...` functions ("combine substructure) are designed to
70 //! make life easier by providing some pre-made recipes for common
71 //! threads; mostly calling the function being derived on all the
72 //! arguments and then combining them back together in some way (or
73 //! letting the user chose that). They are not meant to be the only
74 //! way to handle the structures that this code creates.
75 //!
76 //! # Examples
77 //!
78 //! The following simplified `PartialEq` is used for in-code examples:
79 //!
80 //! ```rust
81 //! trait PartialEq {
82 //!     fn eq(&self, other: &Self) -> bool;
83 //! }
84 //! impl PartialEq for i32 {
85 //!     fn eq(&self, other: &i32) -> bool {
86 //!         *self == *other
87 //!     }
88 //! }
89 //! ```
90 //!
91 //! Some examples of the values of `SubstructureFields` follow, using the
92 //! above `PartialEq`, `A`, `B` and `C`.
93 //!
94 //! ## Structs
95 //!
96 //! When generating the `expr` for the `A` impl, the `SubstructureFields` is
97 //!
98 //! ```{.text}
99 //! Struct(vec![FieldInfo {
100 //!            span: <span of x>
101 //!            name: Some(<ident of x>),
102 //!            self_: <expr for &self.x>,
103 //!            other: vec![<expr for &other.x]
104 //!          }])
105 //! ```
106 //!
107 //! For the `B` impl, called with `B(a)` and `B(b)`,
108 //!
109 //! ```{.text}
110 //! Struct(vec![FieldInfo {
111 //!           span: <span of `i32`>,
112 //!           name: None,
113 //!           self_: <expr for &a>
114 //!           other: vec![<expr for &b>]
115 //!          }])
116 //! ```
117 //!
118 //! ## Enums
119 //!
120 //! When generating the `expr` for a call with `self == C0(a)` and `other
121 //! == C0(b)`, the SubstructureFields is
122 //!
123 //! ```{.text}
124 //! EnumMatching(0, <ast::Variant for C0>,
125 //!              vec![FieldInfo {
126 //!                 span: <span of i32>
127 //!                 name: None,
128 //!                 self_: <expr for &a>,
129 //!                 other: vec![<expr for &b>]
130 //!               }])
131 //! ```
132 //!
133 //! For `C1 {x}` and `C1 {x}`,
134 //!
135 //! ```{.text}
136 //! EnumMatching(1, <ast::Variant for C1>,
137 //!              vec![FieldInfo {
138 //!                 span: <span of x>
139 //!                 name: Some(<ident of x>),
140 //!                 self_: <expr for &self.x>,
141 //!                 other: vec![<expr for &other.x>]
142 //!                }])
143 //! ```
144 //!
145 //! For `C0(a)` and `C1 {x}` ,
146 //!
147 //! ```{.text}
148 //! EnumNonMatchingCollapsed(
149 //!     vec![<ident of self>, <ident of __arg_1>],
150 //!     &[<ast::Variant for C0>, <ast::Variant for C1>],
151 //!     &[<ident for self index value>, <ident of __arg_1 index value>])
152 //! ```
153 //!
154 //! It is the same for when the arguments are flipped to `C1 {x}` and
155 //! `C0(a)`; the only difference is what the values of the identifiers
156 //! <ident for self index value> and <ident of __arg_1 index value> will
157 //! be in the generated code.
158 //!
159 //! `EnumNonMatchingCollapsed` deliberately provides far less information
160 //! than is generally available for a given pair of variants; see #15375
161 //! for discussion.
162 //!
163 //! ## Static
164 //!
165 //! A static method on the types above would result in,
166 //!
167 //! ```{.text}
168 //! StaticStruct(<ast::VariantData of A>, Named(vec![(<ident of x>, <span of x>)]))
169 //!
170 //! StaticStruct(<ast::VariantData of B>, Unnamed(vec![<span of x>]))
171 //!
172 //! StaticEnum(<ast::EnumDef of C>,
173 //!            vec![(<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])),
174 //!                 (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)]))])
175 //! ```
176
177 pub use StaticFields::*;
178 pub use SubstructureFields::*;
179
180 use std::cell::RefCell;
181 use std::iter;
182 use std::vec;
183
184 use rustc_ast::ptr::P;
185 use rustc_ast::{self as ast, BinOpKind, EnumDef, Expr, Generics, PatKind};
186 use rustc_ast::{GenericArg, GenericParamKind, VariantData};
187 use rustc_attr as attr;
188 use rustc_data_structures::map_in_place::MapInPlace;
189 use rustc_expand::base::{Annotatable, ExtCtxt};
190 use rustc_span::symbol::{kw, sym, Ident, Symbol};
191 use rustc_span::Span;
192
193 use ty::{Bounds, Path, Ptr, PtrTy, Self_, Ty};
194
195 use crate::deriving;
196
197 pub mod ty;
198
199 pub struct TraitDef<'a> {
200     /// The span for the current #[derive(Foo)] header.
201     pub span: Span,
202
203     pub attributes: Vec<ast::Attribute>,
204
205     /// Path of the trait, including any type parameters
206     pub path: Path,
207
208     /// Additional bounds required of any type parameters of the type,
209     /// other than the current trait
210     pub additional_bounds: Vec<Ty>,
211
212     /// Any extra lifetimes and/or bounds, e.g., `D: serialize::Decoder`
213     pub generics: Bounds,
214
215     /// Is it an `unsafe` trait?
216     pub is_unsafe: bool,
217
218     /// Can this trait be derived for unions?
219     pub supports_unions: bool,
220
221     pub methods: Vec<MethodDef<'a>>,
222
223     pub associated_types: Vec<(Ident, Ty)>,
224 }
225
226 pub struct MethodDef<'a> {
227     /// name of the method
228     pub name: Symbol,
229     /// List of generics, e.g., `R: rand::Rng`
230     pub generics: Bounds,
231
232     /// Whether there is a self argument (outer Option) i.e., whether
233     /// this is a static function, and whether it is a pointer (inner
234     /// Option)
235     pub explicit_self: Option<Option<PtrTy>>,
236
237     /// Arguments other than the self argument
238     pub args: Vec<(Ty, Symbol)>,
239
240     /// Returns type
241     pub ret_ty: Ty,
242
243     pub attributes: Vec<ast::Attribute>,
244
245     // Is it an `unsafe fn`?
246     pub is_unsafe: bool,
247
248     /// Can we combine fieldless variants for enums into a single match arm?
249     pub unify_fieldless_variants: bool,
250
251     pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
252 }
253
254 /// All the data about the data structure/method being derived upon.
255 pub struct Substructure<'a> {
256     /// ident of self
257     pub type_ident: Ident,
258     /// ident of the method
259     pub method_ident: Ident,
260     /// dereferenced access to any `Self_` or `Ptr(Self_, _)` arguments
261     pub self_args: &'a [P<Expr>],
262     /// verbatim access to any other arguments
263     pub nonself_args: &'a [P<Expr>],
264     pub fields: &'a SubstructureFields<'a>,
265 }
266
267 /// Summary of the relevant parts of a struct/enum field.
268 pub struct FieldInfo<'a> {
269     pub span: Span,
270     /// None for tuple structs/normal enum variants, Some for normal
271     /// structs/struct enum variants.
272     pub name: Option<Ident>,
273     /// The expression corresponding to this field of `self`
274     /// (specifically, a reference to it).
275     pub self_: P<Expr>,
276     /// The expressions corresponding to references to this field in
277     /// the other `Self` arguments.
278     pub other: Vec<P<Expr>>,
279     /// The attributes on the field
280     pub attrs: &'a [ast::Attribute],
281 }
282
283 /// Fields for a static method
284 pub enum StaticFields {
285     /// Tuple and unit structs/enum variants like this.
286     Unnamed(Vec<Span>, bool /*is tuple*/),
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(&'a ast::VariantData, Vec<FieldInfo<'a>>),
294     /// Matching variants of the enum: variant index, variant count, ast::Variant,
295     /// fields: the field name is only non-`None` in the case of a struct
296     /// variant.
297     EnumMatching(usize, usize, &'a ast::Variant, Vec<FieldInfo<'a>>),
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 [ast::Variant], &'a [Ident]),
306
307     /// A static method where `Self` is a struct.
308     StaticStruct(&'a ast::VariantData, StaticFields),
309     /// A static method where `Self` is an enum.
310     StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
311 }
312
313 /// Combine the values of all the fields together. The last argument is
314 /// all the fields of all the structures.
315 pub type CombineSubstructureFunc<'a> =
316     Box<dyn FnMut(&mut ExtCtxt<'_>, Span, &Substructure<'_>) -> P<Expr> + 'a>;
317
318 /// Deal with non-matching enum variants. The tuple is a list of
319 /// identifiers (one for each `Self` argument, which could be any of the
320 /// variants since they have been collapsed together) and the identifiers
321 /// holding the variant index value for each of the `Self` arguments. The
322 /// last argument is all the non-`Self` args of the method being derived.
323 pub type EnumNonMatchCollapsedFunc<'a> =
324     Box<dyn FnMut(&mut ExtCtxt<'_>, Span, (&[Ident], &[Ident]), &[P<Expr>]) -> P<Expr> + 'a>;
325
326 pub fn combine_substructure(
327     f: CombineSubstructureFunc<'_>,
328 ) -> RefCell<CombineSubstructureFunc<'_>> {
329     RefCell::new(f)
330 }
331
332 /// This method helps to extract all the type parameters referenced from a
333 /// type. For a type parameter `<T>`, it looks for either a `TyPath` that
334 /// is not global and starts with `T`, or a `TyQPath`.
335 fn find_type_parameters(
336     ty: &ast::Ty,
337     ty_param_names: &[Symbol],
338     cx: &ExtCtxt<'_>,
339 ) -> Vec<P<ast::Ty>> {
340     use rustc_ast::visit;
341
342     struct Visitor<'a, 'b> {
343         cx: &'a ExtCtxt<'b>,
344         ty_param_names: &'a [Symbol],
345         types: Vec<P<ast::Ty>>,
346     }
347
348     impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
349         fn visit_ty(&mut self, ty: &'a ast::Ty) {
350             if let ast::TyKind::Path(_, ref path) = ty.kind {
351                 if let Some(segment) = path.segments.first() {
352                     if self.ty_param_names.contains(&segment.ident.name) {
353                         self.types.push(P(ty.clone()));
354                     }
355                 }
356             }
357
358             visit::walk_ty(self, ty)
359         }
360
361         fn visit_mac(&mut self, mac: &ast::MacCall) {
362             self.cx.span_err(mac.span(), "`derive` cannot be used on items with type macros");
363         }
364     }
365
366     let mut visitor = Visitor { cx, ty_param_names, types: Vec::new() };
367     visit::Visitor::visit_ty(&mut visitor, ty);
368
369     visitor.types
370 }
371
372 impl<'a> TraitDef<'a> {
373     pub fn expand(
374         self,
375         cx: &mut ExtCtxt<'_>,
376         mitem: &ast::MetaItem,
377         item: &'a Annotatable,
378         push: &mut dyn FnMut(Annotatable),
379     ) {
380         self.expand_ext(cx, mitem, item, push, false);
381     }
382
383     pub fn expand_ext(
384         self,
385         cx: &mut ExtCtxt<'_>,
386         mitem: &ast::MetaItem,
387         item: &'a Annotatable,
388         push: &mut dyn FnMut(Annotatable),
389         from_scratch: bool,
390     ) {
391         match *item {
392             Annotatable::Item(ref item) => {
393                 let is_packed = item.attrs.iter().any(|attr| {
394                     for r in attr::find_repr_attrs(&cx.sess, attr) {
395                         if let attr::ReprPacked(_) = r {
396                             return true;
397                         }
398                     }
399                     false
400                 });
401                 let has_no_type_params = match item.kind {
402                     ast::ItemKind::Struct(_, ref generics)
403                     | ast::ItemKind::Enum(_, ref generics)
404                     | ast::ItemKind::Union(_, ref generics) => {
405                         !generics.params.iter().any(|param| match param.kind {
406                             ast::GenericParamKind::Type { .. } => true,
407                             _ => false,
408                         })
409                     }
410                     _ => {
411                         // Non-ADT derive is an error, but it should have been
412                         // set earlier; see
413                         // librustc_expand/expand.rs:MacroExpander::fully_expand_fragment()
414                         // librustc_expand/base.rs:Annotatable::derive_allowed()
415                         return;
416                     }
417                 };
418                 let container_id = cx.current_expansion.id.expn_data().parent;
419                 let always_copy = has_no_type_params && cx.resolver.has_derive_copy(container_id);
420                 let use_temporaries = is_packed && always_copy;
421
422                 let newitem = match item.kind {
423                     ast::ItemKind::Struct(ref struct_def, ref generics) => self.expand_struct_def(
424                         cx,
425                         &struct_def,
426                         item.ident,
427                         generics,
428                         from_scratch,
429                         use_temporaries,
430                     ),
431                     ast::ItemKind::Enum(ref enum_def, ref generics) => {
432                         // We ignore `use_temporaries` here, because
433                         // `repr(packed)` enums cause an error later on.
434                         //
435                         // This can only cause further compilation errors
436                         // downstream in blatantly illegal code, so it
437                         // is fine.
438                         self.expand_enum_def(cx, enum_def, item.ident, generics, from_scratch)
439                     }
440                     ast::ItemKind::Union(ref struct_def, ref generics) => {
441                         if self.supports_unions {
442                             self.expand_struct_def(
443                                 cx,
444                                 &struct_def,
445                                 item.ident,
446                                 generics,
447                                 from_scratch,
448                                 use_temporaries,
449                             )
450                         } else {
451                             cx.span_err(mitem.span, "this trait cannot be derived for unions");
452                             return;
453                         }
454                     }
455                     _ => unreachable!(),
456                 };
457                 // Keep the lint attributes of the previous item to control how the
458                 // generated implementations are linted
459                 let mut attrs = newitem.attrs.clone();
460                 attrs.extend(
461                     item.attrs
462                         .iter()
463                         .filter(|a| {
464                             [
465                                 sym::allow,
466                                 sym::warn,
467                                 sym::deny,
468                                 sym::forbid,
469                                 sym::stable,
470                                 sym::unstable,
471                             ]
472                             .contains(&a.name_or_empty())
473                         })
474                         .cloned(),
475                 );
476                 push(Annotatable::Item(P(ast::Item { attrs, ..(*newitem).clone() })))
477             }
478             _ => {
479                 // Non-Item derive is an error, but it should have been
480                 // set earlier; see
481                 // librustc_expand/expand.rs:MacroExpander::fully_expand_fragment()
482                 // librustc_expand/base.rs:Annotatable::derive_allowed()
483             }
484         }
485     }
486
487     /// Given that we are deriving a trait `DerivedTrait` for a type like:
488     ///
489     /// ```ignore (only-for-syntax-highlight)
490     /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z> where C: WhereTrait {
491     ///     a: A,
492     ///     b: B::Item,
493     ///     b1: <B as DeclaredTrait>::Item,
494     ///     c1: <C as WhereTrait>::Item,
495     ///     c2: Option<<C as WhereTrait>::Item>,
496     ///     ...
497     /// }
498     /// ```
499     ///
500     /// create an impl like:
501     ///
502     /// ```ignore (only-for-syntax-highlight)
503     /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ... Z> where
504     ///     C:                       WhereTrait,
505     ///     A: DerivedTrait + B1 + ... + BN,
506     ///     B: DerivedTrait + B1 + ... + BN,
507     ///     C: DerivedTrait + B1 + ... + BN,
508     ///     B::Item:                 DerivedTrait + B1 + ... + BN,
509     ///     <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
510     ///     ...
511     /// {
512     ///     ...
513     /// }
514     /// ```
515     ///
516     /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
517     /// therefore does not get bound by the derived trait.
518     fn create_derived_impl(
519         &self,
520         cx: &mut ExtCtxt<'_>,
521         type_ident: Ident,
522         generics: &Generics,
523         field_tys: Vec<P<ast::Ty>>,
524         methods: Vec<P<ast::AssocItem>>,
525     ) -> P<ast::Item> {
526         let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
527
528         // Transform associated types from `deriving::ty::Ty` into `ast::AssocItem`
529         let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
530             P(ast::AssocItem {
531                 id: ast::DUMMY_NODE_ID,
532                 span: self.span,
533                 ident,
534                 vis: ast::Visibility {
535                     span: self.span.shrink_to_lo(),
536                     kind: ast::VisibilityKind::Inherited,
537                     tokens: None,
538                 },
539                 attrs: Vec::new(),
540                 kind: ast::AssocItemKind::TyAlias(
541                     ast::Defaultness::Final,
542                     Generics::default(),
543                     Vec::new(),
544                     Some(type_def.to_ty(cx, self.span, type_ident, generics)),
545                 ),
546                 tokens: None,
547             })
548         });
549
550         let Generics { mut params, mut where_clause, span } =
551             self.generics.to_generics(cx, self.span, type_ident, generics);
552
553         // Create the generic parameters
554         params.extend(generics.params.iter().map(|param| match param.kind {
555             GenericParamKind::Lifetime { .. } => param.clone(),
556             GenericParamKind::Type { .. } => {
557                 // I don't think this can be moved out of the loop, since
558                 // a GenericBound requires an ast id
559                 let bounds: Vec<_> =
560                     // extra restrictions on the generics parameters to the
561                     // type being derived upon
562                     self.additional_bounds.iter().map(|p| {
563                         cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))
564                     }).chain(
565                         // require the current trait
566                         iter::once(cx.trait_bound(trait_path.clone()))
567                     ).chain(
568                         // also add in any bounds from the declaration
569                         param.bounds.iter().cloned()
570                     ).collect();
571
572                 cx.typaram(self.span, param.ident, vec![], bounds, None)
573             }
574             GenericParamKind::Const { .. } => param.clone(),
575         }));
576
577         // and similarly for where clauses
578         where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
579             match *clause {
580                 ast::WherePredicate::BoundPredicate(ref wb) => {
581                     ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
582                         span: self.span,
583                         bound_generic_params: wb.bound_generic_params.clone(),
584                         bounded_ty: wb.bounded_ty.clone(),
585                         bounds: wb.bounds.to_vec(),
586                     })
587                 }
588                 ast::WherePredicate::RegionPredicate(ref rb) => {
589                     ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
590                         span: self.span,
591                         lifetime: rb.lifetime,
592                         bounds: rb.bounds.to_vec(),
593                     })
594                 }
595                 ast::WherePredicate::EqPredicate(ref we) => {
596                     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
597                         id: ast::DUMMY_NODE_ID,
598                         span: self.span,
599                         lhs_ty: we.lhs_ty.clone(),
600                         rhs_ty: we.rhs_ty.clone(),
601                     })
602                 }
603             }
604         }));
605
606         {
607             // Extra scope required here so ty_params goes out of scope before params is moved
608
609             let mut ty_params = params
610                 .iter()
611                 .filter_map(|param| match param.kind {
612                     ast::GenericParamKind::Type { .. } => Some(param),
613                     _ => None,
614                 })
615                 .peekable();
616
617             if ty_params.peek().is_some() {
618                 let ty_param_names: Vec<Symbol> =
619                     ty_params.map(|ty_param| ty_param.ident.name).collect();
620
621                 for field_ty in field_tys {
622                     let tys = find_type_parameters(&field_ty, &ty_param_names, cx);
623
624                     for ty in tys {
625                         // if we have already handled this type, skip it
626                         if let ast::TyKind::Path(_, ref p) = ty.kind {
627                             if p.segments.len() == 1
628                                 && ty_param_names.contains(&p.segments[0].ident.name)
629                             {
630                                 continue;
631                             };
632                         }
633                         let mut bounds: Vec<_> = self
634                             .additional_bounds
635                             .iter()
636                             .map(|p| cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)))
637                             .collect();
638
639                         // require the current trait
640                         bounds.push(cx.trait_bound(trait_path.clone()));
641
642                         let predicate = ast::WhereBoundPredicate {
643                             span: self.span,
644                             bound_generic_params: Vec::new(),
645                             bounded_ty: ty,
646                             bounds,
647                         };
648
649                         let predicate = ast::WherePredicate::BoundPredicate(predicate);
650                         where_clause.predicates.push(predicate);
651                     }
652                 }
653             }
654         }
655
656         let trait_generics = Generics { params, where_clause, span };
657
658         // Create the reference to the trait.
659         let trait_ref = cx.trait_ref(trait_path);
660
661         let self_params: Vec<_> = generics
662             .params
663             .iter()
664             .map(|param| match param.kind {
665                 GenericParamKind::Lifetime { .. } => {
666                     GenericArg::Lifetime(cx.lifetime(self.span, param.ident))
667                 }
668                 GenericParamKind::Type { .. } => {
669                     GenericArg::Type(cx.ty_ident(self.span, param.ident))
670                 }
671                 GenericParamKind::Const { .. } => {
672                     GenericArg::Const(cx.const_ident(self.span, param.ident))
673                 }
674             })
675             .collect();
676
677         // Create the type of `self`.
678         let path = cx.path_all(self.span, false, vec![type_ident], self_params);
679         let self_type = cx.ty_path(path);
680
681         let attr = cx.attribute(cx.meta_word(self.span, sym::automatically_derived));
682         // Just mark it now since we know that it'll end up used downstream
683         cx.sess.mark_attr_used(&attr);
684         let opt_trait_ref = Some(trait_ref);
685         let unused_qual = {
686             let word = rustc_ast::attr::mk_nested_word_item(Ident::new(
687                 sym::unused_qualifications,
688                 self.span,
689             ));
690             let list = rustc_ast::attr::mk_list_item(Ident::new(sym::allow, self.span), vec![word]);
691             cx.attribute(list)
692         };
693
694         let mut a = vec![attr, unused_qual];
695         a.extend(self.attributes.iter().cloned());
696
697         let unsafety = if self.is_unsafe { ast::Unsafe::Yes(self.span) } else { ast::Unsafe::No };
698
699         cx.item(
700             self.span,
701             Ident::invalid(),
702             a,
703             ast::ItemKind::Impl {
704                 unsafety,
705                 polarity: ast::ImplPolarity::Positive,
706                 defaultness: ast::Defaultness::Final,
707                 constness: ast::Const::No,
708                 generics: trait_generics,
709                 of_trait: opt_trait_ref,
710                 self_ty: self_type,
711                 items: methods.into_iter().chain(associated_types).collect(),
712             },
713         )
714     }
715
716     fn expand_struct_def(
717         &self,
718         cx: &mut ExtCtxt<'_>,
719         struct_def: &'a VariantData,
720         type_ident: Ident,
721         generics: &Generics,
722         from_scratch: bool,
723         use_temporaries: bool,
724     ) -> P<ast::Item> {
725         let field_tys: Vec<P<ast::Ty>> =
726             struct_def.fields().iter().map(|field| field.ty.clone()).collect();
727
728         let methods = self
729             .methods
730             .iter()
731             .map(|method_def| {
732                 let (explicit_self, self_args, nonself_args, tys) =
733                     method_def.split_self_nonself_args(cx, self, type_ident, generics);
734
735                 let body = if from_scratch || method_def.is_static() {
736                     method_def.expand_static_struct_method_body(
737                         cx,
738                         self,
739                         struct_def,
740                         type_ident,
741                         &self_args[..],
742                         &nonself_args[..],
743                     )
744                 } else {
745                     method_def.expand_struct_method_body(
746                         cx,
747                         self,
748                         struct_def,
749                         type_ident,
750                         &self_args[..],
751                         &nonself_args[..],
752                         use_temporaries,
753                     )
754                 };
755
756                 method_def.create_method(cx, self, type_ident, generics, explicit_self, tys, body)
757             })
758             .collect();
759
760         self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
761     }
762
763     fn expand_enum_def(
764         &self,
765         cx: &mut ExtCtxt<'_>,
766         enum_def: &'a EnumDef,
767         type_ident: Ident,
768         generics: &Generics,
769         from_scratch: bool,
770     ) -> P<ast::Item> {
771         let mut field_tys = Vec::new();
772
773         for variant in &enum_def.variants {
774             field_tys.extend(variant.data.fields().iter().map(|field| field.ty.clone()));
775         }
776
777         let methods = self
778             .methods
779             .iter()
780             .map(|method_def| {
781                 let (explicit_self, self_args, nonself_args, tys) =
782                     method_def.split_self_nonself_args(cx, self, type_ident, generics);
783
784                 let body = if from_scratch || method_def.is_static() {
785                     method_def.expand_static_enum_method_body(
786                         cx,
787                         self,
788                         enum_def,
789                         type_ident,
790                         &self_args[..],
791                         &nonself_args[..],
792                     )
793                 } else {
794                     method_def.expand_enum_method_body(
795                         cx,
796                         self,
797                         enum_def,
798                         type_ident,
799                         self_args,
800                         &nonself_args[..],
801                     )
802                 };
803
804                 method_def.create_method(cx, self, type_ident, generics, explicit_self, tys, body)
805             })
806             .collect();
807
808         self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
809     }
810 }
811
812 impl<'a> MethodDef<'a> {
813     fn call_substructure_method(
814         &self,
815         cx: &mut ExtCtxt<'_>,
816         trait_: &TraitDef<'_>,
817         type_ident: Ident,
818         self_args: &[P<Expr>],
819         nonself_args: &[P<Expr>],
820         fields: &SubstructureFields<'_>,
821     ) -> P<Expr> {
822         let substructure = Substructure {
823             type_ident,
824             method_ident: Ident::new(self.name, trait_.span),
825             self_args,
826             nonself_args,
827             fields,
828         };
829         let mut f = self.combine_substructure.borrow_mut();
830         let f: &mut CombineSubstructureFunc<'_> = &mut *f;
831         f(cx, trait_.span, &substructure)
832     }
833
834     fn get_ret_ty(
835         &self,
836         cx: &mut ExtCtxt<'_>,
837         trait_: &TraitDef<'_>,
838         generics: &Generics,
839         type_ident: Ident,
840     ) -> P<ast::Ty> {
841         self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
842     }
843
844     fn is_static(&self) -> bool {
845         self.explicit_self.is_none()
846     }
847
848     fn split_self_nonself_args(
849         &self,
850         cx: &mut ExtCtxt<'_>,
851         trait_: &TraitDef<'_>,
852         type_ident: Ident,
853         generics: &Generics,
854     ) -> (Option<ast::ExplicitSelf>, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) {
855         let mut self_args = Vec::new();
856         let mut nonself_args = Vec::new();
857         let mut arg_tys = Vec::new();
858         let mut nonstatic = false;
859
860         let ast_explicit_self = self.explicit_self.as_ref().map(|self_ptr| {
861             let (self_expr, explicit_self) = ty::get_explicit_self(cx, trait_.span, self_ptr);
862
863             self_args.push(self_expr);
864             nonstatic = true;
865
866             explicit_self
867         });
868
869         for (ty, name) in self.args.iter() {
870             let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics);
871             let ident = Ident::new(*name, trait_.span);
872             arg_tys.push((ident, ast_ty));
873
874             let arg_expr = cx.expr_ident(trait_.span, ident);
875
876             match *ty {
877                 // for static methods, just treat any Self
878                 // arguments as a normal arg
879                 Self_ if nonstatic => {
880                     self_args.push(arg_expr);
881                 }
882                 Ptr(ref ty, _) if (if let Self_ = **ty { true } else { false }) && nonstatic => {
883                     self_args.push(cx.expr_deref(trait_.span, arg_expr))
884                 }
885                 _ => {
886                     nonself_args.push(arg_expr);
887                 }
888             }
889         }
890
891         (ast_explicit_self, self_args, nonself_args, arg_tys)
892     }
893
894     fn create_method(
895         &self,
896         cx: &mut ExtCtxt<'_>,
897         trait_: &TraitDef<'_>,
898         type_ident: Ident,
899         generics: &Generics,
900         explicit_self: Option<ast::ExplicitSelf>,
901         arg_types: Vec<(Ident, P<ast::Ty>)>,
902         body: P<Expr>,
903     ) -> P<ast::AssocItem> {
904         // Create the generics that aren't for `Self`.
905         let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics);
906
907         let args = {
908             let self_args = explicit_self.map(|explicit_self| {
909                 let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(trait_.span);
910                 ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident)
911             });
912             let nonself_args =
913                 arg_types.into_iter().map(|(name, ty)| cx.param(trait_.span, name, ty));
914             self_args.into_iter().chain(nonself_args).collect()
915         };
916
917         let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
918
919         let method_ident = Ident::new(self.name, trait_.span);
920         let fn_decl = cx.fn_decl(args, ast::FnRetTy::Ty(ret_type));
921         let body_block = cx.block_expr(body);
922
923         let unsafety = if self.is_unsafe { ast::Unsafe::Yes(trait_.span) } else { ast::Unsafe::No };
924
925         let trait_lo_sp = trait_.span.shrink_to_lo();
926
927         let sig = ast::FnSig {
928             header: ast::FnHeader { unsafety, ext: ast::Extern::None, ..ast::FnHeader::default() },
929             decl: fn_decl,
930             span: trait_.span,
931         };
932         let def = ast::Defaultness::Final;
933
934         // Create the method.
935         P(ast::AssocItem {
936             id: ast::DUMMY_NODE_ID,
937             attrs: self.attributes.clone(),
938             span: trait_.span,
939             vis: ast::Visibility {
940                 span: trait_lo_sp,
941                 kind: ast::VisibilityKind::Inherited,
942                 tokens: None,
943             },
944             ident: method_ident,
945             kind: ast::AssocItemKind::Fn(def, sig, fn_generics, Some(body_block)),
946             tokens: None,
947         })
948     }
949
950     /// ```
951     /// #[derive(PartialEq)]
952     /// # struct Dummy;
953     /// struct A { x: i32, y: i32 }
954     ///
955     /// // equivalent to:
956     /// impl PartialEq for A {
957     ///     fn eq(&self, other: &A) -> bool {
958     ///         match *self {
959     ///             A {x: ref __self_0_0, y: ref __self_0_1} => {
960     ///                 match *other {
961     ///                     A {x: ref __self_1_0, y: ref __self_1_1} => {
962     ///                         __self_0_0.eq(__self_1_0) && __self_0_1.eq(__self_1_1)
963     ///                     }
964     ///                 }
965     ///             }
966     ///         }
967     ///     }
968     /// }
969     ///
970     /// // or if A is repr(packed) - note fields are matched by-value
971     /// // instead of by-reference.
972     /// impl PartialEq for A {
973     ///     fn eq(&self, other: &A) -> bool {
974     ///         match *self {
975     ///             A {x: __self_0_0, y: __self_0_1} => {
976     ///                 match other {
977     ///                     A {x: __self_1_0, y: __self_1_1} => {
978     ///                         __self_0_0.eq(&__self_1_0) && __self_0_1.eq(&__self_1_1)
979     ///                     }
980     ///                 }
981     ///             }
982     ///         }
983     ///     }
984     /// }
985     /// ```
986     fn expand_struct_method_body<'b>(
987         &self,
988         cx: &mut ExtCtxt<'_>,
989         trait_: &TraitDef<'b>,
990         struct_def: &'b VariantData,
991         type_ident: Ident,
992         self_args: &[P<Expr>],
993         nonself_args: &[P<Expr>],
994         use_temporaries: bool,
995     ) -> P<Expr> {
996         let mut raw_fields = Vec::new(); // Vec<[fields of self],
997         // [fields of next Self arg], [etc]>
998         let mut patterns = Vec::new();
999         for i in 0..self_args.len() {
1000             let struct_path = cx.path(trait_.span, vec![type_ident]);
1001             let (pat, ident_expr) = trait_.create_struct_pattern(
1002                 cx,
1003                 struct_path,
1004                 struct_def,
1005                 &format!("__self_{}", i),
1006                 ast::Mutability::Not,
1007                 use_temporaries,
1008             );
1009             patterns.push(pat);
1010             raw_fields.push(ident_expr);
1011         }
1012
1013         // transpose raw_fields
1014         let fields = if !raw_fields.is_empty() {
1015             let mut raw_fields = raw_fields.into_iter().map(|v| v.into_iter());
1016             let first_field = raw_fields.next().unwrap();
1017             let mut other_fields: Vec<vec::IntoIter<_>> = raw_fields.collect();
1018             first_field
1019                 .map(|(span, opt_id, field, attrs)| FieldInfo {
1020                     span,
1021                     name: opt_id,
1022                     self_: field,
1023                     other: other_fields
1024                         .iter_mut()
1025                         .map(|l| {
1026                             let (.., ex, _) = l.next().unwrap();
1027                             ex
1028                         })
1029                         .collect(),
1030                     attrs,
1031                 })
1032                 .collect()
1033         } else {
1034             cx.span_bug(trait_.span, "no `self` parameter for method in generic `derive`")
1035         };
1036
1037         // body of the inner most destructuring match
1038         let mut body = self.call_substructure_method(
1039             cx,
1040             trait_,
1041             type_ident,
1042             self_args,
1043             nonself_args,
1044             &Struct(struct_def, fields),
1045         );
1046
1047         // make a series of nested matches, to destructure the
1048         // structs. This is actually right-to-left, but it shouldn't
1049         // matter.
1050         for (arg_expr, pat) in self_args.iter().zip(patterns) {
1051             body = cx.expr_match(
1052                 trait_.span,
1053                 arg_expr.clone(),
1054                 vec![cx.arm(trait_.span, pat.clone(), body)],
1055             )
1056         }
1057
1058         body
1059     }
1060
1061     fn expand_static_struct_method_body(
1062         &self,
1063         cx: &mut ExtCtxt<'_>,
1064         trait_: &TraitDef<'_>,
1065         struct_def: &VariantData,
1066         type_ident: Ident,
1067         self_args: &[P<Expr>],
1068         nonself_args: &[P<Expr>],
1069     ) -> P<Expr> {
1070         let summary = trait_.summarise_struct(cx, struct_def);
1071
1072         self.call_substructure_method(
1073             cx,
1074             trait_,
1075             type_ident,
1076             self_args,
1077             nonself_args,
1078             &StaticStruct(struct_def, summary),
1079         )
1080     }
1081
1082     /// ```
1083     /// #[derive(PartialEq)]
1084     /// # struct Dummy;
1085     /// enum A {
1086     ///     A1,
1087     ///     A2(i32)
1088     /// }
1089     ///
1090     /// // is equivalent to
1091     ///
1092     /// impl PartialEq for A {
1093     ///     fn eq(&self, other: &A) -> ::bool {
1094     ///         match (&*self, &*other) {
1095     ///             (&A1, &A1) => true,
1096     ///             (&A2(ref self_0),
1097     ///              &A2(ref __arg_1_0)) => (*self_0).eq(&(*__arg_1_0)),
1098     ///             _ => {
1099     ///                 let __self_vi = match *self { A1(..) => 0, A2(..) => 1 };
1100     ///                 let __arg_1_vi = match *other { A1(..) => 0, A2(..) => 1 };
1101     ///                 false
1102     ///             }
1103     ///         }
1104     ///     }
1105     /// }
1106     /// ```
1107     ///
1108     /// (Of course `__self_vi` and `__arg_1_vi` are unused for
1109     /// `PartialEq`, and those subcomputations will hopefully be removed
1110     /// as their results are unused. The point of `__self_vi` and
1111     /// `__arg_1_vi` is for `PartialOrd`; see #15503.)
1112     fn expand_enum_method_body<'b>(
1113         &self,
1114         cx: &mut ExtCtxt<'_>,
1115         trait_: &TraitDef<'b>,
1116         enum_def: &'b EnumDef,
1117         type_ident: Ident,
1118         self_args: Vec<P<Expr>>,
1119         nonself_args: &[P<Expr>],
1120     ) -> P<Expr> {
1121         self.build_enum_match_tuple(cx, trait_, enum_def, type_ident, self_args, nonself_args)
1122     }
1123
1124     /// Creates a match for a tuple of all `self_args`, where either all
1125     /// variants match, or it falls into a catch-all for when one variant
1126     /// does not match.
1127
1128     /// There are N + 1 cases because is a case for each of the N
1129     /// variants where all of the variants match, and one catch-all for
1130     /// when one does not match.
1131
1132     /// As an optimization we generate code which checks whether all variants
1133     /// match first which makes llvm see that C-like enums can be compiled into
1134     /// a simple equality check (for PartialEq).
1135
1136     /// The catch-all handler is provided access the variant index values
1137     /// for each of the self-args, carried in precomputed variables.
1138
1139     /// ```{.text}
1140     /// let __self0_vi = unsafe {
1141     ///     std::intrinsics::discriminant_value(&self) };
1142     /// let __self1_vi = unsafe {
1143     ///     std::intrinsics::discriminant_value(&arg1) };
1144     /// let __self2_vi = unsafe {
1145     ///     std::intrinsics::discriminant_value(&arg2) };
1146     ///
1147     /// if __self0_vi == __self1_vi && __self0_vi == __self2_vi && ... {
1148     ///     match (...) {
1149     ///         (Variant1, Variant1, ...) => Body1
1150     ///         (Variant2, Variant2, ...) => Body2,
1151     ///         ...
1152     ///         _ => ::core::intrinsics::unreachable()
1153     ///     }
1154     /// }
1155     /// else {
1156     ///     ... // catch-all remainder can inspect above variant index values.
1157     /// }
1158     /// ```
1159     fn build_enum_match_tuple<'b>(
1160         &self,
1161         cx: &mut ExtCtxt<'_>,
1162         trait_: &TraitDef<'b>,
1163         enum_def: &'b EnumDef,
1164         type_ident: Ident,
1165         mut self_args: Vec<P<Expr>>,
1166         nonself_args: &[P<Expr>],
1167     ) -> P<Expr> {
1168         let sp = trait_.span;
1169         let variants = &enum_def.variants;
1170
1171         let self_arg_names = iter::once("__self".to_string())
1172             .chain(
1173                 self_args
1174                     .iter()
1175                     .enumerate()
1176                     .skip(1)
1177                     .map(|(arg_count, _self_arg)| format!("__arg_{}", arg_count)),
1178             )
1179             .collect::<Vec<String>>();
1180
1181         let self_arg_idents = self_arg_names
1182             .iter()
1183             .map(|name| Ident::from_str_and_span(name, sp))
1184             .collect::<Vec<Ident>>();
1185
1186         // The `vi_idents` will be bound, solely in the catch-all, to
1187         // a series of let statements mapping each self_arg to an int
1188         // value corresponding to its discriminant.
1189         let vi_idents = self_arg_names
1190             .iter()
1191             .map(|name| {
1192                 let vi_suffix = format!("{}_vi", &name[..]);
1193                 Ident::from_str_and_span(&vi_suffix, trait_.span)
1194             })
1195             .collect::<Vec<Ident>>();
1196
1197         // Builds, via callback to call_substructure_method, the
1198         // delegated expression that handles the catch-all case,
1199         // using `__variants_tuple` to drive logic if necessary.
1200         let catch_all_substructure =
1201             EnumNonMatchingCollapsed(self_arg_idents, &variants[..], &vi_idents[..]);
1202
1203         let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1204
1205         // These arms are of the form:
1206         // (Variant1, Variant1, ...) => Body1
1207         // (Variant2, Variant2, ...) => Body2
1208         // ...
1209         // where each tuple has length = self_args.len()
1210         let mut match_arms: Vec<ast::Arm> = variants
1211             .iter()
1212             .enumerate()
1213             .filter(|&(_, v)| !(self.unify_fieldless_variants && v.data.fields().is_empty()))
1214             .map(|(index, variant)| {
1215                 let mk_self_pat = |cx: &mut ExtCtxt<'_>, self_arg_name: &str| {
1216                     let (p, idents) = trait_.create_enum_variant_pattern(
1217                         cx,
1218                         type_ident,
1219                         variant,
1220                         self_arg_name,
1221                         ast::Mutability::Not,
1222                     );
1223                     (cx.pat(sp, PatKind::Ref(p, ast::Mutability::Not)), idents)
1224                 };
1225
1226                 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
1227                 // (see "Final wrinkle" note below for why.)
1228                 let mut subpats = Vec::with_capacity(self_arg_names.len());
1229                 let mut self_pats_idents = Vec::with_capacity(self_arg_names.len() - 1);
1230                 let first_self_pat_idents = {
1231                     let (p, idents) = mk_self_pat(cx, &self_arg_names[0]);
1232                     subpats.push(p);
1233                     idents
1234                 };
1235                 for self_arg_name in &self_arg_names[1..] {
1236                     let (p, idents) = mk_self_pat(cx, &self_arg_name[..]);
1237                     subpats.push(p);
1238                     self_pats_idents.push(idents);
1239                 }
1240
1241                 // Here is the pat = `(&VariantK, &VariantK, ...)`
1242                 let single_pat = cx.pat_tuple(sp, subpats);
1243
1244                 // For the BodyK, we need to delegate to our caller,
1245                 // passing it an EnumMatching to indicate which case
1246                 // we are in.
1247
1248                 // All of the Self args have the same variant in these
1249                 // cases.  So we transpose the info in self_pats_idents
1250                 // to gather the getter expressions together, in the
1251                 // form that EnumMatching expects.
1252
1253                 // The transposition is driven by walking across the
1254                 // arg fields of the variant for the first self pat.
1255                 let field_tuples = first_self_pat_idents
1256                     .into_iter()
1257                     .enumerate()
1258                     // For each arg field of self, pull out its getter expr ...
1259                     .map(|(field_index, (sp, opt_ident, self_getter_expr, attrs))| {
1260                         // ... but FieldInfo also wants getter expr
1261                         // for matching other arguments of Self type;
1262                         // so walk across the *other* self_pats_idents
1263                         // and pull out getter for same field in each
1264                         // of them (using `field_index` tracked above).
1265                         // That is the heart of the transposition.
1266                         let others = self_pats_idents
1267                             .iter()
1268                             .map(|fields| {
1269                                 let (_, _opt_ident, ref other_getter_expr, _) = fields[field_index];
1270
1271                                 // All Self args have same variant, so
1272                                 // opt_idents are the same.  (Assert
1273                                 // here to make it self-evident that
1274                                 // it is okay to ignore `_opt_ident`.)
1275                                 assert!(opt_ident == _opt_ident);
1276
1277                                 other_getter_expr.clone()
1278                             })
1279                             .collect::<Vec<P<Expr>>>();
1280
1281                         FieldInfo {
1282                             span: sp,
1283                             name: opt_ident,
1284                             self_: self_getter_expr,
1285                             other: others,
1286                             attrs,
1287                         }
1288                     })
1289                     .collect::<Vec<FieldInfo<'_>>>();
1290
1291                 // Now, for some given VariantK, we have built up
1292                 // expressions for referencing every field of every
1293                 // Self arg, assuming all are instances of VariantK.
1294                 // Build up code associated with such a case.
1295                 let substructure = EnumMatching(index, variants.len(), variant, field_tuples);
1296                 let arm_expr = self.call_substructure_method(
1297                     cx,
1298                     trait_,
1299                     type_ident,
1300                     &self_args[..],
1301                     nonself_args,
1302                     &substructure,
1303                 );
1304
1305                 cx.arm(sp, single_pat, arm_expr)
1306             })
1307             .collect();
1308
1309         let default = match first_fieldless {
1310             Some(v) if self.unify_fieldless_variants => {
1311                 // We need a default case that handles the fieldless variants.
1312                 // The index and actual variant aren't meaningful in this case,
1313                 // so just use whatever
1314                 let substructure = EnumMatching(0, variants.len(), v, Vec::new());
1315                 Some(self.call_substructure_method(
1316                     cx,
1317                     trait_,
1318                     type_ident,
1319                     &self_args[..],
1320                     nonself_args,
1321                     &substructure,
1322                 ))
1323             }
1324             _ if variants.len() > 1 && self_args.len() > 1 => {
1325                 // Since we know that all the arguments will match if we reach
1326                 // the match expression we add the unreachable intrinsics as the
1327                 // result of the catch all which should help llvm in optimizing it
1328                 Some(deriving::call_intrinsic(cx, sp, sym::unreachable, vec![]))
1329             }
1330             _ => None,
1331         };
1332         if let Some(arm) = default {
1333             match_arms.push(cx.arm(sp, cx.pat_wild(sp), arm));
1334         }
1335
1336         // We will usually need the catch-all after matching the
1337         // tuples `(VariantK, VariantK, ...)` for each VariantK of the
1338         // enum.  But:
1339         //
1340         // * when there is only one Self arg, the arms above suffice
1341         // (and the deriving we call back into may not be prepared to
1342         // handle EnumNonMatchCollapsed), and,
1343         //
1344         // * when the enum has only one variant, the single arm that
1345         // is already present always suffices.
1346         //
1347         // * In either of the two cases above, if we *did* add a
1348         //   catch-all `_` match, it would trigger the
1349         //   unreachable-pattern error.
1350         //
1351         if variants.len() > 1 && self_args.len() > 1 {
1352             // Build a series of let statements mapping each self_arg
1353             // to its discriminant value.
1354             //
1355             // i.e., for `enum E<T> { A, B(1), C(T, T) }`, and a deriving
1356             // with three Self args, builds three statements:
1357             //
1358             // ```
1359             // let __self0_vi = unsafe {
1360             //     std::intrinsics::discriminant_value(&self) };
1361             // let __self1_vi = unsafe {
1362             //     std::intrinsics::discriminant_value(&arg1) };
1363             // let __self2_vi = unsafe {
1364             //     std::intrinsics::discriminant_value(&arg2) };
1365             // ```
1366             let mut index_let_stmts: Vec<ast::Stmt> = Vec::with_capacity(vi_idents.len() + 1);
1367
1368             // We also build an expression which checks whether all discriminants are equal
1369             // discriminant_test = __self0_vi == __self1_vi && __self0_vi == __self2_vi && ...
1370             let mut discriminant_test = cx.expr_bool(sp, true);
1371
1372             let mut first_ident = None;
1373             for (&ident, self_arg) in vi_idents.iter().zip(&self_args) {
1374                 let self_addr = cx.expr_addr_of(sp, self_arg.clone());
1375                 let variant_value =
1376                     deriving::call_intrinsic(cx, sp, sym::discriminant_value, vec![self_addr]);
1377                 let let_stmt = cx.stmt_let(sp, false, ident, variant_value);
1378                 index_let_stmts.push(let_stmt);
1379
1380                 match first_ident {
1381                     Some(first) => {
1382                         let first_expr = cx.expr_ident(sp, first);
1383                         let id = cx.expr_ident(sp, ident);
1384                         let test = cx.expr_binary(sp, BinOpKind::Eq, first_expr, id);
1385                         discriminant_test =
1386                             cx.expr_binary(sp, BinOpKind::And, discriminant_test, test)
1387                     }
1388                     None => {
1389                         first_ident = Some(ident);
1390                     }
1391                 }
1392             }
1393
1394             let arm_expr = self.call_substructure_method(
1395                 cx,
1396                 trait_,
1397                 type_ident,
1398                 &self_args[..],
1399                 nonself_args,
1400                 &catch_all_substructure,
1401             );
1402
1403             // Final wrinkle: the self_args are expressions that deref
1404             // down to desired places, but we cannot actually deref
1405             // them when they are fed as r-values into a tuple
1406             // expression; here add a layer of borrowing, turning
1407             // `(*self, *__arg_0, ...)` into `(&*self, &*__arg_0, ...)`.
1408             self_args.map_in_place(|self_arg| cx.expr_addr_of(sp, self_arg));
1409             let match_arg = cx.expr(sp, ast::ExprKind::Tup(self_args));
1410
1411             // Lastly we create an expression which branches on all discriminants being equal
1412             //  if discriminant_test {
1413             //      match (...) {
1414             //          (Variant1, Variant1, ...) => Body1
1415             //          (Variant2, Variant2, ...) => Body2,
1416             //          ...
1417             //          _ => ::core::intrinsics::unreachable()
1418             //      }
1419             //  }
1420             //  else {
1421             //      <delegated expression referring to __self0_vi, et al.>
1422             //  }
1423             let all_match = cx.expr_match(sp, match_arg, match_arms);
1424             let arm_expr = cx.expr_if(sp, discriminant_test, all_match, Some(arm_expr));
1425             index_let_stmts.push(cx.stmt_expr(arm_expr));
1426             cx.expr_block(cx.block(sp, index_let_stmts))
1427         } else if variants.is_empty() {
1428             // As an additional wrinkle, For a zero-variant enum A,
1429             // currently the compiler
1430             // will accept `fn (a: &Self) { match   *a   { } }`
1431             // but rejects `fn (a: &Self) { match (&*a,) { } }`
1432             // as well as  `fn (a: &Self) { match ( *a,) { } }`
1433             //
1434             // This means that the strategy of building up a tuple of
1435             // all Self arguments fails when Self is a zero variant
1436             // enum: rustc rejects the expanded program, even though
1437             // the actual code tends to be impossible to execute (at
1438             // least safely), according to the type system.
1439             //
1440             // The most expedient fix for this is to just let the
1441             // code fall through to the catch-all.  But even this is
1442             // error-prone, since the catch-all as defined above would
1443             // generate code like this:
1444             //
1445             //     _ => { let __self0 = match *self { };
1446             //            let __self1 = match *__arg_0 { };
1447             //            <catch-all-expr> }
1448             //
1449             // Which is yields bindings for variables which type
1450             // inference cannot resolve to unique types.
1451             //
1452             // One option to the above might be to add explicit type
1453             // annotations.  But the *only* reason to go down that path
1454             // would be to try to make the expanded output consistent
1455             // with the case when the number of enum variants >= 1.
1456             //
1457             // That just isn't worth it.  In fact, trying to generate
1458             // sensible code for *any* deriving on a zero-variant enum
1459             // does not make sense.  But at the same time, for now, we
1460             // do not want to cause a compile failure just because the
1461             // user happened to attach a deriving to their
1462             // zero-variant enum.
1463             //
1464             // Instead, just generate a failing expression for the
1465             // zero variant case, skipping matches and also skipping
1466             // delegating back to the end user code entirely.
1467             //
1468             // (See also #4499 and #12609; note that some of the
1469             // discussions there influence what choice we make here;
1470             // e.g., if we feature-gate `match x { ... }` when x refers
1471             // to an uninhabited type (e.g., a zero-variant enum or a
1472             // type holding such an enum), but do not feature-gate
1473             // zero-variant enums themselves, then attempting to
1474             // derive Debug on such a type could here generate code
1475             // that needs the feature gate enabled.)
1476
1477             deriving::call_intrinsic(cx, sp, sym::unreachable, vec![])
1478         } else {
1479             // Final wrinkle: the self_args are expressions that deref
1480             // down to desired places, but we cannot actually deref
1481             // them when they are fed as r-values into a tuple
1482             // expression; here add a layer of borrowing, turning
1483             // `(*self, *__arg_0, ...)` into `(&*self, &*__arg_0, ...)`.
1484             self_args.map_in_place(|self_arg| cx.expr_addr_of(sp, self_arg));
1485             let match_arg = cx.expr(sp, ast::ExprKind::Tup(self_args));
1486             cx.expr_match(sp, match_arg, match_arms)
1487         }
1488     }
1489
1490     fn expand_static_enum_method_body(
1491         &self,
1492         cx: &mut ExtCtxt<'_>,
1493         trait_: &TraitDef<'_>,
1494         enum_def: &EnumDef,
1495         type_ident: Ident,
1496         self_args: &[P<Expr>],
1497         nonself_args: &[P<Expr>],
1498     ) -> P<Expr> {
1499         let summary = enum_def
1500             .variants
1501             .iter()
1502             .map(|v| {
1503                 let sp = v.span.with_ctxt(trait_.span.ctxt());
1504                 let summary = trait_.summarise_struct(cx, &v.data);
1505                 (v.ident, sp, summary)
1506             })
1507             .collect();
1508         self.call_substructure_method(
1509             cx,
1510             trait_,
1511             type_ident,
1512             self_args,
1513             nonself_args,
1514             &StaticEnum(enum_def, summary),
1515         )
1516     }
1517 }
1518
1519 // general helper methods.
1520 impl<'a> TraitDef<'a> {
1521     fn summarise_struct(&self, cx: &mut ExtCtxt<'_>, struct_def: &VariantData) -> StaticFields {
1522         let mut named_idents = Vec::new();
1523         let mut just_spans = Vec::new();
1524         for field in struct_def.fields() {
1525             let sp = field.span.with_ctxt(self.span.ctxt());
1526             match field.ident {
1527                 Some(ident) => named_idents.push((ident, sp)),
1528                 _ => just_spans.push(sp),
1529             }
1530         }
1531
1532         let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..));
1533         match (just_spans.is_empty(), named_idents.is_empty()) {
1534             (false, false) => cx.span_bug(
1535                 self.span,
1536                 "a struct with named and unnamed \
1537                                           fields in generic `derive`",
1538             ),
1539             // named fields
1540             (_, false) => Named(named_idents),
1541             // unnamed fields
1542             (false, _) => Unnamed(just_spans, is_tuple),
1543             // empty
1544             _ => Named(Vec::new()),
1545         }
1546     }
1547
1548     fn create_subpatterns(
1549         &self,
1550         cx: &mut ExtCtxt<'_>,
1551         field_paths: Vec<Ident>,
1552         mutbl: ast::Mutability,
1553         use_temporaries: bool,
1554     ) -> Vec<P<ast::Pat>> {
1555         field_paths
1556             .iter()
1557             .map(|path| {
1558                 let binding_mode = if use_temporaries {
1559                     ast::BindingMode::ByValue(ast::Mutability::Not)
1560                 } else {
1561                     ast::BindingMode::ByRef(mutbl)
1562                 };
1563                 cx.pat(path.span, PatKind::Ident(binding_mode, *path, None))
1564             })
1565             .collect()
1566     }
1567
1568     fn create_struct_pattern(
1569         &self,
1570         cx: &mut ExtCtxt<'_>,
1571         struct_path: ast::Path,
1572         struct_def: &'a VariantData,
1573         prefix: &str,
1574         mutbl: ast::Mutability,
1575         use_temporaries: bool,
1576     ) -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) {
1577         let mut paths = Vec::new();
1578         let mut ident_exprs = Vec::new();
1579         for (i, struct_field) in struct_def.fields().iter().enumerate() {
1580             let sp = struct_field.span.with_ctxt(self.span.ctxt());
1581             let ident = Ident::from_str_and_span(&format!("{}_{}", prefix, i), self.span);
1582             paths.push(ident.with_span_pos(sp));
1583             let val = cx.expr_path(cx.path_ident(sp, ident));
1584             let val = if use_temporaries { val } else { cx.expr_deref(sp, val) };
1585             let val = cx.expr(sp, ast::ExprKind::Paren(val));
1586
1587             ident_exprs.push((sp, struct_field.ident, val, &struct_field.attrs[..]));
1588         }
1589
1590         let subpats = self.create_subpatterns(cx, paths, mutbl, use_temporaries);
1591         let pattern = match *struct_def {
1592             VariantData::Struct(..) => {
1593                 let field_pats = subpats
1594                     .into_iter()
1595                     .zip(&ident_exprs)
1596                     .map(|(pat, &(sp, ident, ..))| {
1597                         if ident.is_none() {
1598                             cx.span_bug(sp, "a braced struct with unnamed fields in `derive`");
1599                         }
1600                         ast::FieldPat {
1601                             ident: ident.unwrap(),
1602                             is_shorthand: false,
1603                             attrs: ast::AttrVec::new(),
1604                             id: ast::DUMMY_NODE_ID,
1605                             span: pat.span.with_ctxt(self.span.ctxt()),
1606                             pat,
1607                             is_placeholder: false,
1608                         }
1609                     })
1610                     .collect();
1611                 cx.pat_struct(self.span, struct_path, field_pats)
1612             }
1613             VariantData::Tuple(..) => cx.pat_tuple_struct(self.span, struct_path, subpats),
1614             VariantData::Unit(..) => cx.pat_path(self.span, struct_path),
1615         };
1616
1617         (pattern, ident_exprs)
1618     }
1619
1620     fn create_enum_variant_pattern(
1621         &self,
1622         cx: &mut ExtCtxt<'_>,
1623         enum_ident: Ident,
1624         variant: &'a ast::Variant,
1625         prefix: &str,
1626         mutbl: ast::Mutability,
1627     ) -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) {
1628         let sp = variant.span.with_ctxt(self.span.ctxt());
1629         let variant_path = cx.path(sp, vec![enum_ident, variant.ident]);
1630         let use_temporaries = false; // enums can't be repr(packed)
1631         self.create_struct_pattern(cx, variant_path, &variant.data, prefix, mutbl, use_temporaries)
1632     }
1633 }
1634
1635 // helpful premade recipes
1636
1637 pub fn cs_fold_fields<'a, F>(
1638     use_foldl: bool,
1639     mut f: F,
1640     base: P<Expr>,
1641     cx: &mut ExtCtxt<'_>,
1642     all_fields: &[FieldInfo<'a>],
1643 ) -> P<Expr>
1644 where
1645     F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>,
1646 {
1647     if use_foldl {
1648         all_fields
1649             .iter()
1650             .fold(base, |old, field| f(cx, field.span, old, field.self_.clone(), &field.other))
1651     } else {
1652         all_fields
1653             .iter()
1654             .rev()
1655             .fold(base, |old, field| f(cx, field.span, old, field.self_.clone(), &field.other))
1656     }
1657 }
1658
1659 pub fn cs_fold_enumnonmatch(
1660     mut enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>,
1661     cx: &mut ExtCtxt<'_>,
1662     trait_span: Span,
1663     substructure: &Substructure<'_>,
1664 ) -> P<Expr> {
1665     match *substructure.fields {
1666         EnumNonMatchingCollapsed(ref all_args, _, tuple) => {
1667             enum_nonmatch_f(cx, trait_span, (&all_args[..], tuple), substructure.nonself_args)
1668         }
1669         _ => cx.span_bug(trait_span, "cs_fold_enumnonmatch expected an EnumNonMatchingCollapsed"),
1670     }
1671 }
1672
1673 pub fn cs_fold_static(cx: &mut ExtCtxt<'_>, trait_span: Span) -> P<Expr> {
1674     cx.span_bug(trait_span, "static function in `derive`")
1675 }
1676
1677 /// Fold the fields. `use_foldl` controls whether this is done
1678 /// left-to-right (`true`) or right-to-left (`false`).
1679 pub fn cs_fold<F>(
1680     use_foldl: bool,
1681     f: F,
1682     base: P<Expr>,
1683     enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>,
1684     cx: &mut ExtCtxt<'_>,
1685     trait_span: Span,
1686     substructure: &Substructure<'_>,
1687 ) -> P<Expr>
1688 where
1689     F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>,
1690 {
1691     match *substructure.fields {
1692         EnumMatching(.., ref all_fields) | Struct(_, ref all_fields) => {
1693             cs_fold_fields(use_foldl, f, base, cx, all_fields)
1694         }
1695         EnumNonMatchingCollapsed(..) => {
1696             cs_fold_enumnonmatch(enum_nonmatch_f, cx, trait_span, substructure)
1697         }
1698         StaticEnum(..) | StaticStruct(..) => cs_fold_static(cx, trait_span),
1699     }
1700 }
1701
1702 /// Function to fold over fields, with three cases, to generate more efficient and concise code.
1703 /// When the `substructure` has grouped fields, there are two cases:
1704 /// Zero fields: call the base case function with `None` (like the usual base case of `cs_fold`).
1705 /// One or more fields: call the base case function on the first value (which depends on
1706 /// `use_fold`), and use that as the base case. Then perform `cs_fold` on the remainder of the
1707 /// fields.
1708 /// When the `substructure` is a `EnumNonMatchingCollapsed`, the result of `enum_nonmatch_f`
1709 /// is returned. Statics may not be folded over.
1710 /// See `cs_op` in `partial_ord.rs` for a model example.
1711 pub fn cs_fold1<F, B>(
1712     use_foldl: bool,
1713     f: F,
1714     mut b: B,
1715     enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>,
1716     cx: &mut ExtCtxt<'_>,
1717     trait_span: Span,
1718     substructure: &Substructure<'_>,
1719 ) -> P<Expr>
1720 where
1721     F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>,
1722     B: FnMut(&mut ExtCtxt<'_>, Option<(Span, P<Expr>, &[P<Expr>])>) -> P<Expr>,
1723 {
1724     match *substructure.fields {
1725         EnumMatching(.., ref all_fields) | Struct(_, ref all_fields) => {
1726             let (base, all_fields) = match (all_fields.is_empty(), use_foldl) {
1727                 (false, true) => {
1728                     let field = &all_fields[0];
1729                     let args = (field.span, field.self_.clone(), &field.other[..]);
1730                     (b(cx, Some(args)), &all_fields[1..])
1731                 }
1732                 (false, false) => {
1733                     let idx = all_fields.len() - 1;
1734                     let field = &all_fields[idx];
1735                     let args = (field.span, field.self_.clone(), &field.other[..]);
1736                     (b(cx, Some(args)), &all_fields[..idx])
1737                 }
1738                 (true, _) => (b(cx, None), &all_fields[..]),
1739             };
1740
1741             cs_fold_fields(use_foldl, f, base, cx, all_fields)
1742         }
1743         EnumNonMatchingCollapsed(..) => {
1744             cs_fold_enumnonmatch(enum_nonmatch_f, cx, trait_span, substructure)
1745         }
1746         StaticEnum(..) | StaticStruct(..) => cs_fold_static(cx, trait_span),
1747     }
1748 }
1749
1750 /// Returns `true` if the type has no value fields
1751 /// (for an enum, no variant has any fields)
1752 pub fn is_type_without_fields(item: &Annotatable) -> bool {
1753     if let Annotatable::Item(ref item) = *item {
1754         match item.kind {
1755             ast::ItemKind::Enum(ref enum_def, _) => {
1756                 enum_def.variants.iter().all(|v| v.data.fields().is_empty())
1757             }
1758             ast::ItemKind::Struct(ref variant_data, _) => variant_data.fields().is_empty(),
1759             _ => false,
1760         }
1761     } else {
1762         false
1763     }
1764 }