generateHelper generates the code that transform instances of source into target. Both source and targe must be user types or generateHelper panics. generateHelper returns nil if a helper has already been generated for the pair source, target.
(source, target *expr.AttributeExpr, req bool, ta *TransformAttrs, seen map[string]*TransformFunctionData)
| 642 | // generateHelper returns nil if a helper has already been generated for the |
| 643 | // pair source, target. |
| 644 | func generateHelper(source, target *expr.AttributeExpr, req bool, ta *TransformAttrs, seen map[string]*TransformFunctionData) (*TransformFunctionData, error) { |
| 645 | name := transformHelperName(source, target, ta) |
| 646 | if _, ok := seen[name]; ok { |
| 647 | return nil, nil |
| 648 | } |
| 649 | |
| 650 | // Reset need for type assertion for union types because we are |
| 651 | // generating the code to transform the concrete type. |
| 652 | ta.TargetCtx.IsInterface = false |
| 653 | // When transforming into a user type defined in an external package, assume |
| 654 | // nested anonymous types (e.g., union sum types) belong to the same target |
| 655 | // package unless they explicitly specify a different location. |
| 656 | prevDefaultPkg := ta.TargetCtx.DefaultPkg |
| 657 | prevSamePackageConversion := ta.TargetCtx.SamePackageConversion |
| 658 | if pkg := ta.TargetCtx.Pkg(target); pkg != "" && pkg != prevDefaultPkg { |
| 659 | ta.TargetCtx.DefaultPkg = pkg |
| 660 | ta.TargetCtx.SamePackageConversion = false |
| 661 | defer func() { |
| 662 | ta.TargetCtx.DefaultPkg = prevDefaultPkg |
| 663 | ta.TargetCtx.SamePackageConversion = prevSamePackageConversion |
| 664 | }() |
| 665 | } |
| 666 | |
| 667 | code, err := transformAttribute(source, target, "v", "res", true, ta) |
| 668 | if err != nil { |
| 669 | return nil, err |
| 670 | } |
| 671 | if !req && !expr.IsPrimitive(source.Type) { |
| 672 | code = "if v == nil {\n\treturn nil\n}\n" + code |
| 673 | } |
| 674 | tfd := &TransformFunctionData{ |
| 675 | Name: name, |
| 676 | ParamTypeRef: ta.SourceCtx.Scope.Ref(source, ta.SourceCtx.Pkg(source)), |
| 677 | ResultTypeRef: ta.TargetCtx.Scope.Ref(target, ta.TargetCtx.Pkg(target)), |
| 678 | Code: code, |
| 679 | } |
| 680 | seen[name] = tfd |
| 681 | return tfd, nil |
| 682 | } |
| 683 | |
| 684 | // walkMatches iterates through the attributes of source and looks for |
| 685 | // attributes with identical names in target. walkMatches calls the walker |
no test coverage detected