mirror of
https://github.com/netbirdio/easyjson.git
synced 2026-05-22 18:44:42 -07:00
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)
This commit is contained in:
+14
-2
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -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"}}`
|
||||
|
||||
Reference in New Issue
Block a user