Commit 77b4beba authored by André Carvalho's avatar André Carvalho Committed by Ian Lance Taylor

reflect: handle types with unexported methods before exported ones

The method Method expects index to be an index of exported fields,
but, before this change, the index used by MethodByName could
take into account unexported fields if those happened sort
before the exported one.

Fixes #21177

Change-Id: I90bb64a47b23e2e43fdd2b8a1e0a2c9a8a63ded2
Reviewed-on: https://go-review.googlesource.com/51810Reviewed-by: default avatarIan Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent e0ab505a
...@@ -5521,6 +5521,25 @@ func TestKeepFuncLive(t *testing.T) { ...@@ -5521,6 +5521,25 @@ func TestKeepFuncLive(t *testing.T) {
MakeFunc(typ, f).Call([]Value{ValueOf(10)}) MakeFunc(typ, f).Call([]Value{ValueOf(10)})
} }
type UnExportedFirst int
func (i UnExportedFirst) ΦExported() {}
func (i UnExportedFirst) unexported() {}
// Issue 21177
func TestMethodByNameUnExportedFirst(t *testing.T) {
defer func() {
if recover() != nil {
t.Errorf("should not panic")
}
}()
typ := TypeOf(UnExportedFirst(0))
m, _ := typ.MethodByName("ΦExported")
if m.Name != "ΦExported" {
t.Errorf("got %s, expected ΦExported", m.Name)
}
}
// Issue 18635 (method version). // Issue 18635 (method version).
type KeepMethodLive struct{} type KeepMethodLive struct{}
......
...@@ -871,11 +871,15 @@ func (t *rtype) MethodByName(name string) (m Method, ok bool) { ...@@ -871,11 +871,15 @@ func (t *rtype) MethodByName(name string) (m Method, ok bool) {
return Method{}, false return Method{}, false
} }
utmethods := ut.methods() utmethods := ut.methods()
var eidx int
for i := 0; i < int(ut.mcount); i++ { for i := 0; i < int(ut.mcount); i++ {
p := utmethods[i] p := utmethods[i]
pname := t.nameOff(p.name) pname := t.nameOff(p.name)
if pname.isExported() && pname.name() == name { if pname.isExported() {
return t.Method(i), true if pname.name() == name {
return t.Method(eidx), true
}
eidx++
} }
} }
return Method{}, false return Method{}, false
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment