diff --git a/gen/generator.go b/gen/generator.go index 323fc64..1b9284d 100644 --- a/gen/generator.go +++ b/gen/generator.go @@ -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++ diff --git a/tests/basic_test.go b/tests/basic_test.go index 25b1bfc..c072f28 100644 --- a/tests/basic_test.go +++ b/tests/basic_test.go @@ -36,6 +36,7 @@ var testCases = []struct { {&deepNestValue, deepNestString}, {&IntsValue, IntsString}, {&mapStringStringValue, mapStringStringString}, + {&namedTypeValue, namedTypeValueString}, } func TestMarshal(t *testing.T) { diff --git a/tests/named_type.go b/tests/named_type.go index 9948d3b..0ff8dfe 100644 --- a/tests/named_type.go +++ b/tests/named_type.go @@ -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}}`