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