1use std::cell::RefCell;
178use std::ops::Not;
179use std::{iter, vec};
180
181pub(crate) use StaticFields::*;
182pub(crate) use SubstructureFields::*;
183use rustc_ast::token::{IdentIsRaw, LitKind, Token, TokenKind};
184use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenTree};
185use rustc_ast::{
186 self as ast, AnonConst, AttrArgs, BindingMode, ByRef, DelimArgs, EnumDef, Expr, GenericArg,
187 GenericParamKind, Generics, Mutability, PatKind, Safety, VariantData,
188};
189use rustc_attr_parsing::AttributeParser;
190use rustc_expand::base::{Annotatable, ExtCtxt};
191use rustc_hir::Attribute;
192use rustc_hir::attrs::{AttributeKind, ReprPacked};
193use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
194use thin_vec::{ThinVec, thin_vec};
195use ty::{Bounds, Path, Ref, Self_, Ty};
196
197use crate::{deriving, diagnostics};
198
199pub(crate) mod ty;
200
201pub(crate) struct TraitDef<'a> {
202 pub span: Span,
204
205 pub path: Path,
207
208 pub skip_path_as_bound: bool,
210
211 pub needs_copy_as_bound_if_packed: bool,
213
214 pub additional_bounds: Vec<Ty>,
217
218 pub supports_unions: bool,
220
221 pub methods: Vec<MethodDef<'a>>,
222
223 pub associated_types: Vec<(Ident, Ty)>,
224
225 pub is_const: bool,
226
227 pub is_staged_api_crate: bool,
228
229 pub safety: Safety,
231
232 pub document: bool,
234}
235
236pub(crate) struct MethodDef<'a> {
237 pub name: Symbol,
239 pub generics: Bounds,
241
242 pub explicit_self: bool,
244
245 pub nonself_args: Vec<(Ty, Symbol)>,
247
248 pub ret_ty: Ty,
250
251 pub attributes: ast::AttrVec,
252
253 pub fieldless_variants_strategy: FieldlessVariantsStrategy,
254
255 pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
256}
257
258#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for FieldlessVariantsStrategy {
#[inline]
fn eq(&self, other: &FieldlessVariantsStrategy) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
260pub(crate) enum FieldlessVariantsStrategy {
261 Unify,
265 Default,
268 SpecializeIfAllVariantsFieldless,
272}
273
274pub(crate) struct Substructure<'a> {
276 pub type_ident: Ident,
278 pub nonselflike_args: &'a [Box<Expr>],
281 pub fields: &'a SubstructureFields<'a>,
282}
283
284pub(crate) struct FieldInfo {
286 pub span: Span,
287 pub name: Option<Ident>,
290 pub self_expr: Box<Expr>,
293 pub other_selflike_exprs: Vec<Box<Expr>>,
296 pub maybe_scalar: bool,
297}
298
299#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsTuple { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsTuple {
#[inline]
fn clone(&self) -> IsTuple { *self }
}Clone)]
300pub(crate) enum IsTuple {
301 No,
302 Yes,
303}
304
305pub(crate) enum StaticFields<'a> {
307 Unnamed(Vec<Span>, IsTuple),
309 Named(Vec<(Ident, Span, Option<&'a AnonConst>)>),
311}
312
313pub(crate) enum SubstructureFields<'a> {
315 Struct(&'a ast::VariantData, Vec<FieldInfo>),
317
318 AllFieldlessEnum(&'a ast::EnumDef),
322
323 EnumMatching(&'a ast::Variant, Vec<FieldInfo>),
327
328 EnumDiscr(FieldInfo, Option<Box<Expr>>),
332
333 StaticStruct(&'a ast::VariantData, StaticFields<'a>),
335
336 StaticEnum(&'a ast::EnumDef),
338}
339
340pub(crate) type CombineSubstructureFunc<'a> =
343 Box<dyn FnMut(&ExtCtxt<'_>, Span, &Substructure<'_>) -> BlockOrExpr + 'a>;
344
345pub(crate) fn combine_substructure(
346 f: CombineSubstructureFunc<'_>,
347) -> RefCell<CombineSubstructureFunc<'_>> {
348 RefCell::new(f)
349}
350
351struct TypeParameter {
352 bound_generic_params: ThinVec<ast::GenericParam>,
353 ty: Box<ast::Ty>,
354}
355
356pub(crate) struct BlockOrExpr(ThinVec<ast::Stmt>, Option<Box<Expr>>);
363
364impl BlockOrExpr {
365 pub(crate) fn new_stmts(stmts: ThinVec<ast::Stmt>) -> BlockOrExpr {
366 BlockOrExpr(stmts, None)
367 }
368
369 pub(crate) fn new_expr(expr: Box<Expr>) -> BlockOrExpr {
370 BlockOrExpr(ThinVec::new(), Some(expr))
371 }
372
373 pub(crate) fn new_mixed(stmts: ThinVec<ast::Stmt>, expr: Option<Box<Expr>>) -> BlockOrExpr {
374 BlockOrExpr(stmts, expr)
375 }
376
377 fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> Box<ast::Block> {
379 if let Some(expr) = self.1 {
380 self.0.push(cx.stmt_expr(expr));
381 }
382 cx.block(span, self.0)
383 }
384
385 fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> Box<Expr> {
387 if self.0.is_empty() {
388 match self.1 {
389 None => cx.expr_block(cx.block(span, ThinVec::new())),
390 Some(expr) => expr,
391 }
392 } else if let [stmt] = self.0.as_slice()
393 && let ast::StmtKind::Expr(expr) = &stmt.kind
394 && self.1.is_none()
395 {
396 expr.clone()
398 } else {
399 cx.expr_block(self.into_block(cx, span))
401 }
402 }
403}
404
405fn find_type_parameters(
410 ty: &ast::Ty,
411 ty_param_names: &[Symbol],
412 cx: &ExtCtxt<'_>,
413) -> Vec<TypeParameter> {
414 use rustc_ast::visit;
415
416 struct Visitor<'a, 'b> {
417 cx: &'a ExtCtxt<'b>,
418 ty_param_names: &'a [Symbol],
419 bound_generic_params_stack: ThinVec<ast::GenericParam>,
420 type_params: Vec<TypeParameter>,
421 }
422
423 impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
424 fn visit_ty(&mut self, ty: &'a ast::Ty) {
425 let stack_len = self.bound_generic_params_stack.len();
426 if let ast::TyKind::FnPtr(fn_ptr) = &ty.kind
427 && !fn_ptr.generic_params.is_empty()
428 {
429 self.bound_generic_params_stack.extend(fn_ptr.generic_params.iter().cloned());
432 }
433
434 if let ast::TyKind::Path(_, path) = &ty.kind
435 && let Some(segment) = path.segments.first()
436 && self.ty_param_names.contains(&segment.ident.name)
437 {
438 self.type_params.push(TypeParameter {
439 bound_generic_params: self.bound_generic_params_stack.clone(),
440 ty: Box::new(ty.clone()),
441 });
442 }
443
444 visit::walk_ty(self, ty);
445 self.bound_generic_params_stack.truncate(stack_len);
446 }
447
448 fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
450 let stack_len = self.bound_generic_params_stack.len();
451 self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
452
453 visit::walk_poly_trait_ref(self, trait_ref);
454
455 self.bound_generic_params_stack.truncate(stack_len);
456 }
457
458 fn visit_mac_call(&mut self, mac: &ast::MacCall) {
459 self.cx.dcx().emit_err(diagnostics::DeriveMacroCall { span: mac.span() });
460 }
461 }
462
463 let mut visitor = Visitor {
464 cx,
465 ty_param_names,
466 bound_generic_params_stack: ThinVec::new(),
467 type_params: Vec::new(),
468 };
469 visit::Visitor::visit_ty(&mut visitor, ty);
470
471 visitor.type_params
472}
473
474impl<'a> TraitDef<'a> {
475 pub(crate) fn expand(
476 self,
477 cx: &ExtCtxt<'_>,
478 mitem: &ast::MetaItem,
479 item: &'a Annotatable,
480 push: &mut dyn FnMut(Annotatable),
481 ) {
482 self.expand_ext(cx, mitem, item, push, false);
483 }
484
485 pub(crate) fn expand_ext(
486 self,
487 cx: &ExtCtxt<'_>,
488 mitem: &ast::MetaItem,
489 item: &'a Annotatable,
490 push: &mut dyn FnMut(Annotatable),
491 from_scratch: bool,
492 ) {
493 match item {
494 Annotatable::Item(item) => {
495 let is_packed = #[allow(non_exhaustive_omitted_patterns)] match AttributeParser::parse_limited(cx.sess,
&item.attrs, &[sym::repr]) {
Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if
reprs.iter().any(|(x, _)|
#[allow(non_exhaustive_omitted_patterns)] match x {
ReprPacked(..) => true,
_ => false,
}) => true,
_ => false,
}matches!(
496 AttributeParser::parse_limited(cx.sess, &item.attrs, &[sym::repr]),
497 Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if reprs.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
498 );
499
500 let newitem = match &item.kind {
501 ast::ItemKind::Struct(ident, generics, struct_def) => self.expand_struct_def(
502 cx,
503 struct_def,
504 *ident,
505 generics,
506 from_scratch,
507 is_packed,
508 ),
509 ast::ItemKind::Enum(ident, generics, enum_def) => {
510 self.expand_enum_def(cx, enum_def, *ident, generics, from_scratch)
516 }
517 ast::ItemKind::Union(ident, generics, struct_def) => {
518 if self.supports_unions {
519 self.expand_struct_def(
520 cx,
521 struct_def,
522 *ident,
523 generics,
524 from_scratch,
525 is_packed,
526 )
527 } else {
528 cx.dcx().emit_err(diagnostics::DeriveUnion { span: mitem.span });
529 return;
530 }
531 }
532 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
533 };
534 let mut attrs = newitem.attrs.clone();
537 attrs.extend(
538 item.attrs
539 .iter()
540 .filter(|a| {
541 a.has_any_name(&[
542 sym::allow,
543 sym::warn,
544 sym::deny,
545 sym::forbid,
546 sym::stable,
547 sym::unstable,
548 ])
549 })
550 .cloned(),
551 );
552 push(Annotatable::Item(Box::new(ast::Item { attrs, ..(*newitem).clone() })))
553 }
554 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
555 }
556 }
557
558 fn create_derived_impl(
594 &self,
595 cx: &ExtCtxt<'_>,
596 type_ident: Ident,
597 generics: &Generics,
598 field_tys: Vec<&ast::Ty>,
599 methods: Vec<Box<ast::AssocItem>>,
600 is_packed: bool,
601 ) -> Box<ast::Item> {
602 let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
603
604 let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
606 Box::new(ast::AssocItem {
607 id: ast::DUMMY_NODE_ID,
608 span: self.span,
609 vis: ast::Visibility {
610 span: self.span.shrink_to_lo(),
611 kind: ast::VisibilityKind::Inherited,
612 },
613 attrs: ast::AttrVec::new(),
614 kind: ast::AssocItemKind::Type(Box::new(ast::TyAlias {
615 defaultness: ast::Defaultness::Implicit,
616 ident,
617 generics: Generics::default(),
618 after_where_clause: ast::WhereClause::default(),
619 bounds: ThinVec::new(),
620 ty: Some(type_def.to_ty(cx, self.span, type_ident, generics)),
621 })),
622 tokens: None,
623 })
624 });
625
626 let mut where_clause = ast::WhereClause::default();
627 where_clause.span = generics.where_clause.span;
628 let ctxt = self.span.ctxt();
629 let span = generics.span.with_ctxt(ctxt);
630
631 let params: ThinVec<_> = generics
633 .params
634 .iter()
635 .map(|param| match ¶m.kind {
636 GenericParamKind::Lifetime { .. } => param.clone(),
637 GenericParamKind::Type { .. } => {
638 let span = param.ident.span.with_ctxt(ctxt);
641 let bounds: ThinVec<_> = self
642 .additional_bounds
643 .iter()
644 .map(|p| {
645 cx.trait_bound(p.to_path(cx, span, type_ident, generics), self.is_const)
646 })
647 .chain(
648 self.skip_path_as_bound.not().then(|| {
650 let mut trait_path = trait_path.clone();
651 trait_path.span = span;
652 cx.trait_bound(trait_path, self.is_const)
653 }),
654 )
655 .chain({
656 if is_packed && self.needs_copy_as_bound_if_packed {
658 let p = generic::ty::Path::new({
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[sym::marker, sym::Copy]))
})deriving::path_std!(marker::Copy);
659 Some(cx.trait_bound(
660 p.to_path(cx, span, type_ident, generics),
661 self.is_const,
662 ))
663 } else {
664 None
665 }
666 })
667 .chain(
668 param.bounds.iter().cloned(),
670 )
671 .collect();
672
673 cx.typaram(span, param.ident, bounds, None)
674 }
675 GenericParamKind::Const { ty, span, .. } => {
676 let const_nodefault_kind = GenericParamKind::Const {
677 ty: ty.clone(),
678 span: span.with_ctxt(ctxt),
679
680 default: None,
682 };
683 let mut param_clone = param.clone();
684 param_clone.kind = const_nodefault_kind;
685 param_clone
686 }
687 })
688 .map(|mut param| {
689 param.attrs.clear();
692 param
693 })
694 .collect();
695
696 where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
698 ast::WherePredicate {
699 attrs: clause.attrs.clone(),
700 kind: clause.kind.clone(),
701 id: ast::DUMMY_NODE_ID,
702 span: clause.span.with_ctxt(ctxt),
703 is_placeholder: false,
704 }
705 }));
706
707 let ty_param_names: Vec<Symbol> = params
708 .iter()
709 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Type { .. } => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Type { .. }))
710 .map(|ty_param| ty_param.ident.name)
711 .collect();
712
713 if !ty_param_names.is_empty() {
714 for field_ty in field_tys {
715 let field_ty_params = find_type_parameters(&field_ty, &ty_param_names, cx);
716
717 for field_ty_param in field_ty_params {
718 if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
720 && let [sole_segment] = &*p.segments
721 && ty_param_names.contains(&sole_segment.ident.name)
722 {
723 continue;
724 }
725 let mut bounds: ThinVec<_> = self
726 .additional_bounds
727 .iter()
728 .map(|p| {
729 cx.trait_bound(
730 p.to_path(cx, self.span, type_ident, generics),
731 self.is_const,
732 )
733 })
734 .collect();
735
736 if !self.skip_path_as_bound {
738 bounds.push(cx.trait_bound(trait_path.clone(), self.is_const));
739 }
740
741 if is_packed && self.needs_copy_as_bound_if_packed {
743 let p = generic::ty::Path::new({
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[sym::marker, sym::Copy]))
})deriving::path_std!(marker::Copy);
744 bounds.push(cx.trait_bound(
745 p.to_path(cx, self.span, type_ident, generics),
746 self.is_const,
747 ));
748 }
749
750 if !bounds.is_empty() {
751 let predicate = ast::WhereBoundPredicate {
752 bound_generic_params: field_ty_param.bound_generic_params,
753 bounded_ty: field_ty_param.ty,
754 bounds,
755 };
756
757 let kind = ast::WherePredicateKind::BoundPredicate(predicate);
758 let predicate = ast::WherePredicate {
759 attrs: ThinVec::new(),
760 kind,
761 id: ast::DUMMY_NODE_ID,
762 span: self.span,
763 is_placeholder: false,
764 };
765 where_clause.predicates.push(predicate);
766 }
767 }
768 }
769 }
770
771 let trait_generics = Generics { params, where_clause, span };
772
773 let trait_ref = cx.trait_ref(trait_path);
775
776 let self_params: Vec<_> = generics
777 .params
778 .iter()
779 .map(|param| match param.kind {
780 GenericParamKind::Lifetime { .. } => {
781 GenericArg::Lifetime(cx.lifetime(param.ident.span.with_ctxt(ctxt), param.ident))
782 }
783 GenericParamKind::Type { .. } => {
784 GenericArg::Type(cx.ty_ident(param.ident.span.with_ctxt(ctxt), param.ident))
785 }
786 GenericParamKind::Const { .. } => {
787 GenericArg::Const(cx.const_ident(param.ident.span.with_ctxt(ctxt), param.ident))
788 }
789 })
790 .collect();
791
792 let path =
794 cx.path_all(type_ident.span.with_ctxt(ctxt), false, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[type_ident]))vec![type_ident], self_params);
795 let self_type = cx.ty_path(path);
796 let rustc_const_unstable =
797 cx.path_ident(self.span, Ident::new(sym::rustc_const_unstable, self.span));
798
799 let mut attrs = {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.attr_word(sym::automatically_derived, self.span));
vec
}thin_vec![cx.attr_word(sym::automatically_derived, self.span),];
800
801 if self.is_const && self.is_staged_api_crate {
805 attrs.push(
806 cx.attr_nested(
807 rustc_ast::AttrItem {
808 unsafety: Safety::Default,
809 path: rustc_const_unstable,
810 args: AttrArgs::Delimited(DelimArgs {
811 dspan: DelimSpan::from_single(self.span),
812 delim: rustc_ast::token::Delimiter::Parenthesis,
813 tokens: [
814 TokenKind::Ident(sym::feature, IdentIsRaw::No),
815 TokenKind::Eq,
816 TokenKind::lit(LitKind::Str, sym::derive_const, None),
817 TokenKind::Comma,
818 TokenKind::Ident(sym::issue, IdentIsRaw::No),
819 TokenKind::Eq,
820 TokenKind::lit(LitKind::Str, sym::derive_const_issue, None),
821 ]
822 .into_iter()
823 .map(|kind| {
824 TokenTree::Token(Token { kind, span: self.span }, Spacing::Alone)
825 })
826 .collect(),
827 }),
828 span: self.span,
829 },
830 self.span,
831 ),
832 )
833 }
834
835 if !self.document {
836 attrs.push(cx.attr_nested_word(sym::doc, sym::hidden, self.span));
837 }
838
839 cx.item(
840 self.span,
841 attrs,
842 ast::ItemKind::Impl(ast::Impl {
843 generics: trait_generics,
844 of_trait: Some(Box::new(ast::TraitImplHeader {
845 safety: self.safety,
846 polarity: ast::ImplPolarity::Positive,
847 defaultness: ast::Defaultness::Implicit,
848 trait_ref,
849 })),
850 constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },
851 self_ty: self_type,
852 items: methods.into_iter().chain(associated_types).collect(),
853 }),
854 )
855 }
856
857 fn expand_struct_def(
858 &self,
859 cx: &ExtCtxt<'_>,
860 struct_def: &'a VariantData,
861 type_ident: Ident,
862 generics: &Generics,
863 from_scratch: bool,
864 is_packed: bool,
865 ) -> Box<ast::Item> {
866 let field_tys = Vec::from_iter(struct_def.fields().iter().map(|field| &*field.ty));
867
868 let methods = self
869 .methods
870 .iter()
871 .map(|method_def| {
872 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
873 method_def.extract_arg_details(cx, self, type_ident, generics);
874
875 let body = if from_scratch || method_def.is_static() {
876 method_def.expand_static_struct_method_body(
877 cx,
878 self,
879 struct_def,
880 type_ident,
881 &nonselflike_args,
882 )
883 } else {
884 method_def.expand_struct_method_body(
885 cx,
886 self,
887 struct_def,
888 type_ident,
889 &selflike_args,
890 &nonselflike_args,
891 is_packed,
892 )
893 };
894
895 method_def.create_method(
896 cx,
897 self,
898 type_ident,
899 generics,
900 explicit_self,
901 nonself_arg_tys,
902 body,
903 )
904 })
905 .collect();
906
907 self.create_derived_impl(cx, type_ident, generics, field_tys, methods, is_packed)
908 }
909
910 fn expand_enum_def(
911 &self,
912 cx: &ExtCtxt<'_>,
913 enum_def: &'a EnumDef,
914 type_ident: Ident,
915 generics: &Generics,
916 from_scratch: bool,
917 ) -> Box<ast::Item> {
918 let field_tys = Vec::from_iter(
919 enum_def
920 .variants
921 .iter()
922 .flat_map(|variant| variant.data.fields())
923 .map(|field| &*field.ty),
924 );
925
926 let methods = self
927 .methods
928 .iter()
929 .map(|method_def| {
930 let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
931 method_def.extract_arg_details(cx, self, type_ident, generics);
932
933 let body = if from_scratch || method_def.is_static() {
934 method_def.expand_static_enum_method_body(
935 cx,
936 self,
937 enum_def,
938 type_ident,
939 &nonselflike_args,
940 )
941 } else {
942 method_def.expand_enum_method_body(
943 cx,
944 self,
945 enum_def,
946 type_ident,
947 selflike_args,
948 &nonselflike_args,
949 )
950 };
951
952 method_def.create_method(
953 cx,
954 self,
955 type_ident,
956 generics,
957 explicit_self,
958 nonself_arg_tys,
959 body,
960 )
961 })
962 .collect();
963
964 let is_packed = false; self.create_derived_impl(cx, type_ident, generics, field_tys, methods, is_packed)
966 }
967}
968
969impl<'a> MethodDef<'a> {
970 fn call_substructure_method(
971 &self,
972 cx: &ExtCtxt<'_>,
973 trait_: &TraitDef<'_>,
974 type_ident: Ident,
975 nonselflike_args: &[Box<Expr>],
976 fields: &SubstructureFields<'_>,
977 ) -> BlockOrExpr {
978 let span = trait_.span;
979 let substructure = Substructure { type_ident, nonselflike_args, fields };
980 let mut f = self.combine_substructure.borrow_mut();
981 let f: &mut CombineSubstructureFunc<'_> = &mut *f;
982 f(cx, span, &substructure)
983 }
984
985 fn is_static(&self) -> bool {
986 !self.explicit_self
987 }
988
989 fn extract_arg_details(
997 &self,
998 cx: &ExtCtxt<'_>,
999 trait_: &TraitDef<'_>,
1000 type_ident: Ident,
1001 generics: &Generics,
1002 ) -> (Option<ast::ExplicitSelf>, ThinVec<Box<Expr>>, Vec<Box<Expr>>, Vec<(Ident, Box<ast::Ty>)>)
1003 {
1004 let mut selflike_args = ThinVec::new();
1005 let mut nonselflike_args = Vec::new();
1006 let mut nonself_arg_tys = Vec::new();
1007 let span = trait_.span;
1008
1009 let explicit_self = self.explicit_self.then(|| {
1010 let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
1011 selflike_args.push(self_expr);
1012 explicit_self
1013 });
1014
1015 for (ty, name) in self.nonself_args.iter() {
1016 let ast_ty = ty.to_ty(cx, span, type_ident, generics);
1017 let ident = Ident::new(*name, span);
1018 nonself_arg_tys.push((ident, ast_ty));
1019
1020 let arg_expr = cx.expr_ident(span, ident);
1021
1022 match ty {
1023 Ref(Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
1025 Self_ => cx.dcx().span_bug(span, "`Self` in non-return position"),
1026 _ => nonselflike_args.push(arg_expr),
1027 }
1028 }
1029
1030 (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys)
1031 }
1032
1033 fn create_method(
1034 &self,
1035 cx: &ExtCtxt<'_>,
1036 trait_: &TraitDef<'_>,
1037 type_ident: Ident,
1038 generics: &Generics,
1039 explicit_self: Option<ast::ExplicitSelf>,
1040 nonself_arg_tys: Vec<(Ident, Box<ast::Ty>)>,
1041 body: BlockOrExpr,
1042 ) -> Box<ast::AssocItem> {
1043 let span = trait_.span;
1044 let fn_generics = self.generics.to_generics(cx, span, type_ident, generics);
1046
1047 let args = {
1048 let self_arg = explicit_self.map(|explicit_self| {
1049 let ident = Ident::new(kw::SelfLower, span);
1050 ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident)
1051 });
1052 let nonself_args =
1053 nonself_arg_tys.into_iter().map(|(name, ty)| cx.param(span, name, ty));
1054 self_arg.into_iter().chain(nonself_args).collect()
1055 };
1056
1057 let ret_type = if let Ty::Unit = &self.ret_ty {
1058 ast::FnRetTy::Default(span)
1059 } else {
1060 ast::FnRetTy::Ty(self.ret_ty.to_ty(cx, span, type_ident, generics))
1061 };
1062
1063 let method_ident = Ident::new(self.name, span);
1064 let fn_decl = cx.fn_decl(args, ret_type);
1065 let body_block = body.into_block(cx, span);
1066
1067 let trait_lo_sp = span.shrink_to_lo();
1068
1069 let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
1070 let defaultness = ast::Defaultness::Implicit;
1071
1072 Box::new(ast::AssocItem {
1074 id: ast::DUMMY_NODE_ID,
1075 attrs: self.attributes.clone(),
1076 span,
1077 vis: ast::Visibility { span: trait_lo_sp, kind: ast::VisibilityKind::Inherited },
1078 kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
1079 defaultness,
1080 sig,
1081 ident: method_ident,
1082 generics: fn_generics,
1083 contract: None,
1084 body: Some(body_block),
1085 define_opaque: None,
1086 eii_impls: ThinVec::new(),
1087 })),
1088 tokens: None,
1089 })
1090 }
1091
1092 fn expand_struct_method_body<'b>(
1128 &self,
1129 cx: &ExtCtxt<'_>,
1130 trait_: &TraitDef<'b>,
1131 struct_def: &'b VariantData,
1132 type_ident: Ident,
1133 selflike_args: &[Box<Expr>],
1134 nonselflike_args: &[Box<Expr>],
1135 is_packed: bool,
1136 ) -> BlockOrExpr {
1137 if !(selflike_args.len() == 1 || selflike_args.len() == 2) {
::core::panicking::panic("assertion failed: selflike_args.len() == 1 || selflike_args.len() == 2")
};assert!(selflike_args.len() == 1 || selflike_args.len() == 2);
1138
1139 let selflike_fields =
1140 trait_.create_struct_field_access_fields(cx, selflike_args, struct_def, is_packed);
1141 self.call_substructure_method(
1142 cx,
1143 trait_,
1144 type_ident,
1145 nonselflike_args,
1146 &Struct(struct_def, selflike_fields),
1147 )
1148 }
1149
1150 fn expand_static_struct_method_body(
1151 &self,
1152 cx: &ExtCtxt<'_>,
1153 trait_: &TraitDef<'a>,
1154 struct_def: &'a VariantData,
1155 type_ident: Ident,
1156 nonselflike_args: &[Box<Expr>],
1157 ) -> BlockOrExpr {
1158 let summary = trait_.summarise_struct(cx, struct_def);
1159
1160 self.call_substructure_method(
1161 cx,
1162 trait_,
1163 type_ident,
1164 nonselflike_args,
1165 &StaticStruct(struct_def, summary),
1166 )
1167 }
1168
1169 fn expand_enum_method_body<'b>(
1205 &self,
1206 cx: &ExtCtxt<'_>,
1207 trait_: &TraitDef<'b>,
1208 enum_def: &'b EnumDef,
1209 type_ident: Ident,
1210 mut selflike_args: ThinVec<Box<Expr>>,
1211 nonselflike_args: &[Box<Expr>],
1212 ) -> BlockOrExpr {
1213 if !!selflike_args.is_empty() {
{
::core::panicking::panic_fmt(format_args!("static methods must use `expand_static_enum_method_body`"));
}
};assert!(
1214 !selflike_args.is_empty(),
1215 "static methods must use `expand_static_enum_method_body`",
1216 );
1217
1218 let span = trait_.span;
1219 let variants = &enum_def.variants;
1220
1221 let unify_fieldless_variants =
1223 self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify;
1224
1225 if variants.is_empty() {
1229 selflike_args.truncate(1);
1230 let match_arg = cx.expr_deref(span, selflike_args.pop().unwrap());
1231 let match_arms = ThinVec::new();
1232 let expr = cx.expr_match(span, match_arg, match_arms);
1233 return BlockOrExpr(ThinVec::new(), Some(expr));
1234 }
1235
1236 let prefixes = iter::once("__self".to_string())
1237 .chain(
1238 selflike_args
1239 .iter()
1240 .enumerate()
1241 .skip(1)
1242 .map(|(arg_count, _selflike_arg)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__arg{0}", arg_count))
})format!("__arg{arg_count}")),
1243 )
1244 .collect::<Vec<String>>();
1245
1246 let get_discr_pieces = |cx: &ExtCtxt<'_>| {
1255 let discr_idents: Vec<_> = prefixes
1256 .iter()
1257 .map(|name| Ident::from_str_and_span(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_discr", name))
})format!("{name}_discr"), span))
1258 .collect();
1259
1260 let mut discr_exprs: Vec<_> = discr_idents
1261 .iter()
1262 .map(|&ident| cx.expr_addr_of(span, cx.expr_ident(span, ident)))
1263 .collect();
1264
1265 let self_expr = discr_exprs.remove(0);
1266 let other_selflike_exprs = discr_exprs;
1267 let discr_field =
1268 FieldInfo { span, name: None, self_expr, other_selflike_exprs, maybe_scalar: true };
1269
1270 let discr_let_stmts: ThinVec<_> = iter::zip(&discr_idents, &selflike_args)
1271 .map(|(&ident, selflike_arg)| {
1272 let variant_value = deriving::call_intrinsic(
1273 cx,
1274 span,
1275 sym::discriminant_value,
1276 {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(selflike_arg.clone());
vec
}thin_vec![selflike_arg.clone()],
1277 );
1278 cx.stmt_let(span, false, ident, variant_value)
1279 })
1280 .collect();
1281
1282 (discr_field, discr_let_stmts)
1283 };
1284
1285 let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
1288 if all_fieldless {
1289 if variants.len() > 1 {
1290 match self.fieldless_variants_strategy {
1291 FieldlessVariantsStrategy::Unify => {
1292 let (discr_field, mut discr_let_stmts) = get_discr_pieces(cx);
1296 let mut discr_check = self.call_substructure_method(
1297 cx,
1298 trait_,
1299 type_ident,
1300 nonselflike_args,
1301 &EnumDiscr(discr_field, None),
1302 );
1303 discr_let_stmts.append(&mut discr_check.0);
1304 return BlockOrExpr(discr_let_stmts, discr_check.1);
1305 }
1306 FieldlessVariantsStrategy::SpecializeIfAllVariantsFieldless => {
1307 return self.call_substructure_method(
1308 cx,
1309 trait_,
1310 type_ident,
1311 nonselflike_args,
1312 &AllFieldlessEnum(enum_def),
1313 );
1314 }
1315 FieldlessVariantsStrategy::Default => (),
1316 }
1317 } else if let [variant] = variants.as_slice() {
1318 return self.call_substructure_method(
1321 cx,
1322 trait_,
1323 type_ident,
1324 nonselflike_args,
1325 &EnumMatching(variant, Vec::new()),
1326 );
1327 }
1328 }
1329
1330 let mut match_arms: ThinVec<ast::Arm> = variants
1336 .iter()
1337 .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty()))
1338 .map(|variant| {
1339 let fields = trait_.create_struct_pattern_fields(cx, &variant.data, &prefixes);
1343
1344 let sp = variant.span.with_ctxt(trait_.span.ctxt());
1345 let variant_path = cx.path(sp, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[type_ident, variant.ident]))vec![type_ident, variant.ident]);
1346 let by_ref = ByRef::No; let mut subpats = trait_.create_struct_patterns(
1348 cx,
1349 variant_path,
1350 &variant.data,
1351 &prefixes,
1352 by_ref,
1353 );
1354
1355 let single_pat = if subpats.len() == 1 {
1357 subpats.pop().unwrap()
1358 } else {
1359 cx.pat_tuple(span, subpats)
1360 };
1361
1362 let substructure = EnumMatching(variant, fields);
1371 let arm_expr = self
1372 .call_substructure_method(
1373 cx,
1374 trait_,
1375 type_ident,
1376 nonselflike_args,
1377 &substructure,
1378 )
1379 .into_expr(cx, span);
1380
1381 cx.arm(span, single_pat, arm_expr)
1382 })
1383 .collect();
1384
1385 let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1387 let default = match first_fieldless {
1388 Some(v) if unify_fieldless_variants => {
1389 Some(
1393 self.call_substructure_method(
1394 cx,
1395 trait_,
1396 type_ident,
1397 nonselflike_args,
1398 &EnumMatching(v, Vec::new()),
1399 )
1400 .into_expr(cx, span),
1401 )
1402 }
1403 _ if variants.len() > 1 && selflike_args.len() > 1 => {
1404 Some(deriving::call_unreachable(cx, span))
1408 }
1409 _ => None,
1410 };
1411 if let Some(arm) = default {
1412 match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
1413 }
1414
1415 let get_match_expr = |mut selflike_args: ThinVec<Box<Expr>>| {
1424 let match_arg = if selflike_args.len() == 1 {
1425 selflike_args.pop().unwrap()
1426 } else {
1427 cx.expr(span, ast::ExprKind::Tup(selflike_args))
1428 };
1429 cx.expr_match(span, match_arg, match_arms)
1430 };
1431
1432 if unify_fieldless_variants && variants.len() > 1 {
1436 let (discr_field, mut discr_let_stmts) = get_discr_pieces(cx);
1437
1438 let mut discr_check_plus_match = self.call_substructure_method(
1440 cx,
1441 trait_,
1442 type_ident,
1443 nonselflike_args,
1444 &EnumDiscr(discr_field, Some(get_match_expr(selflike_args))),
1445 );
1446 discr_let_stmts.append(&mut discr_check_plus_match.0);
1447 BlockOrExpr(discr_let_stmts, discr_check_plus_match.1)
1448 } else {
1449 BlockOrExpr(ThinVec::new(), Some(get_match_expr(selflike_args)))
1450 }
1451 }
1452
1453 fn expand_static_enum_method_body(
1454 &self,
1455 cx: &ExtCtxt<'_>,
1456 trait_: &TraitDef<'_>,
1457 enum_def: &EnumDef,
1458 type_ident: Ident,
1459 nonselflike_args: &[Box<Expr>],
1460 ) -> BlockOrExpr {
1461 self.call_substructure_method(
1462 cx,
1463 trait_,
1464 type_ident,
1465 nonselflike_args,
1466 &StaticEnum(enum_def),
1467 )
1468 }
1469}
1470
1471impl<'a> TraitDef<'a> {
1473 fn summarise_struct(&self, cx: &ExtCtxt<'_>, struct_def: &'a VariantData) -> StaticFields<'a> {
1474 let mut named_idents = Vec::new();
1475 let mut just_spans = Vec::new();
1476 for field in struct_def.fields() {
1477 let sp = field.span.with_ctxt(self.span.ctxt());
1478 match field.ident {
1479 Some(ident) => named_idents.push((ident, sp, field.default_value())),
1480 _ => just_spans.push(sp),
1481 }
1482 }
1483
1484 let is_tuple = match struct_def {
1485 ast::VariantData::Tuple(..) => IsTuple::Yes,
1486 _ => IsTuple::No,
1487 };
1488 match (just_spans.is_empty(), named_idents.is_empty()) {
1489 (false, false) => cx
1490 .dcx()
1491 .span_bug(self.span, "a struct with named and unnamed fields in generic `derive`"),
1492 (_, false) => Named(named_idents),
1494 (false, _) => Unnamed(just_spans, is_tuple),
1496 _ => Named(Vec::new()),
1498 }
1499 }
1500
1501 fn create_struct_patterns(
1502 &self,
1503 cx: &ExtCtxt<'_>,
1504 struct_path: ast::Path,
1505 struct_def: &'a VariantData,
1506 prefixes: &[String],
1507 by_ref: ByRef,
1508 ) -> ThinVec<ast::Pat> {
1509 prefixes
1510 .iter()
1511 .map(|prefix| {
1512 let pieces_iter =
1513 struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1514 let sp = struct_field.span.with_ctxt(self.span.ctxt());
1515 let ident = self.mk_pattern_ident(prefix, i);
1516 let path = ident.with_span_pos(sp);
1517 (
1518 sp,
1519 struct_field.ident,
1520 cx.pat(
1521 path.span,
1522 PatKind::Ident(BindingMode(by_ref, Mutability::Not), path, None),
1523 ),
1524 )
1525 });
1526
1527 let struct_path = struct_path.clone();
1528 match *struct_def {
1529 VariantData::Struct { .. } => {
1530 let field_pats = pieces_iter
1531 .map(|(sp, ident, pat)| {
1532 if ident.is_none() {
1533 cx.dcx().span_bug(
1534 sp,
1535 "a braced struct with unnamed fields in `derive`",
1536 );
1537 }
1538 ast::PatField {
1539 ident: ident.unwrap(),
1540 is_shorthand: false,
1541 attrs: ast::AttrVec::new(),
1542 id: ast::DUMMY_NODE_ID,
1543 span: pat.span.with_ctxt(self.span.ctxt()),
1544 pat: Box::new(pat),
1545 is_placeholder: false,
1546 }
1547 })
1548 .collect();
1549 cx.pat_struct(self.span, struct_path, field_pats)
1550 }
1551 VariantData::Tuple(..) => {
1552 let subpats = pieces_iter.map(|(_, _, subpat)| subpat).collect();
1553 cx.pat_tuple_struct(self.span, struct_path, subpats)
1554 }
1555 VariantData::Unit(..) => cx.pat_path(self.span, struct_path),
1556 }
1557 })
1558 .collect()
1559 }
1560
1561 fn create_fields<F>(&self, struct_def: &'a VariantData, mk_exprs: F) -> Vec<FieldInfo>
1562 where
1563 F: Fn(usize, &ast::FieldDef, Span) -> Vec<Box<ast::Expr>>,
1564 {
1565 struct_def
1566 .fields()
1567 .iter()
1568 .enumerate()
1569 .map(|(i, struct_field)| {
1570 let sp = struct_field.span.with_ctxt(self.span.ctxt());
1573 let mut exprs: Vec<_> = mk_exprs(i, struct_field, sp);
1574 let self_expr = exprs.remove(0);
1575 let other_selflike_exprs = exprs;
1576 FieldInfo {
1577 span: sp.with_ctxt(self.span.ctxt()),
1578 name: struct_field.ident,
1579 self_expr,
1580 other_selflike_exprs,
1581 maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(),
1582 }
1583 })
1584 .collect()
1585 }
1586
1587 fn mk_pattern_ident(&self, prefix: &str, i: usize) -> Ident {
1588 Ident::from_str_and_span(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}_{1}", prefix, i))
})format!("{prefix}_{i}"), self.span)
1589 }
1590
1591 fn create_struct_pattern_fields(
1592 &self,
1593 cx: &ExtCtxt<'_>,
1594 struct_def: &'a VariantData,
1595 prefixes: &[String],
1596 ) -> Vec<FieldInfo> {
1597 self.create_fields(struct_def, |i, _struct_field, sp| {
1598 prefixes
1599 .iter()
1600 .map(|prefix| {
1601 let ident = self.mk_pattern_ident(prefix, i);
1602 cx.expr_path(cx.path_ident(sp, ident))
1603 })
1604 .collect()
1605 })
1606 }
1607
1608 fn create_struct_field_access_fields(
1609 &self,
1610 cx: &ExtCtxt<'_>,
1611 selflike_args: &[Box<Expr>],
1612 struct_def: &'a VariantData,
1613 is_packed: bool,
1614 ) -> Vec<FieldInfo> {
1615 self.create_fields(struct_def, |i, struct_field, sp| {
1616 selflike_args
1617 .iter()
1618 .map(|selflike_arg| {
1619 let mut field_expr = cx.expr(
1624 sp,
1625 ast::ExprKind::Field(
1626 selflike_arg.clone(),
1627 struct_field.ident.unwrap_or_else(|| {
1628 Ident::from_str_and_span(&i.to_string(), struct_field.span)
1629 }),
1630 ),
1631 );
1632 if is_packed {
1633 field_expr = cx.expr_block(
1636 cx.block(struct_field.span, {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.stmt_expr(field_expr));
vec
}thin_vec![cx.stmt_expr(field_expr)]),
1637 );
1638 }
1639 cx.expr_addr_of(sp, field_expr)
1640 })
1641 .collect()
1642 })
1643 }
1644}
1645
1646pub(crate) enum CsFold<'a> {
1650 Single(&'a FieldInfo),
1653
1654 Combine(Span, Box<Expr>, Box<Expr>),
1657
1658 Fieldless,
1660}
1661
1662pub(crate) fn cs_fold<F>(
1665 use_foldl: bool,
1666 cx: &ExtCtxt<'_>,
1667 trait_span: Span,
1668 substructure: &Substructure<'_>,
1669 mut f: F,
1670) -> Box<Expr>
1671where
1672 F: FnMut(&ExtCtxt<'_>, CsFold<'_>) -> Box<Expr>,
1673{
1674 match substructure.fields {
1675 EnumMatching(.., all_fields) | Struct(_, all_fields) => {
1676 if all_fields.is_empty() {
1677 return f(cx, CsFold::Fieldless);
1678 }
1679
1680 let (base_field, rest) = if use_foldl {
1681 all_fields.split_first().unwrap()
1682 } else {
1683 all_fields.split_last().unwrap()
1684 };
1685
1686 let base_expr = f(cx, CsFold::Single(base_field));
1687
1688 let op = |old, field: &FieldInfo| {
1689 let new = f(cx, CsFold::Single(field));
1690 f(cx, CsFold::Combine(field.span, old, new))
1691 };
1692
1693 if use_foldl {
1694 rest.iter().fold(base_expr, op)
1695 } else {
1696 rest.iter().rfold(base_expr, op)
1697 }
1698 }
1699 EnumDiscr(discr_field, match_expr) => {
1700 let discr_check_expr = f(cx, CsFold::Single(discr_field));
1701 if let Some(match_expr) = match_expr {
1702 if use_foldl {
1703 f(cx, CsFold::Combine(trait_span, discr_check_expr, match_expr.clone()))
1704 } else {
1705 f(cx, CsFold::Combine(trait_span, match_expr.clone(), discr_check_expr))
1706 }
1707 } else {
1708 discr_check_expr
1709 }
1710 }
1711 StaticEnum(..) | StaticStruct(..) => {
1712 cx.dcx().span_bug(trait_span, "static function in `derive`")
1713 }
1714 AllFieldlessEnum(..) => cx.dcx().span_bug(trait_span, "fieldless enum in `derive`"),
1715 }
1716}