From 14bd82d332192df0ae0af5a3d21cec9aed176b4a Mon Sep 17 00:00:00 2001 From: "Nicolas S. Dade" Date: Thu, 5 Jan 2017 20:13:35 -0800 Subject: [PATCH] properly handle named types inside anonymous structs without this the tests/named_type.go test fails because reflect.Type.String() of the anonmymous struct returns package-qualified type names for the fields, including those types which are within the current package. (it could also fail when our alias for the some other package collides with Type.String() picked) --- gen/generator.go | 16 ++++++++++++++-- tests/named_type.go | 8 ++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/gen/generator.go b/gen/generator.go index 32e806e..323fc64 100644 --- a/gen/generator.go +++ b/gen/generator.go @@ -60,7 +60,7 @@ func NewGenerator(filename string) *Generator { imports: map[string]string{ pkgWriter: "jwriter", pkgLexer: "jlexer", - pkgEasyjson: "easyjson", + pkgEasyjson: "easyjson", "encoding/json": "json", }, fieldNamer: DefaultFieldNamer{}, @@ -255,11 +255,23 @@ func (g *Generator) getType(t reflect.Type) string { } if t.Name() == "" || t.PkgPath() == "" { + if t.Kind() == reflect.Struct { + // the fields of an anonymous struct can have named types, + // and t.String() will not be sufficient because it does not + // remove the package name when it matches g.pkgPath. + // so we convert by hand + nf := t.NumField() + lines := make([]string, 0, nf) + for i := 0; i < nf; i++ { + f := t.Field(i) + lines = append(lines, f.Name+" "+g.getType(f.Type)) + } + return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") + } return t.String() } else if t.PkgPath() == g.pkgPath { return t.Name() } - // TODO: unnamed structs. return g.pkgAlias(t.PkgPath()) + "." + t.Name() } diff --git a/tests/named_type.go b/tests/named_type.go index a157553..9948d3b 100644 --- a/tests/named_type.go +++ b/tests/named_type.go @@ -5,11 +5,15 @@ 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 + Field MyString + Field2 int } } type MyString string -var namedTypeValue = NamedType{Inner: struct{ Field MyString }{Field: "test"}} +var namedTypeValue = NamedType{Inner: struct { + Field MyString + Field2 int +}{Field: "test"}} var namedTypeValueString = `{"Inner":{"Field":"test"}}`