Skip to content

Commit

Permalink
fix #39: recognize and process struct field tags
Browse files Browse the repository at this point in the history
  • Loading branch information
cosmos72 committed Oct 26, 2018
1 parent a2d2a3c commit 9c590cf
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions fast/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import (
"go/token"
r "reflect"

"github.com/cosmos72/gomacro/base/strings"

. "github.com/cosmos72/gomacro/base"
"github.com/cosmos72/gomacro/base/reflect"
"github.com/cosmos72/gomacro/base/untyped"
Expand Down Expand Up @@ -255,9 +257,10 @@ func (c *Comp) compileType2(node ast.Expr, allowEllipsis bool) (t xr.Type, ellip
case *ast.StructType:
// c.Debugf("evalType() struct declaration: %v <%v>", node, r.TypeOf(node))
types, names := c.TypeFields(node.Fields)
// c.Debugf("evalType() struct names and types: %v %v", types, names)
tags := c.fieldsTags(node.Fields)
// c.Debugf("evalType() struct names = %v types = %v tags = %v", names, types, tags)
pkg := universe.LoadPackage(c.FileComp().Path)
fields := c.makeStructFields(pkg, names, types)
fields := c.makeStructFields(pkg, names, types, tags)
// c.Debugf("compileType2() declaring struct type. fields=%#v", fields)
t = universe.StructOf(fields)
case nil:
Expand Down Expand Up @@ -378,6 +381,24 @@ func (c *Comp) typeFieldsOrParams(list []*ast.Field, allowEllipsis bool) (types
return types, names, ellipsis
}

func (c *Comp) fieldsTags(fields *ast.FieldList) []string {
var tags []string
if fields != nil {
list := fields.List
for _, field := range list {
if lit := field.Tag; lit != nil && lit.Kind == token.STRING {
tag := strings.MaybeUnescapeString(lit.Value)
if len(tag) != 0 {
for range field.Names {
tags = append(tags, tag)
}
}
}
}
}
return tags
}

func (c *Comp) TryResolveType(name string) xr.Type {
var t xr.Type
for ; c != nil; c = c.Outer {
Expand All @@ -396,7 +417,7 @@ func (c *Comp) ResolveType(name string) xr.Type {
return t
}

func (c *Comp) makeStructFields(pkg *xr.Package, names []string, types []xr.Type) []xr.StructField {
func (c *Comp) makeStructFields(pkg *xr.Package, names []string, types []xr.Type, tags []string) []xr.StructField {
// pkgIdentifier := sanitizeIdentifier(pkgPath)
fields := make([]xr.StructField, len(names))
for i, name := range names {
Expand All @@ -408,6 +429,9 @@ func (c *Comp) makeStructFields(pkg *xr.Package, names []string, types []xr.Type
Tag: "",
Anonymous: len(name) == 0,
}
if i < len(tags) {
fields[i].Tag = r.StructTag(tags[i])
}
}
return fields
}
Expand Down

0 comments on commit 9c590cf

Please sign in to comment.