Example #1
0
// t is a tuple for representing parameters or return values of  function.
func (g *generator) parse(name string, t *types.Tuple) *args {
	ps := toList(t)
	var fields []*types.Var
	var tags []string
	imports := map[types.Object]*ast.SelectorExpr{}
	un := uniqueNames{}
	m := &args{}
	for _, p := range ps {
		n := p.Name()
		if n == "" {
			n = p.Type().String()
			if !validIdentifier(n) {
				n = "p"
			}
		}
		n = un.get(capitalize(n))
		t := types.NewField(0, g.pkg, n, p.Type(), false)
		// Filter out context and error.
		switch p.Type().String() {
		case "golang.org/x/net/context.Context":
			ctxName := un.get("ctx")
			m.Args = append(m.Args, func(string) string { return ctxName })
			m.CtxName = ctxName
			m.HasCtx = true
			m.Args2 = append(m.Args2, struct{ Name, Type string }{ctxName, types.TypeString(t.Type(), relativeTo(g.pkg))})
			continue
		case "error":
			errName := un.get("err")
			m.Args = append(m.Args, func(string) string { return errName })
			m.ErrName = errName
			m.HasErr = true
			m.Args2 = append(m.Args2, struct{ Name, Type string }{errName, types.TypeString(t.Type(), relativeTo(g.pkg))})
			continue
		}
		m.Args2 = append(m.Args2, struct{ Name, Type string }{uncapitalize(n), types.TypeString(t.Type(), relativeTo(g.pkg))})
		updateDeps(g.rev[p.Type()], g.info, imports)
		// Make sure all the names are unique.
		m.Args = append(m.Args, func(s string) string { return fmt.Sprintf("%s.%s", s, n) })
		fields = append(fields, t)
		tags = append(tags, fmt.Sprintf(`json:"%s"`, toSnake(n)))
	}
	if !m.HasCtx {
		m.CtxName = un.get("ctx")
	}
	if !m.HasErr {
		m.ErrName = un.get("err")
	}
	imps := cleanImports(imports)
	m.StructDef = structDef{
		Pkg:     g.pkg.Name(),
		Imports: imps,
		Name:    name,
	}
	for i, v := range fields {
		m.StructDef.Fields = append(m.StructDef.Fields, struct {
			Name string
			Tag  string
			Type string
		}{
			Name: v.Name(),
			Type: types.TypeString(v.Type(), relativeTo(g.pkg)),
			Tag:  tags[i],
		})
	}
	return m
}