MCPcopy Create free account
hub / github.com/goadesign/goa / InitStructFields

Function InitStructFields

codegen/funcs.go:285–342  ·  view source on GitHub ↗

InitStructFields produces Go code to initialize a struct and its fields from the given init arguments.

(args []*InitArgData, targetVar, sourcePkg, targetPkg string)

Source from the content-addressed store, hash-verified

283// InitStructFields produces Go code to initialize a struct and its fields from
284// the given init arguments.
285func InitStructFields(args []*InitArgData, targetVar, sourcePkg, targetPkg string) (string, []*TransformFunctionData, error) {
286 scope := NewNameScope()
287 scope.Unique(targetVar)
288
289 var (
290 code string
291 helpers []*TransformFunctionData
292 )
293 for _, arg := range args {
294 switch {
295 case arg.FieldName == "" && arg.FieldType == nil:
296 // do nothing
297 case expr.Equal(unalias(arg.Type), arg.FieldType):
298 // arg type and struct field type are the same. No need to call transform
299 // to initialize the field
300 deref := ""
301 if !arg.Pointer && arg.FieldPointer && expr.IsPrimitive(arg.FieldType) {
302 deref = "&"
303 }
304 code += fmt.Sprintf("%s.%s = %s%s\n", targetVar, arg.FieldName, deref, arg.Name)
305 case expr.IsPrimitive(arg.FieldType):
306 // aliased primitive type
307 pkg := targetPkg
308 if loc := UserTypeLocation(arg.FieldType); loc != nil {
309 pkg = loc.PackageName()
310 }
311 t := scope.GoFullTypeRef(&expr.AttributeExpr{Type: arg.FieldType}, pkg)
312 cast := fmt.Sprintf("%s(%s)", t, arg.Name)
313 if arg.Pointer {
314 code += "if " + arg.Name + " != nil {\n"
315 cast = fmt.Sprintf("%s(*%s)", t, arg.Name)
316 }
317 switch {
318 case arg.FieldPointer:
319 code += fmt.Sprintf("tmp%s := %s\n%s.%s = &tmp%s\n", arg.Name, cast, targetVar, arg.FieldName, arg.Name)
320 case arg.FieldName != "":
321 code += fmt.Sprintf("%s.%s = %s\n", targetVar, arg.FieldName, cast)
322 default:
323 code += fmt.Sprintf("%s := %s\n", targetVar, cast)
324 }
325 if arg.Pointer {
326 code += "}\n"
327 }
328 default:
329 srcctx := NewAttributeContext(arg.Pointer, false, true, sourcePkg, scope)
330 tgtctx := NewAttributeContext(arg.FieldPointer, false, true, targetPkg, scope)
331 c, h, err := GoTransform(
332 &expr.AttributeExpr{Type: arg.Type}, &expr.AttributeExpr{Type: arg.FieldType},
333 arg.Name, fmt.Sprintf("%s.%s", targetVar, arg.FieldName), srcctx, tgtctx, "", false)
334 if err != nil {
335 return "", helpers, err
336 }
337 code += c + "\n"
338 helpers = AppendHelpers(helpers, h)
339 }
340 }
341 return code, helpers, nil
342}

Callers 2

fieldCodeFunction · 0.92
fieldCodeFunction · 0.92

Calls 11

UniqueMethod · 0.95
GoFullTypeRefMethod · 0.95
EqualFunction · 0.92
IsPrimitiveFunction · 0.92
NewNameScopeFunction · 0.85
UserTypeLocationFunction · 0.85
NewAttributeContextFunction · 0.85
GoTransformFunction · 0.85
AppendHelpersFunction · 0.85
PackageNameMethod · 0.80
unaliasFunction · 0.70

Tested by

no test coverage detected