field tags are considered part of the anonymous struct definition

so they must be included in the generated source code.
This commit is contained in:
Nicolas S. Dade
2017-01-07 17:20:05 -08:00
parent 14bd82d332
commit 012765f25f
3 changed files with 27 additions and 8 deletions
+16 -1
View File
@@ -264,7 +264,12 @@ func (g *Generator) getType(t reflect.Type) string {
lines := make([]string, 0, nf)
for i := 0; i < nf; i++ {
f := t.Field(i)
lines = append(lines, f.Name+" "+g.getType(f.Type))
line := f.Name + " " + g.getType(f.Type)
t := f.Tag
if t != "" {
line += " " + escapeTag(t)
}
lines = append(lines, line)
}
return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "")
}
@@ -275,6 +280,16 @@ func (g *Generator) getType(t reflect.Type) string {
return g.pkgAlias(t.PkgPath()) + "." + t.Name()
}
// escape a struct field tag string back to source code
func escapeTag(tag reflect.StructTag) string {
t := string(tag)
if strings.ContainsRune(t, '`') {
// there are ` in the string; we can't use ` to enclose the string
return strconv.Quote(t)
}
return "`" + t + "`"
}
// uniqueVarName returns a file-unique name that can be used for generated variables.
func (g *Generator) uniqueVarName() string {
g.varCounter++
+1
View File
@@ -36,6 +36,7 @@ var testCases = []struct {
{&deepNestValue, deepNestString},
{&IntsValue, IntsString},
{&mapStringStringValue, mapStringStringString},
{&namedTypeValue, namedTypeValueString},
}
func TestMarshal(t *testing.T) {
+10 -7
View File
@@ -5,15 +5,18 @@ type NamedType struct {
Inner struct {
// easyjson is mistakenly naming the type of this field 'tests.MyString' in the generated output
// something about a named type inside an anonmymous type is triggering this bug
Field MyString
Field2 int
Field MyString `tag:"value"`
Field2 int "tag:\"value with ` in it\""
}
}
type MyString string
var namedTypeValue = NamedType{Inner: struct {
Field MyString
Field2 int
}{Field: "test"}}
var namedTypeValueString = `{"Inner":{"Field":"test"}}`
var namedTypeValue NamedType
func init() {
namedTypeValue.Inner.Field = "test"
namedTypeValue.Inner.Field2 = 123
}
var namedTypeValueString = `{"Inner":{"Field":"test","Field2":123}}`