Ejemplo n.º 1
0
Archivo: compile.go Proyecto: gemrs/gem
func (c *context) generateEncodeFuncs(strct *ast.Struct) (string, error) {
	encodeFields, decodeFields := make([]string, 0), make([]string, 0)

	for _, field := range strct.Scope.S {
		switch field := field.(type) {
		case *ast.Field:
			encode, err := c.generateFieldFunc("Encode", field)
			if err != nil {
				return "", err
			}

			decode, err := c.generateFieldFunc("Decode", field)
			if err != nil {
				return "", err
			}

			encodeFields = append(encodeFields, encode)
			decodeFields = append(decodeFields, decode)
		default:
			panic("non-field in struct scope")
		}
	}

	tmplData := struct {
		Type         string
		EncodeFields []string
		DecodeFields []string
	}{
		Type:         strct.Identifier(),
		EncodeFields: encodeFields,
		DecodeFields: decodeFields,
	}

	return bufferTemplate(encodeFuncsTmpl, tmplData)
}
Ejemplo n.º 2
0
Archivo: compile.go Proyecto: gemrs/gem
func (c *context) doGenerateType(strct *ast.Struct) error {
	if _, ok := c.types[strct.Identifier()]; ok {
		fmt.Printf("Already generated type for structure %v\n", strct.Identifier())
		return nil
	}

	fmt.Printf("Generating type for %v\n", strct.Identifier())

	fields := make([]string, 0)
	for _, f := range strct.Scope.S {
		switch f := f.(type) {
		case *ast.Field:
			fieldStr := fmt.Sprintf("%v %v", f.Name, c.goType(f.Type))
			fields = append(fields, fieldStr)
		default:
			panic("declaration in structure is not a valid field")
		}
	}

	funcs, err := c.generateEncodeFuncs(strct)
	if err != nil {
		return err
	}

	tmplData := struct {
		Name        string
		Fields      []string
		EncodeFuncs string
	}{
		Name:        strct.Identifier(),
		Fields:      fields,
		EncodeFuncs: funcs,
	}

	typeStr, err := bufferTemplate(typeDefTmpl, tmplData)
	if err != nil {
		return err
	}
	c.types[strct.Identifier()] = typeStr
	return nil
}