text/template: fix method lookup on addressable nil pointer

Fixes #18816.

Change-Id: I4f8f1cac2680dbde492c56d3a5a038577605e7c1
Reviewed-on: https://go-review.googlesource.com/36542
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Russ Cox 2017-01-27 14:14:05 -05:00
parent e4371fb179
commit 06637fb314
2 changed files with 4 additions and 1 deletions

View File

@ -551,7 +551,7 @@ func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node,
// Unless it's an interface, need to get to a value of type *T to guarantee
// we see all methods of T and *T.
ptr := receiver
if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
ptr = ptr.Addr()
}
if method := ptr.MethodByName(fieldName); method.IsValid() {

View File

@ -147,6 +147,8 @@ var tVal = &T{
Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X
}
var tSliceOfNil = []*T{nil}
// A non-empty interface.
type I interface {
Method0() string
@ -337,6 +339,7 @@ var execTests = []execTest{
"true", tVal, true},
{".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true},
{".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true},
{"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true},
// Function call builtin.
{".BinaryFunc", "{{call .BinaryFunc `1` `2`}}", "[1=2]", tVal, true},