Ejemplo n.º 1
0
func parseExpr(e ast.Expr, ul map[string]types.Type) *models.Expression {
	switch v := e.(type) {
	case *ast.StarExpr:
		val := types.ExprString(v.X)
		return &models.Expression{
			Value:      val,
			IsStar:     true,
			Underlying: underlying(val, ul),
		}
	case *ast.Ellipsis:
		exp := parseExpr(v.Elt, ul)
		return &models.Expression{
			Value:      exp.Value,
			IsStar:     exp.IsStar,
			IsVariadic: true,
			Underlying: underlying(exp.Value, ul),
		}
	default:
		val := types.ExprString(e)
		return &models.Expression{
			Value:      val,
			Underlying: underlying(val, ul),
			IsWriter:   val == "io.Writer",
		}
	}
}
Ejemplo n.º 2
0
func (g *Generator) generate(name string, structType *ast.StructType) {
	g.Printf("type %sJSON struct {", name)
	g.Printf("\n")
	fieldNames := make([]string, len(structType.Fields.List))
	for i, field := range structType.Fields.List {
		fieldName := field.Names[0].Name
		fieldNames[i] = fieldName

		fieldType := types.ExprString(field.Type)

		tagValue := ""
		if field.Tag != nil {
			tagValue = field.Tag.Value
		}
		tagValue = addJsonTag(fieldName, tagValue)

		g.Printf("%s %s %s", fieldName, fieldType, tagValue)
		g.Printf("\n")
	}
	g.Printf("}\n")

	g.Printf("\n")

	g.Printf("func (m %s) MarshalJSON() ([]byte, error) {\n", name)
	g.Printf("	j := New%sJSON(&m)\n", name)
	g.Printf("	return json.Marshal(j)\n")
	g.Printf("}\n")

	g.Printf("\n")

	g.Printf("func New%sJSON(m *%s) *%sJSON {\n", name, name, name)
	g.Printf("	return &%sJSON{\n", name)
	for _, fieldName := range fieldNames {
		g.Printf("		%s:  m.%s,\n", fieldName, fieldName)
	}
	g.Printf("	}\n")
	g.Printf("}\n")

	g.Printf("\n")
}
Ejemplo n.º 3
0
// Foo200 compares an expression to a type.
func Foo200(x ast.Expr, t types.Type) bool { return types.ExprString(x) == Bar200(t) }