Commit 11820899 authored by Rob Pike's avatar Rob Pike

text/template: improve the error reporting for unexported fields.

Changes suggested by rsc after last CL.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/6117044
parent cc5cbee1
...@@ -12,8 +12,6 @@ import ( ...@@ -12,8 +12,6 @@ import (
"sort" "sort"
"strings" "strings"
"text/template/parse" "text/template/parse"
"unicode"
"unicode/utf8"
) )
// state represents the state of an execution. It's not part of the // state represents the state of an execution. It's not part of the
...@@ -426,17 +424,16 @@ func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node ...@@ -426,17 +424,16 @@ func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node
tField, ok := receiver.Type().FieldByName(fieldName) tField, ok := receiver.Type().FieldByName(fieldName)
if ok { if ok {
field := receiver.FieldByIndex(tField.Index) field := receiver.FieldByIndex(tField.Index)
if tField.PkgPath == "" { // field is exported if tField.PkgPath != "" { // field is unexported
// If it's a function, we must call it. s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
if hasArgs {
s.errorf("%s has arguments but cannot be invoked as function", fieldName)
}
return field
} }
// If it's a function, we must call it.
if hasArgs {
s.errorf("%s has arguments but cannot be invoked as function", fieldName)
}
return field
} }
if !isExported(fieldName) { s.errorf("%s is not a field of struct type %s", fieldName, typ)
s.errorf("%s is not an exported field of struct type %s", fieldName, typ)
}
case reflect.Map: case reflect.Map:
// If it's a map, attempt to use the field name as a key. // If it's a map, attempt to use the field name as a key.
nameVal := reflect.ValueOf(fieldName) nameVal := reflect.ValueOf(fieldName)
...@@ -451,12 +448,6 @@ func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node ...@@ -451,12 +448,6 @@ func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node
panic("not reached") panic("not reached")
} }
// isExported reports whether the field name (which starts with a period) can be accessed.
func isExported(fieldName string) bool {
r, _ := utf8.DecodeRuneInString(fieldName[1:]) // drop the period
return unicode.IsUpper(r)
}
var ( var (
errorType = reflect.TypeOf((*error)(nil)).Elem() errorType = reflect.TypeOf((*error)(nil)).Elem()
fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
......
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