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.
6 //! Supported features (fairly exhaustive):
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`)
16 //! The most important thing for implementors is the `Substructure` and
17 //! `SubstructureFields` objects. The latter groups 5 possibilities of the
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
30 //! In the first two cases, the values from the corresponding fields in
31 //! all the arguments are grouped together.
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
40 //! # #![allow(dead_code)]
41 //! struct A { x : i32 }
51 //! The `i32`s in `B` and `C0` don't have an identifier, so the
52 //! `Option<ident>`s would be `None` for them.
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.
60 //! # "`cs`" functions
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.
71 //! The following simplified `PartialEq` is used for in-code examples:
75 //! fn eq(&self, other: &Self) -> bool;
77 //! impl PartialEq for i32 {
78 //! fn eq(&self, other: &i32) -> bool {
84 //! Some examples of the values of `SubstructureFields` follow, using the
85 //! above `PartialEq`, `A`, `B` and `C`.
89 //! When generating the `expr` for the `A` impl, the `SubstructureFields` is
92 //! Struct(vec![FieldInfo {
94 //! name: Some(<ident of x>),
95 //! self_: <expr for &self.x>,
96 //! other: vec![<expr for &other.x]
100 //! For the `B` impl, called with `B(a)` and `B(b)`,
103 //! Struct(vec![FieldInfo {
104 //! span: <span of `i32`>,
106 //! self_: <expr for &a>
107 //! other: vec![<expr for &b>]
113 //! When generating the `expr` for a call with `self == C0(a)` and `other
114 //! == C0(b)`, the SubstructureFields is
117 //! EnumMatching(0, <ast::Variant for C0>,
119 //! span: <span of i32>
121 //! self_: <expr for &a>,
122 //! other: vec![<expr for &b>]
126 //! For `C1 {x}` and `C1 {x}`,
129 //! EnumMatching(1, <ast::Variant for C1>,
131 //! span: <span of x>
132 //! name: Some(<ident of x>),
133 //! self_: <expr for &self.x>,
134 //! other: vec![<expr for &other.x>]
142 //! &[<ident of self tag>, <ident of other tag>], <expr to combine with>)
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).
150 //! A static method on the types above would result in,
153 //! StaticStruct(<ast::VariantData of A>, Named(vec![(<ident of x>, <span of x>)]))
155 //! StaticStruct(<ast::VariantData of B>, Unnamed(vec![<span of x>]))
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>)]))])
162 pub use StaticFields::*;
163 pub use SubstructureFields::*;
166 use rustc_ast::ptr::P;
168 self as ast, BindingAnnotation, ByRef, EnumDef, Expr, Generics, Mutability, PatKind,
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;
179 use thin_vec::thin_vec;
180 use ty::{Bounds, Path, Ref, Self_, Ty};
184 pub struct TraitDef<'a> {
185 /// The span for the current #[derive(Foo)] header.
188 /// Path of the trait, including any type parameters
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,
194 /// Additional bounds required of any type parameters of the type,
195 /// other than the current trait
196 pub additional_bounds: Vec<Ty>,
198 /// Can this trait be derived for unions?
199 pub supports_unions: bool,
201 pub methods: Vec<MethodDef<'a>>,
203 pub associated_types: Vec<(Ident, Ty)>,
208 pub struct MethodDef<'a> {
209 /// name of the method
211 /// List of generics, e.g., `R: rand::Rng`
212 pub generics: Bounds,
214 /// Is there is a `&self` argument? If not, it is a static function.
215 pub explicit_self: bool,
217 /// Arguments other than the self argument.
218 pub nonself_args: Vec<(Ty, Symbol)>,
223 pub attributes: ast::AttrVec,
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
228 pub unify_fieldless_variants: bool,
230 pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
233 /// All the data about the data structure/method being derived upon.
234 pub struct Substructure<'a> {
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>,
243 /// Summary of the relevant parts of a struct/enum field.
244 pub struct FieldInfo {
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>>,
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)>),
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>),
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
273 EnumMatching(usize, usize, &'a ast::Variant, Vec<FieldInfo>),
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>>),
280 /// A static method where `Self` is a struct.
281 StaticStruct(&'a ast::VariantData, StaticFields),
283 /// A static method where `Self` is an enum.
284 StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>),
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>;
292 pub fn combine_substructure(
293 f: CombineSubstructureFunc<'_>,
294 ) -> RefCell<CombineSubstructureFunc<'_>> {
298 struct TypeParameter {
299 bound_generic_params: Vec<ast::GenericParam>,
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.
308 /// The statements come before the expression.
309 pub struct BlockOrExpr(Vec<ast::Stmt>, Option<P<Expr>>);
312 pub fn new_stmts(stmts: Vec<ast::Stmt>) -> BlockOrExpr {
313 BlockOrExpr(stmts, None)
316 pub fn new_expr(expr: P<Expr>) -> BlockOrExpr {
317 BlockOrExpr(vec![], Some(expr))
320 pub fn new_mixed(stmts: Vec<ast::Stmt>, expr: Option<P<Expr>>) -> BlockOrExpr {
321 BlockOrExpr(stmts, expr)
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));
329 cx.block(span, self.0)
332 // Converts it into an expression.
333 fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> P<Expr> {
334 if self.0.is_empty() {
336 None => cx.expr_block(cx.block(span, vec![])),
339 } else if self.0.len() == 1
340 && let ast::StmtKind::Expr(expr) = &self.0[0].kind
343 // There's only a single statement expression. Pull it out.
346 // Multiple statements and/or expressions.
347 cx.expr_block(self.into_block(cx, span))
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(
358 ty_param_names: &[Symbol],
360 ) -> Vec<TypeParameter> {
361 use rustc_ast::visit;
363 struct Visitor<'a, 'b> {
365 ty_param_names: &'a [Symbol],
366 bound_generic_params_stack: Vec<ast::GenericParam>,
367 type_params: Vec<TypeParameter>,
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(_, ref path) = ty.kind {
373 if let Some(segment) = path.segments.first() {
374 if self.ty_param_names.contains(&segment.ident.name) {
375 self.type_params.push(TypeParameter {
376 bound_generic_params: self.bound_generic_params_stack.clone(),
383 visit::walk_ty(self, ty)
386 // Place bound generic params on a stack, to extract them when a type is encountered.
387 fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
388 let stack_len = self.bound_generic_params_stack.len();
389 self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
391 visit::walk_poly_trait_ref(self, trait_ref);
393 self.bound_generic_params_stack.truncate(stack_len);
396 fn visit_mac_call(&mut self, mac: &ast::MacCall) {
397 self.cx.span_err(mac.span(), "`derive` cannot be used on items with type macros");
401 let mut visitor = Visitor {
404 bound_generic_params_stack: Vec::new(),
405 type_params: Vec::new(),
407 visit::Visitor::visit_ty(&mut visitor, ty);
412 impl<'a> TraitDef<'a> {
415 cx: &mut ExtCtxt<'_>,
416 mitem: &ast::MetaItem,
417 item: &'a Annotatable,
418 push: &mut dyn FnMut(Annotatable),
420 self.expand_ext(cx, mitem, item, push, false);
425 cx: &mut ExtCtxt<'_>,
426 mitem: &ast::MetaItem,
427 item: &'a Annotatable,
428 push: &mut dyn FnMut(Annotatable),
432 Annotatable::Item(ref item) => {
433 let is_packed = item.attrs.iter().any(|attr| {
434 for r in attr::find_repr_attrs(&cx.sess, attr) {
435 if let attr::ReprPacked(_) = r {
441 let has_no_type_params = match item.kind {
442 ast::ItemKind::Struct(_, ref generics)
443 | ast::ItemKind::Enum(_, ref generics)
444 | ast::ItemKind::Union(_, ref generics) => !generics
447 .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. })),
450 let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
452 is_packed && has_no_type_params && cx.resolver.has_derive_copy(container_id);
454 let newitem = match item.kind {
455 ast::ItemKind::Struct(ref struct_def, ref generics) => self.expand_struct_def(
463 ast::ItemKind::Enum(ref enum_def, ref generics) => {
464 // We ignore `is_packed` here, because `repr(packed)`
465 // enums cause an error later on.
467 // This can only cause further compilation errors
468 // downstream in blatantly illegal code, so it is fine.
469 self.expand_enum_def(cx, enum_def, item.ident, generics, from_scratch)
471 ast::ItemKind::Union(ref struct_def, ref generics) => {
472 if self.supports_unions {
473 self.expand_struct_def(
482 cx.span_err(mitem.span, "this trait cannot be derived for unions");
488 // Keep the lint attributes of the previous item to control how the
489 // generated implementations are linted
490 let mut attrs = newitem.attrs.clone();
503 .contains(&a.name_or_empty())
507 push(Annotatable::Item(P(ast::Item { attrs, ..(*newitem).clone() })))
513 /// Given that we are deriving a trait `DerivedTrait` for a type like:
515 /// ```ignore (only-for-syntax-highlight)
516 /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z> where C: WhereTrait {
519 /// b1: <B as DeclaredTrait>::Item,
520 /// c1: <C as WhereTrait>::Item,
521 /// c2: Option<<C as WhereTrait>::Item>,
526 /// create an impl like:
528 /// ```ignore (only-for-syntax-highlight)
529 /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ... Z> where
531 /// A: DerivedTrait + B1 + ... + BN,
532 /// B: DerivedTrait + B1 + ... + BN,
533 /// C: DerivedTrait + B1 + ... + BN,
534 /// B::Item: DerivedTrait + B1 + ... + BN,
535 /// <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
542 /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
543 /// therefore does not get bound by the derived trait.
544 fn create_derived_impl(
546 cx: &mut ExtCtxt<'_>,
549 field_tys: Vec<P<ast::Ty>>,
550 methods: Vec<P<ast::AssocItem>>,
552 let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
554 // Transform associated types from `deriving::ty::Ty` into `ast::AssocItem`
555 let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
557 id: ast::DUMMY_NODE_ID,
560 vis: ast::Visibility {
561 span: self.span.shrink_to_lo(),
562 kind: ast::VisibilityKind::Inherited,
565 attrs: ast::AttrVec::new(),
566 kind: ast::AssocItemKind::Type(Box::new(ast::TyAlias {
567 defaultness: ast::Defaultness::Final,
568 generics: Generics::default(),
570 ast::TyAliasWhereClause::default(),
571 ast::TyAliasWhereClause::default(),
573 where_predicates_split: 0,
575 ty: Some(type_def.to_ty(cx, self.span, type_ident, generics)),
581 let mut where_clause = ast::WhereClause::default();
582 where_clause.span = generics.where_clause.span;
583 let ctxt = self.span.ctxt();
584 let span = generics.span.with_ctxt(ctxt);
586 // Create the generic parameters
587 let params: Vec<_> = generics
590 .map(|param| match ¶m.kind {
591 GenericParamKind::Lifetime { .. } => param.clone(),
592 GenericParamKind::Type { .. } => {
593 // I don't think this can be moved out of the loop, since
594 // a GenericBound requires an ast id
596 // extra restrictions on the generics parameters to the
597 // type being derived upon
598 self.additional_bounds.iter().map(|p| {
599 cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))
601 // require the current trait
602 self.skip_path_as_bound.not().then(|| cx.trait_bound(trait_path.clone()))
604 // also add in any bounds from the declaration
605 param.bounds.iter().cloned()
608 cx.typaram(param.ident.span.with_ctxt(ctxt), param.ident, bounds, None)
610 GenericParamKind::Const { ty, kw_span, .. } => {
611 let const_nodefault_kind = GenericParamKind::Const {
613 kw_span: kw_span.with_ctxt(ctxt),
615 // We can't have default values inside impl block
618 let mut param_clone = param.clone();
619 param_clone.kind = const_nodefault_kind;
625 // and similarly for where clauses
626 where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
628 ast::WherePredicate::BoundPredicate(wb) => {
629 let span = wb.span.with_ctxt(ctxt);
630 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
635 ast::WherePredicate::RegionPredicate(wr) => {
636 let span = wr.span.with_ctxt(ctxt);
637 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
642 ast::WherePredicate::EqPredicate(we) => {
643 let span = we.span.with_ctxt(ctxt);
644 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { span, ..we.clone() })
650 // Extra scope required here so ty_params goes out of scope before params is moved
652 let mut ty_params = params
654 .filter(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
657 if ty_params.peek().is_some() {
658 let ty_param_names: Vec<Symbol> =
659 ty_params.map(|ty_param| ty_param.ident.name).collect();
661 for field_ty in field_tys {
662 let field_ty_params = find_type_parameters(&field_ty, &ty_param_names, cx);
664 for field_ty_param in field_ty_params {
665 // if we have already handled this type, skip it
666 if let ast::TyKind::Path(_, ref p) = field_ty_param.ty.kind {
667 if p.segments.len() == 1
668 && ty_param_names.contains(&p.segments[0].ident.name)
673 let mut bounds: Vec<_> = self
676 .map(|p| cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)))
679 // require the current trait
680 bounds.push(cx.trait_bound(trait_path.clone()));
682 let predicate = ast::WhereBoundPredicate {
684 bound_generic_params: field_ty_param.bound_generic_params,
685 bounded_ty: field_ty_param.ty,
689 let predicate = ast::WherePredicate::BoundPredicate(predicate);
690 where_clause.predicates.push(predicate);
696 let trait_generics = Generics { params, where_clause, span };
698 // Create the reference to the trait.
699 let trait_ref = cx.trait_ref(trait_path);
701 let self_params: Vec<_> = generics
704 .map(|param| match param.kind {
705 GenericParamKind::Lifetime { .. } => {
706 GenericArg::Lifetime(cx.lifetime(param.ident.span.with_ctxt(ctxt), param.ident))
708 GenericParamKind::Type { .. } => {
709 GenericArg::Type(cx.ty_ident(param.ident.span.with_ctxt(ctxt), param.ident))
711 GenericParamKind::Const { .. } => {
712 GenericArg::Const(cx.const_ident(param.ident.span.with_ctxt(ctxt), param.ident))
717 // Create the type of `self`.
718 let path = cx.path_all(self.span, false, vec![type_ident], self_params);
719 let self_type = cx.ty_path(path);
721 let attr = cx.attribute(cx.meta_word(self.span, sym::automatically_derived));
722 let attrs = thin_vec![attr];
723 let opt_trait_ref = Some(trait_ref);
729 ast::ItemKind::Impl(Box::new(ast::Impl {
730 unsafety: ast::Unsafe::No,
731 polarity: ast::ImplPolarity::Positive,
732 defaultness: ast::Defaultness::Final,
733 constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },
734 generics: trait_generics,
735 of_trait: opt_trait_ref,
737 items: methods.into_iter().chain(associated_types).collect(),
742 fn expand_struct_def(
744 cx: &mut ExtCtxt<'_>,
745 struct_def: &'a VariantData,
751 let field_tys: Vec<P<ast::Ty>> =
752 struct_def.fields().iter().map(|field| field.ty.clone()).collect();
758 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
759 method_def.extract_arg_details(cx, self, type_ident, generics);
761 let body = if from_scratch || method_def.is_static() {
762 method_def.expand_static_struct_method_body(
770 method_def.expand_struct_method_body(
781 method_def.create_method(
793 self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
798 cx: &mut ExtCtxt<'_>,
799 enum_def: &'a EnumDef,
804 let mut field_tys = Vec::new();
806 for variant in &enum_def.variants {
807 field_tys.extend(variant.data.fields().iter().map(|field| field.ty.clone()));
814 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
815 method_def.extract_arg_details(cx, self, type_ident, generics);
817 let body = if from_scratch || method_def.is_static() {
818 method_def.expand_static_enum_method_body(
826 method_def.expand_enum_method_body(
836 method_def.create_method(
848 self.create_derived_impl(cx, type_ident, generics, field_tys, methods)
852 impl<'a> MethodDef<'a> {
853 fn call_substructure_method(
855 cx: &mut ExtCtxt<'_>,
856 trait_: &TraitDef<'_>,
858 nonselflike_args: &[P<Expr>],
859 fields: &SubstructureFields<'_>,
861 let span = trait_.span;
862 let substructure = Substructure { type_ident, nonselflike_args, fields };
863 let mut f = self.combine_substructure.borrow_mut();
864 let f: &mut CombineSubstructureFunc<'_> = &mut *f;
865 f(cx, span, &substructure)
870 cx: &mut ExtCtxt<'_>,
871 trait_: &TraitDef<'_>,
875 self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
878 fn is_static(&self) -> bool {
882 // The return value includes:
883 // - explicit_self: The `&self` arg, if present.
884 // - selflike_args: Expressions for `&self` (if present) and also any other
885 // args with the same type (e.g. the `other` arg in `PartialEq::eq`).
886 // - nonselflike_args: Expressions for all the remaining args.
887 // - nonself_arg_tys: Additional information about all the args other than
889 fn extract_arg_details(
891 cx: &mut ExtCtxt<'_>,
892 trait_: &TraitDef<'_>,
895 ) -> (Option<ast::ExplicitSelf>, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) {
896 let mut selflike_args = Vec::new();
897 let mut nonselflike_args = Vec::new();
898 let mut nonself_arg_tys = Vec::new();
899 let span = trait_.span;
901 let explicit_self = if self.explicit_self {
902 let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
903 selflike_args.push(self_expr);
909 for (ty, name) in self.nonself_args.iter() {
910 let ast_ty = ty.to_ty(cx, span, type_ident, generics);
911 let ident = Ident::new(*name, span);
912 nonself_arg_tys.push((ident, ast_ty));
914 let arg_expr = cx.expr_ident(span, ident);
917 // Selflike (`&Self`) arguments only occur in non-static methods.
918 Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
919 Self_ => cx.span_bug(span, "`Self` in non-return position"),
920 _ => nonselflike_args.push(arg_expr),
924 (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys)
929 cx: &mut ExtCtxt<'_>,
930 trait_: &TraitDef<'_>,
933 explicit_self: Option<ast::ExplicitSelf>,
934 nonself_arg_tys: Vec<(Ident, P<ast::Ty>)>,
936 ) -> P<ast::AssocItem> {
937 let span = trait_.span;
938 // Create the generics that aren't for `Self`.
939 let fn_generics = self.generics.to_generics(cx, span, type_ident, generics);
942 let self_arg = explicit_self.map(|explicit_self| {
943 let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(span);
944 ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident)
947 nonself_arg_tys.into_iter().map(|(name, ty)| cx.param(span, name, ty));
948 self_arg.into_iter().chain(nonself_args).collect()
951 let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
953 let method_ident = Ident::new(self.name, span);
954 let fn_decl = cx.fn_decl(args, ast::FnRetTy::Ty(ret_type));
955 let body_block = body.into_block(cx, span);
957 let trait_lo_sp = span.shrink_to_lo();
959 let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
960 let defaultness = ast::Defaultness::Final;
962 // Create the method.
964 id: ast::DUMMY_NODE_ID,
965 attrs: self.attributes.clone(),
967 vis: ast::Visibility {
969 kind: ast::VisibilityKind::Inherited,
973 kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
976 generics: fn_generics,
977 body: Some(body_block),
983 /// The normal case uses field access.
985 /// #[derive(PartialEq)]
987 /// struct A { x: u8, y: u8 }
989 /// // equivalent to:
990 /// impl PartialEq for A {
991 /// fn eq(&self, other: &A) -> bool {
992 /// self.x == other.x && self.y == other.y
996 /// But if the struct is `repr(packed)`, we can't use something like
997 /// `&self.x` because that might cause an unaligned ref. So for any trait
998 /// method that takes a reference, if the struct impls `Copy` then we use a
999 /// local block to force a copy:
1001 /// # struct A { x: u8, y: u8 }
1002 /// impl PartialEq for A {
1003 /// fn eq(&self, other: &A) -> bool {
1004 /// // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
1005 /// { self.x } == { other.y } && { self.y } == { other.y }
1008 /// impl Hash for A {
1009 /// fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
1010 /// ::core::hash::Hash::hash(&{ self.x }, state);
1011 /// ::core::hash::Hash::hash(&{ self.y }, state)
1015 /// If the struct doesn't impl `Copy`, we use the normal `&self.x`. This
1016 /// only works if the fields match the alignment required by the
1017 /// `packed(N)` attribute. (We'll get errors later on if not.)
1018 fn expand_struct_method_body<'b>(
1020 cx: &mut ExtCtxt<'_>,
1021 trait_: &TraitDef<'b>,
1022 struct_def: &'b VariantData,
1024 selflike_args: &[P<Expr>],
1025 nonselflike_args: &[P<Expr>],
1028 assert!(selflike_args.len() == 1 || selflike_args.len() == 2);
1030 let selflike_fields =
1031 trait_.create_struct_field_access_fields(cx, selflike_args, struct_def, copy_fields);
1032 self.call_substructure_method(
1037 &Struct(struct_def, selflike_fields),
1041 fn expand_static_struct_method_body(
1043 cx: &mut ExtCtxt<'_>,
1044 trait_: &TraitDef<'_>,
1045 struct_def: &VariantData,
1047 nonselflike_args: &[P<Expr>],
1049 let summary = trait_.summarise_struct(cx, struct_def);
1051 self.call_substructure_method(
1056 &StaticStruct(struct_def, summary),
1061 /// #[derive(PartialEq)]
1068 /// is equivalent to:
1070 /// #![feature(core_intrinsics)]
1075 /// impl ::core::cmp::PartialEq for A {
1077 /// fn eq(&self, other: &A) -> bool {
1078 /// let __self_tag = ::core::intrinsics::discriminant_value(self);
1079 /// let __arg1_tag = ::core::intrinsics::discriminant_value(other);
1080 /// __self_tag == __arg1_tag &&
1081 /// match (self, other) {
1082 /// (A::A2(__self_0), A::A2(__arg1_0)) =>
1083 /// *__self_0 == *__arg1_0,
1089 /// Creates a tag check combined with a match for a tuple of all
1090 /// `selflike_args`, with an arm for each variant with fields, possibly an
1091 /// arm for each fieldless variant (if `!unify_fieldless_variants` is not
1092 /// true), and possibly a default arm.
1093 fn expand_enum_method_body<'b>(
1095 cx: &mut ExtCtxt<'_>,
1096 trait_: &TraitDef<'b>,
1097 enum_def: &'b EnumDef,
1099 selflike_args: Vec<P<Expr>>,
1100 nonselflike_args: &[P<Expr>],
1102 let span = trait_.span;
1103 let variants = &enum_def.variants;
1105 // Traits that unify fieldless variants always use the tag(s).
1106 let uses_tags = self.unify_fieldless_variants;
1108 // There is no sensible code to be generated for *any* deriving on a
1109 // zero-variant enum. So we just generate a failing expression.
1110 if variants.is_empty() {
1111 return BlockOrExpr(vec![], Some(deriving::call_unreachable(cx, span)));
1114 let prefixes = iter::once("__self".to_string())
1120 .map(|(arg_count, _selflike_arg)| format!("__arg{}", arg_count)),
1122 .collect::<Vec<String>>();
1124 // Build a series of let statements mapping each selflike_arg
1125 // to its discriminant value.
1127 // e.g. for `PartialEq::eq` builds two statements:
1129 // let __self_tag = ::core::intrinsics::discriminant_value(self);
1130 // let __arg1_tag = ::core::intrinsics::discriminant_value(other);
1132 let get_tag_pieces = |cx: &ExtCtxt<'_>| {
1133 let tag_idents: Vec<_> = prefixes
1135 .map(|name| Ident::from_str_and_span(&format!("{}_tag", name), span))
1138 let mut tag_exprs: Vec<_> = tag_idents
1140 .map(|&ident| cx.expr_addr_of(span, cx.expr_ident(span, ident)))
1143 let self_expr = tag_exprs.remove(0);
1144 let other_selflike_exprs = tag_exprs;
1145 let tag_field = FieldInfo { span, name: None, self_expr, other_selflike_exprs };
1147 let tag_let_stmts: Vec<_> = iter::zip(&tag_idents, &selflike_args)
1148 .map(|(&ident, selflike_arg)| {
1149 let variant_value = deriving::call_intrinsic(
1152 sym::discriminant_value,
1153 vec![selflike_arg.clone()],
1155 cx.stmt_let(span, false, ident, variant_value)
1159 (tag_field, tag_let_stmts)
1162 // There are some special cases involving fieldless enums where no
1163 // match is necessary.
1164 let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
1166 if uses_tags && variants.len() > 1 {
1167 // If the type is fieldless and the trait uses the tag and
1168 // there are multiple variants, we need just an operation on
1170 let (tag_field, mut tag_let_stmts) = get_tag_pieces(cx);
1171 let mut tag_check = self.call_substructure_method(
1176 &EnumTag(tag_field, None),
1178 tag_let_stmts.append(&mut tag_check.0);
1179 return BlockOrExpr(tag_let_stmts, tag_check.1);
1182 if variants.len() == 1 {
1183 // If there is a single variant, we don't need an operation on
1184 // the tag(s). Just use the most degenerate result.
1185 return self.call_substructure_method(
1190 &EnumMatching(0, 1, &variants[0], Vec::new()),
1195 // These arms are of the form:
1196 // (Variant1, Variant1, ...) => Body1
1197 // (Variant2, Variant2, ...) => Body2
1199 // where each tuple has length = selflike_args.len()
1200 let mut match_arms: Vec<ast::Arm> = variants
1203 .filter(|&(_, v)| !(self.unify_fieldless_variants && v.data.fields().is_empty()))
1204 .map(|(index, variant)| {
1205 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
1206 // (see "Final wrinkle" note below for why.)
1208 let fields = trait_.create_struct_pattern_fields(cx, &variant.data, &prefixes);
1210 let sp = variant.span.with_ctxt(trait_.span.ctxt());
1211 let variant_path = cx.path(sp, vec![type_ident, variant.ident]);
1212 let by_ref = ByRef::No; // because enums can't be repr(packed)
1213 let mut subpats: Vec<_> = trait_.create_struct_patterns(
1221 // `(VariantK, VariantK, ...)` or just `VariantK`.
1222 let single_pat = if subpats.len() == 1 {
1223 subpats.pop().unwrap()
1225 cx.pat_tuple(span, subpats)
1228 // For the BodyK, we need to delegate to our caller,
1229 // passing it an EnumMatching to indicate which case
1232 // Now, for some given VariantK, we have built up
1233 // expressions for referencing every field of every
1234 // Self arg, assuming all are instances of VariantK.
1235 // Build up code associated with such a case.
1236 let substructure = EnumMatching(index, variants.len(), variant, fields);
1238 .call_substructure_method(
1245 .into_expr(cx, span);
1247 cx.arm(span, single_pat, arm_expr)
1251 // Add a default arm to the match, if necessary.
1252 let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1253 let default = match first_fieldless {
1254 Some(v) if self.unify_fieldless_variants => {
1255 // We need a default case that handles all the fieldless
1256 // variants. The index and actual variant aren't meaningful in
1257 // this case, so just use dummy values.
1259 self.call_substructure_method(
1264 &EnumMatching(0, variants.len(), v, Vec::new()),
1266 .into_expr(cx, span),
1269 _ if variants.len() > 1 && selflike_args.len() > 1 => {
1270 // Because we know that all the arguments will match if we reach
1271 // the match expression we add the unreachable intrinsics as the
1272 // result of the default which should help llvm in optimizing it.
1273 Some(deriving::call_unreachable(cx, span))
1277 if let Some(arm) = default {
1278 match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
1281 // Create a match expression with one arm per discriminant plus
1282 // possibly a default arm, e.g.:
1283 // match (self, other) {
1284 // (Variant1, Variant1, ...) => Body1
1285 // (Variant2, Variant2, ...) => Body2,
1287 // _ => ::core::intrinsics::unreachable()
1289 let get_match_expr = |mut selflike_args: Vec<P<Expr>>| {
1290 let match_arg = if selflike_args.len() == 1 {
1291 selflike_args.pop().unwrap()
1293 cx.expr(span, ast::ExprKind::Tup(selflike_args))
1295 cx.expr_match(span, match_arg, match_arms)
1298 // If the trait uses the tag and there are multiple variants, we need
1299 // to add a tag check operation before the match. Otherwise, the match
1301 if uses_tags && variants.len() > 1 {
1302 let (tag_field, mut tag_let_stmts) = get_tag_pieces(cx);
1304 // Combine a tag check with the match.
1305 let mut tag_check_plus_match = self.call_substructure_method(
1310 &EnumTag(tag_field, Some(get_match_expr(selflike_args))),
1312 tag_let_stmts.append(&mut tag_check_plus_match.0);
1313 BlockOrExpr(tag_let_stmts, tag_check_plus_match.1)
1315 BlockOrExpr(vec![], Some(get_match_expr(selflike_args)))
1319 fn expand_static_enum_method_body(
1321 cx: &mut ExtCtxt<'_>,
1322 trait_: &TraitDef<'_>,
1325 nonselflike_args: &[P<Expr>],
1327 let summary = enum_def
1331 let sp = v.span.with_ctxt(trait_.span.ctxt());
1332 let summary = trait_.summarise_struct(cx, &v.data);
1333 (v.ident, sp, summary)
1336 self.call_substructure_method(
1341 &StaticEnum(enum_def, summary),
1346 // general helper methods.
1347 impl<'a> TraitDef<'a> {
1348 fn summarise_struct(&self, cx: &mut ExtCtxt<'_>, struct_def: &VariantData) -> StaticFields {
1349 let mut named_idents = Vec::new();
1350 let mut just_spans = Vec::new();
1351 for field in struct_def.fields() {
1352 let sp = field.span.with_ctxt(self.span.ctxt());
1354 Some(ident) => named_idents.push((ident, sp)),
1355 _ => just_spans.push(sp),
1359 let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..));
1360 match (just_spans.is_empty(), named_idents.is_empty()) {
1362 cx.span_bug(self.span, "a struct with named and unnamed fields in generic `derive`")
1365 (_, false) => Named(named_idents),
1367 (false, _) => Unnamed(just_spans, is_tuple),
1369 _ => Named(Vec::new()),
1373 fn create_struct_patterns(
1375 cx: &mut ExtCtxt<'_>,
1376 struct_path: ast::Path,
1377 struct_def: &'a VariantData,
1378 prefixes: &[String],
1380 ) -> Vec<P<ast::Pat>> {
1385 struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1386 let sp = struct_field.span.with_ctxt(self.span.ctxt());
1387 let ident = self.mk_pattern_ident(prefix, i);
1388 let path = ident.with_span_pos(sp);
1395 BindingAnnotation(by_ref, Mutability::Not),
1403 let struct_path = struct_path.clone();
1405 VariantData::Struct(..) => {
1406 let field_pats = pieces_iter
1407 .map(|(sp, ident, pat)| {
1408 if ident.is_none() {
1411 "a braced struct with unnamed fields in `derive`",
1415 ident: ident.unwrap(),
1416 is_shorthand: false,
1417 attrs: ast::AttrVec::new(),
1418 id: ast::DUMMY_NODE_ID,
1419 span: pat.span.with_ctxt(self.span.ctxt()),
1421 is_placeholder: false,
1425 cx.pat_struct(self.span, struct_path, field_pats)
1427 VariantData::Tuple(..) => {
1428 let subpats = pieces_iter.map(|(_, _, subpat)| subpat).collect();
1429 cx.pat_tuple_struct(self.span, struct_path, subpats)
1431 VariantData::Unit(..) => cx.pat_path(self.span, struct_path),
1437 fn create_fields<F>(&self, struct_def: &'a VariantData, mk_exprs: F) -> Vec<FieldInfo>
1439 F: Fn(usize, &ast::FieldDef, Span) -> Vec<P<ast::Expr>>,
1445 .map(|(i, struct_field)| {
1446 // For this field, get an expr for each selflike_arg. E.g. for
1447 // `PartialEq::eq`, one for each of `&self` and `other`.
1448 let sp = struct_field.span.with_ctxt(self.span.ctxt());
1449 let mut exprs: Vec<_> = mk_exprs(i, struct_field, sp);
1450 let self_expr = exprs.remove(0);
1451 let other_selflike_exprs = exprs;
1453 span: sp.with_ctxt(self.span.ctxt()),
1454 name: struct_field.ident,
1456 other_selflike_exprs,
1462 fn mk_pattern_ident(&self, prefix: &str, i: usize) -> Ident {
1463 Ident::from_str_and_span(&format!("{}_{}", prefix, i), self.span)
1466 fn create_struct_pattern_fields(
1468 cx: &mut ExtCtxt<'_>,
1469 struct_def: &'a VariantData,
1470 prefixes: &[String],
1471 ) -> Vec<FieldInfo> {
1472 self.create_fields(struct_def, |i, _struct_field, sp| {
1476 let ident = self.mk_pattern_ident(prefix, i);
1477 cx.expr_path(cx.path_ident(sp, ident))
1483 fn create_struct_field_access_fields(
1485 cx: &mut ExtCtxt<'_>,
1486 selflike_args: &[P<Expr>],
1487 struct_def: &'a VariantData,
1489 ) -> Vec<FieldInfo> {
1490 self.create_fields(struct_def, |i, struct_field, sp| {
1493 .map(|selflike_arg| {
1494 // Note: we must use `struct_field.span` rather than `sp` in the
1495 // `unwrap_or_else` case otherwise the hygiene is wrong and we get
1496 // "field `0` of struct `Point` is private" errors on tuple
1498 let mut field_expr = cx.expr(
1500 ast::ExprKind::Field(
1501 selflike_arg.clone(),
1502 struct_field.ident.unwrap_or_else(|| {
1503 Ident::from_str_and_span(&i.to_string(), struct_field.span)
1508 field_expr = cx.expr_block(
1509 cx.block(struct_field.span, vec![cx.stmt_expr(field_expr)]),
1512 cx.expr_addr_of(sp, field_expr)
1519 /// The function passed to `cs_fold` is called repeatedly with a value of this
1520 /// type. It describes one part of the code generation. The result is always an
1522 pub enum CsFold<'a> {
1523 /// The basic case: a field expression for one or more selflike args. E.g.
1524 /// for `PartialEq::eq` this is something like `self.x == other.x`.
1525 Single(&'a FieldInfo),
1527 /// The combination of two field expressions. E.g. for `PartialEq::eq` this
1528 /// is something like `<field1 equality> && <field2 equality>`.
1529 Combine(Span, P<Expr>, P<Expr>),
1531 // The fallback case for a struct or enum variant with no fields.
1535 /// Folds over fields, combining the expressions for each field in a sequence.
1536 /// Statics may not be folded over.
1539 cx: &mut ExtCtxt<'_>,
1541 substructure: &Substructure<'_>,
1545 F: FnMut(&mut ExtCtxt<'_>, CsFold<'_>) -> P<Expr>,
1547 match substructure.fields {
1548 EnumMatching(.., all_fields) | Struct(_, all_fields) => {
1549 if all_fields.is_empty() {
1550 return f(cx, CsFold::Fieldless);
1553 let (base_field, rest) = if use_foldl {
1554 all_fields.split_first().unwrap()
1556 all_fields.split_last().unwrap()
1559 let base_expr = f(cx, CsFold::Single(base_field));
1561 let op = |old, field: &FieldInfo| {
1562 let new = f(cx, CsFold::Single(field));
1563 f(cx, CsFold::Combine(field.span, old, new))
1567 rest.iter().fold(base_expr, op)
1569 rest.iter().rfold(base_expr, op)
1572 EnumTag(tag_field, match_expr) => {
1573 let tag_check_expr = f(cx, CsFold::Single(tag_field));
1574 if let Some(match_expr) = match_expr {
1576 f(cx, CsFold::Combine(trait_span, tag_check_expr, match_expr.clone()))
1578 f(cx, CsFold::Combine(trait_span, match_expr.clone(), tag_check_expr))
1584 StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span, "static function in `derive`"),