...

Source file src/text/template/exec.go

Documentation: text/template

		 1  // Copyright 2011 The Go Authors. All rights reserved.
		 2  // Use of this source code is governed by a BSD-style
		 3  // license that can be found in the LICENSE file.
		 4  
		 5  package template
		 6  
		 7  import (
		 8  	"fmt"
		 9  	"internal/fmtsort"
		10  	"io"
		11  	"reflect"
		12  	"runtime"
		13  	"strings"
		14  	"text/template/parse"
		15  )
		16  
		17  // maxExecDepth specifies the maximum stack depth of templates within
		18  // templates. This limit is only practically reached by accidentally
		19  // recursive template invocations. This limit allows us to return
		20  // an error instead of triggering a stack overflow.
		21  var maxExecDepth = initMaxExecDepth()
		22  
		23  func initMaxExecDepth() int {
		24  	if runtime.GOARCH == "wasm" {
		25  		return 1000
		26  	}
		27  	return 100000
		28  }
		29  
		30  // state represents the state of an execution. It's not part of the
		31  // template so that multiple executions of the same template
		32  // can execute in parallel.
		33  type state struct {
		34  	tmpl	*Template
		35  	wr		io.Writer
		36  	node	parse.Node // current node, for errors
		37  	vars	[]variable // push-down stack of variable values.
		38  	depth int				// the height of the stack of executing templates.
		39  }
		40  
		41  // variable holds the dynamic value of a variable such as $, $x etc.
		42  type variable struct {
		43  	name	string
		44  	value reflect.Value
		45  }
		46  
		47  // push pushes a new variable on the stack.
		48  func (s *state) push(name string, value reflect.Value) {
		49  	s.vars = append(s.vars, variable{name, value})
		50  }
		51  
		52  // mark returns the length of the variable stack.
		53  func (s *state) mark() int {
		54  	return len(s.vars)
		55  }
		56  
		57  // pop pops the variable stack up to the mark.
		58  func (s *state) pop(mark int) {
		59  	s.vars = s.vars[0:mark]
		60  }
		61  
		62  // setVar overwrites the last declared variable with the given name.
		63  // Used by variable assignments.
		64  func (s *state) setVar(name string, value reflect.Value) {
		65  	for i := s.mark() - 1; i >= 0; i-- {
		66  		if s.vars[i].name == name {
		67  			s.vars[i].value = value
		68  			return
		69  		}
		70  	}
		71  	s.errorf("undefined variable: %s", name)
		72  }
		73  
		74  // setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
		75  func (s *state) setTopVar(n int, value reflect.Value) {
		76  	s.vars[len(s.vars)-n].value = value
		77  }
		78  
		79  // varValue returns the value of the named variable.
		80  func (s *state) varValue(name string) reflect.Value {
		81  	for i := s.mark() - 1; i >= 0; i-- {
		82  		if s.vars[i].name == name {
		83  			return s.vars[i].value
		84  		}
		85  	}
		86  	s.errorf("undefined variable: %s", name)
		87  	return zero
		88  }
		89  
		90  var zero reflect.Value
		91  
		92  type missingValType struct{}
		93  
		94  var missingVal = reflect.ValueOf(missingValType{})
		95  
		96  // at marks the state to be on node n, for error reporting.
		97  func (s *state) at(node parse.Node) {
		98  	s.node = node
		99  }
	 100  
	 101  // doublePercent returns the string with %'s replaced by %%, if necessary,
	 102  // so it can be used safely inside a Printf format string.
	 103  func doublePercent(str string) string {
	 104  	return strings.ReplaceAll(str, "%", "%%")
	 105  }
	 106  
	 107  // TODO: It would be nice if ExecError was more broken down, but
	 108  // the way ErrorContext embeds the template name makes the
	 109  // processing too clumsy.
	 110  
	 111  // ExecError is the custom error type returned when Execute has an
	 112  // error evaluating its template. (If a write error occurs, the actual
	 113  // error is returned; it will not be of type ExecError.)
	 114  type ExecError struct {
	 115  	Name string // Name of template.
	 116  	Err	error	// Pre-formatted error.
	 117  }
	 118  
	 119  func (e ExecError) Error() string {
	 120  	return e.Err.Error()
	 121  }
	 122  
	 123  func (e ExecError) Unwrap() error {
	 124  	return e.Err
	 125  }
	 126  
	 127  // errorf records an ExecError and terminates processing.
	 128  func (s *state) errorf(format string, args ...interface{}) {
	 129  	name := doublePercent(s.tmpl.Name())
	 130  	if s.node == nil {
	 131  		format = fmt.Sprintf("template: %s: %s", name, format)
	 132  	} else {
	 133  		location, context := s.tmpl.ErrorContext(s.node)
	 134  		format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
	 135  	}
	 136  	panic(ExecError{
	 137  		Name: s.tmpl.Name(),
	 138  		Err:	fmt.Errorf(format, args...),
	 139  	})
	 140  }
	 141  
	 142  // writeError is the wrapper type used internally when Execute has an
	 143  // error writing to its output. We strip the wrapper in errRecover.
	 144  // Note that this is not an implementation of error, so it cannot escape
	 145  // from the package as an error value.
	 146  type writeError struct {
	 147  	Err error // Original error.
	 148  }
	 149  
	 150  func (s *state) writeError(err error) {
	 151  	panic(writeError{
	 152  		Err: err,
	 153  	})
	 154  }
	 155  
	 156  // errRecover is the handler that turns panics into returns from the top
	 157  // level of Parse.
	 158  func errRecover(errp *error) {
	 159  	e := recover()
	 160  	if e != nil {
	 161  		switch err := e.(type) {
	 162  		case runtime.Error:
	 163  			panic(e)
	 164  		case writeError:
	 165  			*errp = err.Err // Strip the wrapper.
	 166  		case ExecError:
	 167  			*errp = err // Keep the wrapper.
	 168  		default:
	 169  			panic(e)
	 170  		}
	 171  	}
	 172  }
	 173  
	 174  // ExecuteTemplate applies the template associated with t that has the given name
	 175  // to the specified data object and writes the output to wr.
	 176  // If an error occurs executing the template or writing its output,
	 177  // execution stops, but partial results may already have been written to
	 178  // the output writer.
	 179  // A template may be executed safely in parallel, although if parallel
	 180  // executions share a Writer the output may be interleaved.
	 181  func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
	 182  	tmpl := t.Lookup(name)
	 183  	if tmpl == nil {
	 184  		return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
	 185  	}
	 186  	return tmpl.Execute(wr, data)
	 187  }
	 188  
	 189  // Execute applies a parsed template to the specified data object,
	 190  // and writes the output to wr.
	 191  // If an error occurs executing the template or writing its output,
	 192  // execution stops, but partial results may already have been written to
	 193  // the output writer.
	 194  // A template may be executed safely in parallel, although if parallel
	 195  // executions share a Writer the output may be interleaved.
	 196  //
	 197  // If data is a reflect.Value, the template applies to the concrete
	 198  // value that the reflect.Value holds, as in fmt.Print.
	 199  func (t *Template) Execute(wr io.Writer, data interface{}) error {
	 200  	return t.execute(wr, data)
	 201  }
	 202  
	 203  func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
	 204  	defer errRecover(&err)
	 205  	value, ok := data.(reflect.Value)
	 206  	if !ok {
	 207  		value = reflect.ValueOf(data)
	 208  	}
	 209  	state := &state{
	 210  		tmpl: t,
	 211  		wr:	 wr,
	 212  		vars: []variable{{"$", value}},
	 213  	}
	 214  	if t.Tree == nil || t.Root == nil {
	 215  		state.errorf("%q is an incomplete or empty template", t.Name())
	 216  	}
	 217  	state.walk(value, t.Root)
	 218  	return
	 219  }
	 220  
	 221  // DefinedTemplates returns a string listing the defined templates,
	 222  // prefixed by the string "; defined templates are: ". If there are none,
	 223  // it returns the empty string. For generating an error message here
	 224  // and in html/template.
	 225  func (t *Template) DefinedTemplates() string {
	 226  	if t.common == nil {
	 227  		return ""
	 228  	}
	 229  	var b strings.Builder
	 230  	t.muTmpl.RLock()
	 231  	defer t.muTmpl.RUnlock()
	 232  	for name, tmpl := range t.tmpl {
	 233  		if tmpl.Tree == nil || tmpl.Root == nil {
	 234  			continue
	 235  		}
	 236  		if b.Len() == 0 {
	 237  			b.WriteString("; defined templates are: ")
	 238  		} else {
	 239  			b.WriteString(", ")
	 240  		}
	 241  		fmt.Fprintf(&b, "%q", name)
	 242  	}
	 243  	return b.String()
	 244  }
	 245  
	 246  // Walk functions step through the major pieces of the template structure,
	 247  // generating output as they go.
	 248  func (s *state) walk(dot reflect.Value, node parse.Node) {
	 249  	s.at(node)
	 250  	switch node := node.(type) {
	 251  	case *parse.ActionNode:
	 252  		// Do not pop variables so they persist until next end.
	 253  		// Also, if the action declares variables, don't print the result.
	 254  		val := s.evalPipeline(dot, node.Pipe)
	 255  		if len(node.Pipe.Decl) == 0 {
	 256  			s.printValue(node, val)
	 257  		}
	 258  	case *parse.CommentNode:
	 259  	case *parse.IfNode:
	 260  		s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
	 261  	case *parse.ListNode:
	 262  		for _, node := range node.Nodes {
	 263  			s.walk(dot, node)
	 264  		}
	 265  	case *parse.RangeNode:
	 266  		s.walkRange(dot, node)
	 267  	case *parse.TemplateNode:
	 268  		s.walkTemplate(dot, node)
	 269  	case *parse.TextNode:
	 270  		if _, err := s.wr.Write(node.Text); err != nil {
	 271  			s.writeError(err)
	 272  		}
	 273  	case *parse.WithNode:
	 274  		s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
	 275  	default:
	 276  		s.errorf("unknown node: %s", node)
	 277  	}
	 278  }
	 279  
	 280  // walkIfOrWith walks an 'if' or 'with' node. The two control structures
	 281  // are identical in behavior except that 'with' sets dot.
	 282  func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
	 283  	defer s.pop(s.mark())
	 284  	val := s.evalPipeline(dot, pipe)
	 285  	truth, ok := isTrue(indirectInterface(val))
	 286  	if !ok {
	 287  		s.errorf("if/with can't use %v", val)
	 288  	}
	 289  	if truth {
	 290  		if typ == parse.NodeWith {
	 291  			s.walk(val, list)
	 292  		} else {
	 293  			s.walk(dot, list)
	 294  		}
	 295  	} else if elseList != nil {
	 296  		s.walk(dot, elseList)
	 297  	}
	 298  }
	 299  
	 300  // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
	 301  // and whether the value has a meaningful truth value. This is the definition of
	 302  // truth used by if and other such actions.
	 303  func IsTrue(val interface{}) (truth, ok bool) {
	 304  	return isTrue(reflect.ValueOf(val))
	 305  }
	 306  
	 307  func isTrue(val reflect.Value) (truth, ok bool) {
	 308  	if !val.IsValid() {
	 309  		// Something like var x interface{}, never set. It's a form of nil.
	 310  		return false, true
	 311  	}
	 312  	switch val.Kind() {
	 313  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
	 314  		truth = val.Len() > 0
	 315  	case reflect.Bool:
	 316  		truth = val.Bool()
	 317  	case reflect.Complex64, reflect.Complex128:
	 318  		truth = val.Complex() != 0
	 319  	case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
	 320  		truth = !val.IsNil()
	 321  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
	 322  		truth = val.Int() != 0
	 323  	case reflect.Float32, reflect.Float64:
	 324  		truth = val.Float() != 0
	 325  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
	 326  		truth = val.Uint() != 0
	 327  	case reflect.Struct:
	 328  		truth = true // Struct values are always true.
	 329  	default:
	 330  		return
	 331  	}
	 332  	return truth, true
	 333  }
	 334  
	 335  func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
	 336  	s.at(r)
	 337  	defer s.pop(s.mark())
	 338  	val, _ := indirect(s.evalPipeline(dot, r.Pipe))
	 339  	// mark top of stack before any variables in the body are pushed.
	 340  	mark := s.mark()
	 341  	oneIteration := func(index, elem reflect.Value) {
	 342  		// Set top var (lexically the second if there are two) to the element.
	 343  		if len(r.Pipe.Decl) > 0 {
	 344  			s.setTopVar(1, elem)
	 345  		}
	 346  		// Set next var (lexically the first if there are two) to the index.
	 347  		if len(r.Pipe.Decl) > 1 {
	 348  			s.setTopVar(2, index)
	 349  		}
	 350  		s.walk(elem, r.List)
	 351  		s.pop(mark)
	 352  	}
	 353  	switch val.Kind() {
	 354  	case reflect.Array, reflect.Slice:
	 355  		if val.Len() == 0 {
	 356  			break
	 357  		}
	 358  		for i := 0; i < val.Len(); i++ {
	 359  			oneIteration(reflect.ValueOf(i), val.Index(i))
	 360  		}
	 361  		return
	 362  	case reflect.Map:
	 363  		if val.Len() == 0 {
	 364  			break
	 365  		}
	 366  		om := fmtsort.Sort(val)
	 367  		for i, key := range om.Key {
	 368  			oneIteration(key, om.Value[i])
	 369  		}
	 370  		return
	 371  	case reflect.Chan:
	 372  		if val.IsNil() {
	 373  			break
	 374  		}
	 375  		if val.Type().ChanDir() == reflect.SendDir {
	 376  			s.errorf("range over send-only channel %v", val)
	 377  			break
	 378  		}
	 379  		i := 0
	 380  		for ; ; i++ {
	 381  			elem, ok := val.Recv()
	 382  			if !ok {
	 383  				break
	 384  			}
	 385  			oneIteration(reflect.ValueOf(i), elem)
	 386  		}
	 387  		if i == 0 {
	 388  			break
	 389  		}
	 390  		return
	 391  	case reflect.Invalid:
	 392  		break // An invalid value is likely a nil map, etc. and acts like an empty map.
	 393  	default:
	 394  		s.errorf("range can't iterate over %v", val)
	 395  	}
	 396  	if r.ElseList != nil {
	 397  		s.walk(dot, r.ElseList)
	 398  	}
	 399  }
	 400  
	 401  func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
	 402  	s.at(t)
	 403  	tmpl := s.tmpl.Lookup(t.Name)
	 404  	if tmpl == nil {
	 405  		s.errorf("template %q not defined", t.Name)
	 406  	}
	 407  	if s.depth == maxExecDepth {
	 408  		s.errorf("exceeded maximum template depth (%v)", maxExecDepth)
	 409  	}
	 410  	// Variables declared by the pipeline persist.
	 411  	dot = s.evalPipeline(dot, t.Pipe)
	 412  	newState := *s
	 413  	newState.depth++
	 414  	newState.tmpl = tmpl
	 415  	// No dynamic scoping: template invocations inherit no variables.
	 416  	newState.vars = []variable{{"$", dot}}
	 417  	newState.walk(dot, tmpl.Root)
	 418  }
	 419  
	 420  // Eval functions evaluate pipelines, commands, and their elements and extract
	 421  // values from the data structure by examining fields, calling methods, and so on.
	 422  // The printing of those values happens only through walk functions.
	 423  
	 424  // evalPipeline returns the value acquired by evaluating a pipeline. If the
	 425  // pipeline has a variable declaration, the variable will be pushed on the
	 426  // stack. Callers should therefore pop the stack after they are finished
	 427  // executing commands depending on the pipeline value.
	 428  func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
	 429  	if pipe == nil {
	 430  		return
	 431  	}
	 432  	s.at(pipe)
	 433  	value = missingVal
	 434  	for _, cmd := range pipe.Cmds {
	 435  		value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
	 436  		// If the object has type interface{}, dig down one level to the thing inside.
	 437  		if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
	 438  			value = reflect.ValueOf(value.Interface()) // lovely!
	 439  		}
	 440  	}
	 441  	for _, variable := range pipe.Decl {
	 442  		if pipe.IsAssign {
	 443  			s.setVar(variable.Ident[0], value)
	 444  		} else {
	 445  			s.push(variable.Ident[0], value)
	 446  		}
	 447  	}
	 448  	return value
	 449  }
	 450  
	 451  func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
	 452  	if len(args) > 1 || final != missingVal {
	 453  		s.errorf("can't give argument to non-function %s", args[0])
	 454  	}
	 455  }
	 456  
	 457  func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
	 458  	firstWord := cmd.Args[0]
	 459  	switch n := firstWord.(type) {
	 460  	case *parse.FieldNode:
	 461  		return s.evalFieldNode(dot, n, cmd.Args, final)
	 462  	case *parse.ChainNode:
	 463  		return s.evalChainNode(dot, n, cmd.Args, final)
	 464  	case *parse.IdentifierNode:
	 465  		// Must be a function.
	 466  		return s.evalFunction(dot, n, cmd, cmd.Args, final)
	 467  	case *parse.PipeNode:
	 468  		// Parenthesized pipeline. The arguments are all inside the pipeline; final must be absent.
	 469  		s.notAFunction(cmd.Args, final)
	 470  		return s.evalPipeline(dot, n)
	 471  	case *parse.VariableNode:
	 472  		return s.evalVariableNode(dot, n, cmd.Args, final)
	 473  	}
	 474  	s.at(firstWord)
	 475  	s.notAFunction(cmd.Args, final)
	 476  	switch word := firstWord.(type) {
	 477  	case *parse.BoolNode:
	 478  		return reflect.ValueOf(word.True)
	 479  	case *parse.DotNode:
	 480  		return dot
	 481  	case *parse.NilNode:
	 482  		s.errorf("nil is not a command")
	 483  	case *parse.NumberNode:
	 484  		return s.idealConstant(word)
	 485  	case *parse.StringNode:
	 486  		return reflect.ValueOf(word.Text)
	 487  	}
	 488  	s.errorf("can't evaluate command %q", firstWord)
	 489  	panic("not reached")
	 490  }
	 491  
	 492  // idealConstant is called to return the value of a number in a context where
	 493  // we don't know the type. In that case, the syntax of the number tells us
	 494  // its type, and we use Go rules to resolve. Note there is no such thing as
	 495  // a uint ideal constant in this situation - the value must be of int type.
	 496  func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
	 497  	// These are ideal constants but we don't know the type
	 498  	// and we have no context.	(If it was a method argument,
	 499  	// we'd know what we need.) The syntax guides us to some extent.
	 500  	s.at(constant)
	 501  	switch {
	 502  	case constant.IsComplex:
	 503  		return reflect.ValueOf(constant.Complex128) // incontrovertible.
	 504  
	 505  	case constant.IsFloat &&
	 506  		!isHexInt(constant.Text) && !isRuneInt(constant.Text) &&
	 507  		strings.ContainsAny(constant.Text, ".eEpP"):
	 508  		return reflect.ValueOf(constant.Float64)
	 509  
	 510  	case constant.IsInt:
	 511  		n := int(constant.Int64)
	 512  		if int64(n) != constant.Int64 {
	 513  			s.errorf("%s overflows int", constant.Text)
	 514  		}
	 515  		return reflect.ValueOf(n)
	 516  
	 517  	case constant.IsUint:
	 518  		s.errorf("%s overflows int", constant.Text)
	 519  	}
	 520  	return zero
	 521  }
	 522  
	 523  func isRuneInt(s string) bool {
	 524  	return len(s) > 0 && s[0] == '\''
	 525  }
	 526  
	 527  func isHexInt(s string) bool {
	 528  	return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') && !strings.ContainsAny(s, "pP")
	 529  }
	 530  
	 531  func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
	 532  	s.at(field)
	 533  	return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
	 534  }
	 535  
	 536  func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
	 537  	s.at(chain)
	 538  	if len(chain.Field) == 0 {
	 539  		s.errorf("internal error: no fields in evalChainNode")
	 540  	}
	 541  	if chain.Node.Type() == parse.NodeNil {
	 542  		s.errorf("indirection through explicit nil in %s", chain)
	 543  	}
	 544  	// (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
	 545  	pipe := s.evalArg(dot, nil, chain.Node)
	 546  	return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
	 547  }
	 548  
	 549  func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
	 550  	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
	 551  	s.at(variable)
	 552  	value := s.varValue(variable.Ident[0])
	 553  	if len(variable.Ident) == 1 {
	 554  		s.notAFunction(args, final)
	 555  		return value
	 556  	}
	 557  	return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
	 558  }
	 559  
	 560  // evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
	 561  // dot is the environment in which to evaluate arguments, while
	 562  // receiver is the value being walked along the chain.
	 563  func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
	 564  	n := len(ident)
	 565  	for i := 0; i < n-1; i++ {
	 566  		receiver = s.evalField(dot, ident[i], node, nil, missingVal, receiver)
	 567  	}
	 568  	// Now if it's a method, it gets the arguments.
	 569  	return s.evalField(dot, ident[n-1], node, args, final, receiver)
	 570  }
	 571  
	 572  func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
	 573  	s.at(node)
	 574  	name := node.Ident
	 575  	function, ok := findFunction(name, s.tmpl)
	 576  	if !ok {
	 577  		s.errorf("%q is not a defined function", name)
	 578  	}
	 579  	return s.evalCall(dot, function, cmd, name, args, final)
	 580  }
	 581  
	 582  // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
	 583  // The 'final' argument represents the return value from the preceding
	 584  // value of the pipeline, if any.
	 585  func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
	 586  	if !receiver.IsValid() {
	 587  		if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
	 588  			s.errorf("nil data; no entry for key %q", fieldName)
	 589  		}
	 590  		return zero
	 591  	}
	 592  	typ := receiver.Type()
	 593  	receiver, isNil := indirect(receiver)
	 594  	if receiver.Kind() == reflect.Interface && isNil {
	 595  		// Calling a method on a nil interface can't work. The
	 596  		// MethodByName method call below would panic.
	 597  		s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
	 598  		return zero
	 599  	}
	 600  
	 601  	// Unless it's an interface, need to get to a value of type *T to guarantee
	 602  	// we see all methods of T and *T.
	 603  	ptr := receiver
	 604  	if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Ptr && ptr.CanAddr() {
	 605  		ptr = ptr.Addr()
	 606  	}
	 607  	if method := ptr.MethodByName(fieldName); method.IsValid() {
	 608  		return s.evalCall(dot, method, node, fieldName, args, final)
	 609  	}
	 610  	hasArgs := len(args) > 1 || final != missingVal
	 611  	// It's not a method; must be a field of a struct or an element of a map.
	 612  	switch receiver.Kind() {
	 613  	case reflect.Struct:
	 614  		tField, ok := receiver.Type().FieldByName(fieldName)
	 615  		if ok {
	 616  			field := receiver.FieldByIndex(tField.Index)
	 617  			if !tField.IsExported() {
	 618  				s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
	 619  			}
	 620  			// If it's a function, we must call it.
	 621  			if hasArgs {
	 622  				s.errorf("%s has arguments but cannot be invoked as function", fieldName)
	 623  			}
	 624  			return field
	 625  		}
	 626  	case reflect.Map:
	 627  		// If it's a map, attempt to use the field name as a key.
	 628  		nameVal := reflect.ValueOf(fieldName)
	 629  		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
	 630  			if hasArgs {
	 631  				s.errorf("%s is not a method but has arguments", fieldName)
	 632  			}
	 633  			result := receiver.MapIndex(nameVal)
	 634  			if !result.IsValid() {
	 635  				switch s.tmpl.option.missingKey {
	 636  				case mapInvalid:
	 637  					// Just use the invalid value.
	 638  				case mapZeroValue:
	 639  					result = reflect.Zero(receiver.Type().Elem())
	 640  				case mapError:
	 641  					s.errorf("map has no entry for key %q", fieldName)
	 642  				}
	 643  			}
	 644  			return result
	 645  		}
	 646  	case reflect.Ptr:
	 647  		etyp := receiver.Type().Elem()
	 648  		if etyp.Kind() == reflect.Struct {
	 649  			if _, ok := etyp.FieldByName(fieldName); !ok {
	 650  				// If there's no such field, say "can't evaluate"
	 651  				// instead of "nil pointer evaluating".
	 652  				break
	 653  			}
	 654  		}
	 655  		if isNil {
	 656  			s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
	 657  		}
	 658  	}
	 659  	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
	 660  	panic("not reached")
	 661  }
	 662  
	 663  var (
	 664  	errorType				= reflect.TypeOf((*error)(nil)).Elem()
	 665  	fmtStringerType	= reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
	 666  	reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
	 667  )
	 668  
	 669  // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
	 670  // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
	 671  // as the function itself.
	 672  func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
	 673  	if args != nil {
	 674  		args = args[1:] // Zeroth arg is function name/node; not passed to function.
	 675  	}
	 676  	typ := fun.Type()
	 677  	numIn := len(args)
	 678  	if final != missingVal {
	 679  		numIn++
	 680  	}
	 681  	numFixed := len(args)
	 682  	if typ.IsVariadic() {
	 683  		numFixed = typ.NumIn() - 1 // last arg is the variadic one.
	 684  		if numIn < numFixed {
	 685  			s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
	 686  		}
	 687  	} else if numIn != typ.NumIn() {
	 688  		s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
	 689  	}
	 690  	if !goodFunc(typ) {
	 691  		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
	 692  		s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
	 693  	}
	 694  	// Build the arg list.
	 695  	argv := make([]reflect.Value, numIn)
	 696  	// Args must be evaluated. Fixed args first.
	 697  	i := 0
	 698  	for ; i < numFixed && i < len(args); i++ {
	 699  		argv[i] = s.evalArg(dot, typ.In(i), args[i])
	 700  	}
	 701  	// Now the ... args.
	 702  	if typ.IsVariadic() {
	 703  		argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
	 704  		for ; i < len(args); i++ {
	 705  			argv[i] = s.evalArg(dot, argType, args[i])
	 706  		}
	 707  	}
	 708  	// Add final value if necessary.
	 709  	if final != missingVal {
	 710  		t := typ.In(typ.NumIn() - 1)
	 711  		if typ.IsVariadic() {
	 712  			if numIn-1 < numFixed {
	 713  				// The added final argument corresponds to a fixed parameter of the function.
	 714  				// Validate against the type of the actual parameter.
	 715  				t = typ.In(numIn - 1)
	 716  			} else {
	 717  				// The added final argument corresponds to the variadic part.
	 718  				// Validate against the type of the elements of the variadic slice.
	 719  				t = t.Elem()
	 720  			}
	 721  		}
	 722  		argv[i] = s.validateType(final, t)
	 723  	}
	 724  	v, err := safeCall(fun, argv)
	 725  	// If we have an error that is not nil, stop execution and return that
	 726  	// error to the caller.
	 727  	if err != nil {
	 728  		s.at(node)
	 729  		s.errorf("error calling %s: %w", name, err)
	 730  	}
	 731  	if v.Type() == reflectValueType {
	 732  		v = v.Interface().(reflect.Value)
	 733  	}
	 734  	return v
	 735  }
	 736  
	 737  // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
	 738  func canBeNil(typ reflect.Type) bool {
	 739  	switch typ.Kind() {
	 740  	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
	 741  		return true
	 742  	case reflect.Struct:
	 743  		return typ == reflectValueType
	 744  	}
	 745  	return false
	 746  }
	 747  
	 748  // validateType guarantees that the value is valid and assignable to the type.
	 749  func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
	 750  	if !value.IsValid() {
	 751  		if typ == nil {
	 752  			// An untyped nil interface{}. Accept as a proper nil value.
	 753  			return reflect.ValueOf(nil)
	 754  		}
	 755  		if canBeNil(typ) {
	 756  			// Like above, but use the zero value of the non-nil type.
	 757  			return reflect.Zero(typ)
	 758  		}
	 759  		s.errorf("invalid value; expected %s", typ)
	 760  	}
	 761  	if typ == reflectValueType && value.Type() != typ {
	 762  		return reflect.ValueOf(value)
	 763  	}
	 764  	if typ != nil && !value.Type().AssignableTo(typ) {
	 765  		if value.Kind() == reflect.Interface && !value.IsNil() {
	 766  			value = value.Elem()
	 767  			if value.Type().AssignableTo(typ) {
	 768  				return value
	 769  			}
	 770  			// fallthrough
	 771  		}
	 772  		// Does one dereference or indirection work? We could do more, as we
	 773  		// do with method receivers, but that gets messy and method receivers
	 774  		// are much more constrained, so it makes more sense there than here.
	 775  		// Besides, one is almost always all you need.
	 776  		switch {
	 777  		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
	 778  			value = value.Elem()
	 779  			if !value.IsValid() {
	 780  				s.errorf("dereference of nil pointer of type %s", typ)
	 781  			}
	 782  		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
	 783  			value = value.Addr()
	 784  		default:
	 785  			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
	 786  		}
	 787  	}
	 788  	return value
	 789  }
	 790  
	 791  func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
	 792  	s.at(n)
	 793  	switch arg := n.(type) {
	 794  	case *parse.DotNode:
	 795  		return s.validateType(dot, typ)
	 796  	case *parse.NilNode:
	 797  		if canBeNil(typ) {
	 798  			return reflect.Zero(typ)
	 799  		}
	 800  		s.errorf("cannot assign nil to %s", typ)
	 801  	case *parse.FieldNode:
	 802  		return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, missingVal), typ)
	 803  	case *parse.VariableNode:
	 804  		return s.validateType(s.evalVariableNode(dot, arg, nil, missingVal), typ)
	 805  	case *parse.PipeNode:
	 806  		return s.validateType(s.evalPipeline(dot, arg), typ)
	 807  	case *parse.IdentifierNode:
	 808  		return s.validateType(s.evalFunction(dot, arg, arg, nil, missingVal), typ)
	 809  	case *parse.ChainNode:
	 810  		return s.validateType(s.evalChainNode(dot, arg, nil, missingVal), typ)
	 811  	}
	 812  	switch typ.Kind() {
	 813  	case reflect.Bool:
	 814  		return s.evalBool(typ, n)
	 815  	case reflect.Complex64, reflect.Complex128:
	 816  		return s.evalComplex(typ, n)
	 817  	case reflect.Float32, reflect.Float64:
	 818  		return s.evalFloat(typ, n)
	 819  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
	 820  		return s.evalInteger(typ, n)
	 821  	case reflect.Interface:
	 822  		if typ.NumMethod() == 0 {
	 823  			return s.evalEmptyInterface(dot, n)
	 824  		}
	 825  	case reflect.Struct:
	 826  		if typ == reflectValueType {
	 827  			return reflect.ValueOf(s.evalEmptyInterface(dot, n))
	 828  		}
	 829  	case reflect.String:
	 830  		return s.evalString(typ, n)
	 831  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
	 832  		return s.evalUnsignedInteger(typ, n)
	 833  	}
	 834  	s.errorf("can't handle %s for arg of type %s", n, typ)
	 835  	panic("not reached")
	 836  }
	 837  
	 838  func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
	 839  	s.at(n)
	 840  	if n, ok := n.(*parse.BoolNode); ok {
	 841  		value := reflect.New(typ).Elem()
	 842  		value.SetBool(n.True)
	 843  		return value
	 844  	}
	 845  	s.errorf("expected bool; found %s", n)
	 846  	panic("not reached")
	 847  }
	 848  
	 849  func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
	 850  	s.at(n)
	 851  	if n, ok := n.(*parse.StringNode); ok {
	 852  		value := reflect.New(typ).Elem()
	 853  		value.SetString(n.Text)
	 854  		return value
	 855  	}
	 856  	s.errorf("expected string; found %s", n)
	 857  	panic("not reached")
	 858  }
	 859  
	 860  func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
	 861  	s.at(n)
	 862  	if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
	 863  		value := reflect.New(typ).Elem()
	 864  		value.SetInt(n.Int64)
	 865  		return value
	 866  	}
	 867  	s.errorf("expected integer; found %s", n)
	 868  	panic("not reached")
	 869  }
	 870  
	 871  func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
	 872  	s.at(n)
	 873  	if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
	 874  		value := reflect.New(typ).Elem()
	 875  		value.SetUint(n.Uint64)
	 876  		return value
	 877  	}
	 878  	s.errorf("expected unsigned integer; found %s", n)
	 879  	panic("not reached")
	 880  }
	 881  
	 882  func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
	 883  	s.at(n)
	 884  	if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
	 885  		value := reflect.New(typ).Elem()
	 886  		value.SetFloat(n.Float64)
	 887  		return value
	 888  	}
	 889  	s.errorf("expected float; found %s", n)
	 890  	panic("not reached")
	 891  }
	 892  
	 893  func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
	 894  	if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
	 895  		value := reflect.New(typ).Elem()
	 896  		value.SetComplex(n.Complex128)
	 897  		return value
	 898  	}
	 899  	s.errorf("expected complex; found %s", n)
	 900  	panic("not reached")
	 901  }
	 902  
	 903  func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
	 904  	s.at(n)
	 905  	switch n := n.(type) {
	 906  	case *parse.BoolNode:
	 907  		return reflect.ValueOf(n.True)
	 908  	case *parse.DotNode:
	 909  		return dot
	 910  	case *parse.FieldNode:
	 911  		return s.evalFieldNode(dot, n, nil, missingVal)
	 912  	case *parse.IdentifierNode:
	 913  		return s.evalFunction(dot, n, n, nil, missingVal)
	 914  	case *parse.NilNode:
	 915  		// NilNode is handled in evalArg, the only place that calls here.
	 916  		s.errorf("evalEmptyInterface: nil (can't happen)")
	 917  	case *parse.NumberNode:
	 918  		return s.idealConstant(n)
	 919  	case *parse.StringNode:
	 920  		return reflect.ValueOf(n.Text)
	 921  	case *parse.VariableNode:
	 922  		return s.evalVariableNode(dot, n, nil, missingVal)
	 923  	case *parse.PipeNode:
	 924  		return s.evalPipeline(dot, n)
	 925  	}
	 926  	s.errorf("can't handle assignment of %s to empty interface argument", n)
	 927  	panic("not reached")
	 928  }
	 929  
	 930  // indirect returns the item at the end of indirection, and a bool to indicate
	 931  // if it's nil. If the returned bool is true, the returned value's kind will be
	 932  // either a pointer or interface.
	 933  func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
	 934  	for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
	 935  		if v.IsNil() {
	 936  			return v, true
	 937  		}
	 938  	}
	 939  	return v, false
	 940  }
	 941  
	 942  // indirectInterface returns the concrete value in an interface value,
	 943  // or else the zero reflect.Value.
	 944  // That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
	 945  // the fact that x was an interface value is forgotten.
	 946  func indirectInterface(v reflect.Value) reflect.Value {
	 947  	if v.Kind() != reflect.Interface {
	 948  		return v
	 949  	}
	 950  	if v.IsNil() {
	 951  		return reflect.Value{}
	 952  	}
	 953  	return v.Elem()
	 954  }
	 955  
	 956  // printValue writes the textual representation of the value to the output of
	 957  // the template.
	 958  func (s *state) printValue(n parse.Node, v reflect.Value) {
	 959  	s.at(n)
	 960  	iface, ok := printableValue(v)
	 961  	if !ok {
	 962  		s.errorf("can't print %s of type %s", n, v.Type())
	 963  	}
	 964  	_, err := fmt.Fprint(s.wr, iface)
	 965  	if err != nil {
	 966  		s.writeError(err)
	 967  	}
	 968  }
	 969  
	 970  // printableValue returns the, possibly indirected, interface value inside v that
	 971  // is best for a call to formatted printer.
	 972  func printableValue(v reflect.Value) (interface{}, bool) {
	 973  	if v.Kind() == reflect.Ptr {
	 974  		v, _ = indirect(v) // fmt.Fprint handles nil.
	 975  	}
	 976  	if !v.IsValid() {
	 977  		return "<no value>", true
	 978  	}
	 979  
	 980  	if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
	 981  		if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
	 982  			v = v.Addr()
	 983  		} else {
	 984  			switch v.Kind() {
	 985  			case reflect.Chan, reflect.Func:
	 986  				return nil, false
	 987  			}
	 988  		}
	 989  	}
	 990  	return v.Interface(), true
	 991  }
	 992  

View as plain text