// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package template

import (
	
	
	
	
	
	
	
	
)

// maxExecDepth specifies the maximum stack depth of templates within
// templates. This limit is only practically reached by accidentally
// recursive template invocations. This limit allows us to return
// an error instead of triggering a stack overflow.
var maxExecDepth = initMaxExecDepth()

func initMaxExecDepth() int {
	if runtime.GOARCH == "wasm" {
		return 1000
	}
	return 100000
}

// state represents the state of an execution. It's not part of the
// template so that multiple executions of the same template
// can execute in parallel.
type state struct {
	tmpl  *Template
	wr    io.Writer
	node  parse.Node // current node, for errors
	vars  []variable // push-down stack of variable values.
	depth int        // the height of the stack of executing templates.
}

// variable holds the dynamic value of a variable such as $, $x etc.
type variable struct {
	name  string
	value reflect.Value
}

// push pushes a new variable on the stack.
func ( *state) ( string,  reflect.Value) {
	.vars = append(.vars, variable{, })
}

// mark returns the length of the variable stack.
func ( *state) () int {
	return len(.vars)
}

// pop pops the variable stack up to the mark.
func ( *state) ( int) {
	.vars = .vars[0:]
}

// setVar overwrites the last declared variable with the given name.
// Used by variable assignments.
func ( *state) ( string,  reflect.Value) {
	for  := .mark() - 1;  >= 0; -- {
		if .vars[].name ==  {
			.vars[].value = 
			return
		}
	}
	.errorf("undefined variable: %s", )
}

// setTopVar overwrites the top-nth variable on the stack. Used by range iterations.
func ( *state) ( int,  reflect.Value) {
	.vars[len(.vars)-].value = 
}

// varValue returns the value of the named variable.
func ( *state) ( string) reflect.Value {
	for  := .mark() - 1;  >= 0; -- {
		if .vars[].name ==  {
			return .vars[].value
		}
	}
	.errorf("undefined variable: %s", )
	return zero
}

var zero reflect.Value

type missingValType struct{}

var missingVal = reflect.ValueOf(missingValType{})

var missingValReflectType = reflect.TypeOf(missingValType{})

func isMissing( reflect.Value) bool {
	return .IsValid() && .Type() == missingValReflectType
}

// at marks the state to be on node n, for error reporting.
func ( *state) ( parse.Node) {
	.node = 
}

// doublePercent returns the string with %'s replaced by %%, if necessary,
// so it can be used safely inside a Printf format string.
func doublePercent( string) string {
	return strings.ReplaceAll(, "%", "%%")
}

// TODO: It would be nice if ExecError was more broken down, but
// the way ErrorContext embeds the template name makes the
// processing too clumsy.

// ExecError is the custom error type returned when Execute has an
// error evaluating its template. (If a write error occurs, the actual
// error is returned; it will not be of type ExecError.)
type ExecError struct {
	Name string // Name of template.
	Err  error  // Pre-formatted error.
}

func ( ExecError) () string {
	return .Err.Error()
}

func ( ExecError) () error {
	return .Err
}

// errorf records an ExecError and terminates processing.
func ( *state) ( string,  ...any) {
	 := doublePercent(.tmpl.Name())
	if .node == nil {
		 = fmt.Sprintf("template: %s: %s", , )
	} else {
		,  := .tmpl.ErrorContext(.node)
		 = fmt.Sprintf("template: %s: executing %q at <%s>: %s", , , doublePercent(), )
	}
	panic(ExecError{
		Name: .tmpl.Name(),
		Err:  fmt.Errorf(, ...),
	})
}

// writeError is the wrapper type used internally when Execute has an
// error writing to its output. We strip the wrapper in errRecover.
// Note that this is not an implementation of error, so it cannot escape
// from the package as an error value.
type writeError struct {
	Err error // Original error.
}

func ( *state) ( error) {
	panic(writeError{
		Err: ,
	})
}

// errRecover is the handler that turns panics into returns from the top
// level of Parse.
func errRecover( *error) {
	 := recover()
	if  != nil {
		switch err := .(type) {
		case runtime.Error:
			panic()
		case writeError:
			* = .Err // Strip the wrapper.
		case ExecError:
			* =  // Keep the wrapper.
		default:
			panic()
		}
	}
}

// ExecuteTemplate applies the template associated with t that has the given name
// to the specified data object and writes the output to wr.
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
func ( *Template) ( io.Writer,  string,  any) error {
	 := .Lookup()
	if  == nil {
		return fmt.Errorf("template: no template %q associated with template %q", , .name)
	}
	return .Execute(, )
}

// Execute applies a parsed template to the specified data object,
// and writes the output to wr.
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
//
// If data is a reflect.Value, the template applies to the concrete
// value that the reflect.Value holds, as in fmt.Print.
func ( *Template) ( io.Writer,  any) error {
	return .execute(, )
}

func ( *Template) ( io.Writer,  any) ( error) {
	defer errRecover(&)
	,  := .(reflect.Value)
	if ! {
		 = reflect.ValueOf()
	}
	 := &state{
		tmpl: ,
		wr:   ,
		vars: []variable{{"$", }},
	}
	if .Tree == nil || .Root == nil {
		.errorf("%q is an incomplete or empty template", .Name())
	}
	.walk(, .Root)
	return
}

// DefinedTemplates returns a string listing the defined templates,
// prefixed by the string "; defined templates are: ". If there are none,
// it returns the empty string. For generating an error message here
// and in html/template.
func ( *Template) () string {
	if .common == nil {
		return ""
	}
	var  strings.Builder
	.muTmpl.RLock()
	defer .muTmpl.RUnlock()
	for ,  := range .tmpl {
		if .Tree == nil || .Root == nil {
			continue
		}
		if .Len() == 0 {
			.WriteString("; defined templates are: ")
		} else {
			.WriteString(", ")
		}
		fmt.Fprintf(&, "%q", )
	}
	return .String()
}

// Sentinel errors for use with panic to signal early exits from range loops.
var (
	walkBreak    = errors.New("break")
	walkContinue = errors.New("continue")
)

// Walk functions step through the major pieces of the template structure,
// generating output as they go.
func ( *state) ( reflect.Value,  parse.Node) {
	.at()
	switch node := .(type) {
	case *parse.ActionNode:
		// Do not pop variables so they persist until next end.
		// Also, if the action declares variables, don't print the result.
		 := .evalPipeline(, .Pipe)
		if len(.Pipe.Decl) == 0 {
			.printValue(, )
		}
	case *parse.BreakNode:
		panic(walkBreak)
	case *parse.CommentNode:
	case *parse.ContinueNode:
		panic(walkContinue)
	case *parse.IfNode:
		.walkIfOrWith(parse.NodeIf, , .Pipe, .List, .ElseList)
	case *parse.ListNode:
		for ,  := range .Nodes {
			.(, )
		}
	case *parse.RangeNode:
		.walkRange(, )
	case *parse.TemplateNode:
		.walkTemplate(, )
	case *parse.TextNode:
		if ,  := .wr.Write(.Text);  != nil {
			.writeError()
		}
	case *parse.WithNode:
		.walkIfOrWith(parse.NodeWith, , .Pipe, .List, .ElseList)
	default:
		.errorf("unknown node: %s", )
	}
}

// walkIfOrWith walks an 'if' or 'with' node. The two control structures
// are identical in behavior except that 'with' sets dot.
func ( *state) ( parse.NodeType,  reflect.Value,  *parse.PipeNode, ,  *parse.ListNode) {
	defer .pop(.mark())
	 := .evalPipeline(, )
	,  := isTrue(indirectInterface())
	if ! {
		.errorf("if/with can't use %v", )
	}
	if  {
		if  == parse.NodeWith {
			.walk(, )
		} else {
			.walk(, )
		}
	} else if  != nil {
		.walk(, )
	}
}

// IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
// and whether the value has a meaningful truth value. This is the definition of
// truth used by if and other such actions.
func ( any) (,  bool) {
	return isTrue(reflect.ValueOf())
}

func isTrue( reflect.Value) (,  bool) {
	if !.IsValid() {
		// Something like var x interface{}, never set. It's a form of nil.
		return false, true
	}
	switch .Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		 = .Len() > 0
	case reflect.Bool:
		 = .Bool()
	case reflect.Complex64, reflect.Complex128:
		 = .Complex() != 0
	case reflect.Chan, reflect.Func, reflect.Pointer, reflect.Interface:
		 = !.IsNil()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		 = .Int() != 0
	case reflect.Float32, reflect.Float64:
		 = .Float() != 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		 = .Uint() != 0
	case reflect.Struct:
		 = true // Struct values are always true.
	default:
		return
	}
	return , true
}

func ( *state) ( reflect.Value,  *parse.RangeNode) {
	.at()
	defer func() {
		if  := recover();  != nil &&  != walkBreak {
			panic()
		}
	}()
	defer .pop(.mark())
	,  := indirect(.evalPipeline(, .Pipe))
	// mark top of stack before any variables in the body are pushed.
	 := .mark()
	 := func(,  reflect.Value) {
		if len(.Pipe.Decl) > 0 {
			if .Pipe.IsAssign {
				// With two variables, index comes first.
				// With one, we use the element.
				if len(.Pipe.Decl) > 1 {
					.setVar(.Pipe.Decl[0].Ident[0], )
				} else {
					.setVar(.Pipe.Decl[0].Ident[0], )
				}
			} else {
				// Set top var (lexically the second if there
				// are two) to the element.
				.setTopVar(1, )
			}
		}
		if len(.Pipe.Decl) > 1 {
			if .Pipe.IsAssign {
				.setVar(.Pipe.Decl[1].Ident[0], )
			} else {
				// Set next var (lexically the first if there
				// are two) to the index.
				.setTopVar(2, )
			}
		}
		defer .pop()
		defer func() {
			// Consume panic(walkContinue)
			if  := recover();  != nil &&  != walkContinue {
				panic()
			}
		}()
		.walk(, .List)
	}
	switch .Kind() {
	case reflect.Array, reflect.Slice:
		if .Len() == 0 {
			break
		}
		for  := 0;  < .Len(); ++ {
			(reflect.ValueOf(), .Index())
		}
		return
	case reflect.Map:
		if .Len() == 0 {
			break
		}
		 := fmtsort.Sort()
		for ,  := range .Key {
			(, .Value[])
		}
		return
	case reflect.Chan:
		if .IsNil() {
			break
		}
		if .Type().ChanDir() == reflect.SendDir {
			.errorf("range over send-only channel %v", )
			break
		}
		 := 0
		for ; ; ++ {
			,  := .Recv()
			if ! {
				break
			}
			(reflect.ValueOf(), )
		}
		if  == 0 {
			break
		}
		return
	case reflect.Invalid:
		break // An invalid value is likely a nil map, etc. and acts like an empty map.
	default:
		.errorf("range can't iterate over %v", )
	}
	if .ElseList != nil {
		.walk(, .ElseList)
	}
}

func ( *state) ( reflect.Value,  *parse.TemplateNode) {
	.at()
	 := .tmpl.Lookup(.Name)
	if  == nil {
		.errorf("template %q not defined", .Name)
	}
	if .depth == maxExecDepth {
		.errorf("exceeded maximum template depth (%v)", maxExecDepth)
	}
	// Variables declared by the pipeline persist.
	 = .evalPipeline(, .Pipe)
	 := *
	.depth++
	.tmpl = 
	// No dynamic scoping: template invocations inherit no variables.
	.vars = []variable{{"$", }}
	.walk(, .Root)
}

// Eval functions evaluate pipelines, commands, and their elements and extract
// values from the data structure by examining fields, calling methods, and so on.
// The printing of those values happens only through walk functions.

// evalPipeline returns the value acquired by evaluating a pipeline. If the
// pipeline has a variable declaration, the variable will be pushed on the
// stack. Callers should therefore pop the stack after they are finished
// executing commands depending on the pipeline value.
func ( *state) ( reflect.Value,  *parse.PipeNode) ( reflect.Value) {
	if  == nil {
		return
	}
	.at()
	 = missingVal
	for ,  := range .Cmds {
		 = .evalCommand(, , ) // previous value is this one's final arg.
		// If the object has type interface{}, dig down one level to the thing inside.
		if .Kind() == reflect.Interface && .Type().NumMethod() == 0 {
			 = reflect.ValueOf(.Interface()) // lovely!
		}
	}
	for ,  := range .Decl {
		if .IsAssign {
			.setVar(.Ident[0], )
		} else {
			.push(.Ident[0], )
		}
	}
	return 
}

func ( *state) ( []parse.Node,  reflect.Value) {
	if len() > 1 || !isMissing() {
		.errorf("can't give argument to non-function %s", [0])
	}
}

func ( *state) ( reflect.Value,  *parse.CommandNode,  reflect.Value) reflect.Value {
	 := .Args[0]
	switch n := .(type) {
	case *parse.FieldNode:
		return .evalFieldNode(, , .Args, )
	case *parse.ChainNode:
		return .evalChainNode(, , .Args, )
	case *parse.IdentifierNode:
		// Must be a function.
		return .evalFunction(, , , .Args, )
	case *parse.PipeNode:
		// Parenthesized pipeline. The arguments are all inside the pipeline; final must be absent.
		.notAFunction(.Args, )
		return .evalPipeline(, )
	case *parse.VariableNode:
		return .evalVariableNode(, , .Args, )
	}
	.at()
	.notAFunction(.Args, )
	switch word := .(type) {
	case *parse.BoolNode:
		return reflect.ValueOf(.True)
	case *parse.DotNode:
		return 
	case *parse.NilNode:
		.errorf("nil is not a command")
	case *parse.NumberNode:
		return .idealConstant()
	case *parse.StringNode:
		return reflect.ValueOf(.Text)
	}
	.errorf("can't evaluate command %q", )
	panic("not reached")
}

// idealConstant is called to return the value of a number in a context where
// we don't know the type. In that case, the syntax of the number tells us
// its type, and we use Go rules to resolve. Note there is no such thing as
// a uint ideal constant in this situation - the value must be of int type.
func ( *state) ( *parse.NumberNode) reflect.Value {
	// These are ideal constants but we don't know the type
	// and we have no context.  (If it was a method argument,
	// we'd know what we need.) The syntax guides us to some extent.
	.at()
	switch {
	case .IsComplex:
		return reflect.ValueOf(.Complex128) // incontrovertible.

	case .IsFloat &&
		!isHexInt(.Text) && !isRuneInt(.Text) &&
		strings.ContainsAny(.Text, ".eEpP"):
		return reflect.ValueOf(.Float64)

	case .IsInt:
		 := int(.Int64)
		if int64() != .Int64 {
			.errorf("%s overflows int", .Text)
		}
		return reflect.ValueOf()

	case .IsUint:
		.errorf("%s overflows int", .Text)
	}
	return zero
}

func isRuneInt( string) bool {
	return len() > 0 && [0] == '\''
}

func isHexInt( string) bool {
	return len() > 2 && [0] == '0' && ([1] == 'x' || [1] == 'X') && !strings.ContainsAny(, "pP")
}

func ( *state) ( reflect.Value,  *parse.FieldNode,  []parse.Node,  reflect.Value) reflect.Value {
	.at()
	return .evalFieldChain(, , , .Ident, , )
}

func ( *state) ( reflect.Value,  *parse.ChainNode,  []parse.Node,  reflect.Value) reflect.Value {
	.at()
	if len(.Field) == 0 {
		.errorf("internal error: no fields in evalChainNode")
	}
	if .Node.Type() == parse.NodeNil {
		.errorf("indirection through explicit nil in %s", )
	}
	// (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
	 := .evalArg(, nil, .Node)
	return .evalFieldChain(, , , .Field, , )
}

func ( *state) ( reflect.Value,  *parse.VariableNode,  []parse.Node,  reflect.Value) reflect.Value {
	// $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
	.at()
	 := .varValue(.Ident[0])
	if len(.Ident) == 1 {
		.notAFunction(, )
		return 
	}
	return .evalFieldChain(, , , .Ident[1:], , )
}

// evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
// dot is the environment in which to evaluate arguments, while
// receiver is the value being walked along the chain.
func ( *state) (,  reflect.Value,  parse.Node,  []string,  []parse.Node,  reflect.Value) reflect.Value {
	 := len()
	for  := 0;  < -1; ++ {
		 = .evalField(, [], , nil, missingVal, )
	}
	// Now if it's a method, it gets the arguments.
	return .evalField(, [-1], , , , )
}

func ( *state) ( reflect.Value,  *parse.IdentifierNode,  parse.Node,  []parse.Node,  reflect.Value) reflect.Value {
	.at()
	 := .Ident
	, ,  := findFunction(, .tmpl)
	if ! {
		.errorf("%q is not a defined function", )
	}
	return .evalCall(, , , , , , )
}

// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
// The 'final' argument represents the return value from the preceding
// value of the pipeline, if any.
func ( *state) ( reflect.Value,  string,  parse.Node,  []parse.Node, ,  reflect.Value) reflect.Value {
	if !.IsValid() {
		if .tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
			.errorf("nil data; no entry for key %q", )
		}
		return zero
	}
	 := .Type()
	,  := indirect()
	if .Kind() == reflect.Interface &&  {
		// Calling a method on a nil interface can't work. The
		// MethodByName method call below would panic.
		.errorf("nil pointer evaluating %s.%s", , )
		return zero
	}

	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
	 := 
	if .Kind() != reflect.Interface && .Kind() != reflect.Pointer && .CanAddr() {
		 = .Addr()
	}
	if  := .MethodByName(); .IsValid() {
		return .evalCall(, , false, , , , )
	}
	 := len() > 1 || !isMissing()
	// It's not a method; must be a field of a struct or an element of a map.
	switch .Kind() {
	case reflect.Struct:
		,  := .Type().FieldByName()
		if  {
			,  := .FieldByIndexErr(.Index)
			if !.IsExported() {
				.errorf("%s is an unexported field of struct type %s", , )
			}
			if  != nil {
				.errorf("%v", )
			}
			// If it's a function, we must call it.
			if  {
				.errorf("%s has arguments but cannot be invoked as function", )
			}
			return 
		}
	case reflect.Map:
		// If it's a map, attempt to use the field name as a key.
		 := reflect.ValueOf()
		if .Type().AssignableTo(.Type().Key()) {
			if  {
				.errorf("%s is not a method but has arguments", )
			}
			 := .MapIndex()
			if !.IsValid() {
				switch .tmpl.option.missingKey {
				case mapInvalid:
					// Just use the invalid value.
				case mapZeroValue:
					 = reflect.Zero(.Type().Elem())
				case mapError:
					.errorf("map has no entry for key %q", )
				}
			}
			return 
		}
	case reflect.Pointer:
		 := .Type().Elem()
		if .Kind() == reflect.Struct {
			if ,  := .FieldByName(); ! {
				// If there's no such field, say "can't evaluate"
				// instead of "nil pointer evaluating".
				break
			}
		}
		if  {
			.errorf("nil pointer evaluating %s.%s", , )
		}
	}
	.errorf("can't evaluate field %s in type %s", , )
	panic("not reached")
}

var (
	errorType        = reflect.TypeOf((*error)(nil)).Elem()
	fmtStringerType  = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
	reflectValueType = reflect.TypeOf((*reflect.Value)(nil)).Elem()
)

// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
// as the function itself.
func ( *state) (,  reflect.Value,  bool,  parse.Node,  string,  []parse.Node,  reflect.Value) reflect.Value {
	if  != nil {
		 = [1:] // Zeroth arg is function name/node; not passed to function.
	}
	 := .Type()
	 := len()
	if !isMissing() {
		++
	}
	 := len()
	if .IsVariadic() {
		 = .NumIn() - 1 // last arg is the variadic one.
		if  <  {
			.errorf("wrong number of args for %s: want at least %d got %d", , .NumIn()-1, len())
		}
	} else if  != .NumIn() {
		.errorf("wrong number of args for %s: want %d got %d", , .NumIn(), )
	}
	if !goodFunc() {
		// TODO: This could still be a confusing error; maybe goodFunc should provide info.
		.errorf("can't call method/function %q with %d results", , .NumOut())
	}

	 := func( reflect.Value) reflect.Value {
		if .Type() == reflectValueType {
			 = .Interface().(reflect.Value)
		}
		return 
	}

	// Special case for builtin and/or, which short-circuit.
	if  && ( == "and" ||  == "or") {
		 := .In(0)
		var  reflect.Value
		for ,  := range  {
			 = .evalArg(, , ).Interface().(reflect.Value)
			if truth() == ( == "or") {
				// This value was already unwrapped
				// by the .Interface().(reflect.Value).
				return 
			}
		}
		if  != missingVal {
			// The last argument to and/or is coming from
			// the pipeline. We didn't short circuit on an earlier
			// argument, so we are going to return this one.
			// We don't have to evaluate final, but we do
			// have to check its type. Then, since we are
			// going to return it, we have to unwrap it.
			 = (.validateType(, ))
		}
		return 
	}

	// Build the arg list.
	 := make([]reflect.Value, )
	// Args must be evaluated. Fixed args first.
	 := 0
	for ;  <  &&  < len(); ++ {
		[] = .evalArg(, .In(), [])
	}
	// Now the ... args.
	if .IsVariadic() {
		 := .In(.NumIn() - 1).Elem() // Argument is a slice.
		for ;  < len(); ++ {
			[] = .evalArg(, , [])
		}
	}
	// Add final value if necessary.
	if !isMissing() {
		 := .In(.NumIn() - 1)
		if .IsVariadic() {
			if -1 <  {
				// The added final argument corresponds to a fixed parameter of the function.
				// Validate against the type of the actual parameter.
				 = .In( - 1)
			} else {
				// The added final argument corresponds to the variadic part.
				// Validate against the type of the elements of the variadic slice.
				 = .Elem()
			}
		}
		[] = .validateType(, )
	}
	,  := safeCall(, )
	// If we have an error that is not nil, stop execution and return that
	// error to the caller.
	if  != nil {
		.at()
		.errorf("error calling %s: %w", , )
	}
	return ()
}

// canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
func canBeNil( reflect.Type) bool {
	switch .Kind() {
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
		return true
	case reflect.Struct:
		return  == reflectValueType
	}
	return false
}

// validateType guarantees that the value is valid and assignable to the type.
func ( *state) ( reflect.Value,  reflect.Type) reflect.Value {
	if !.IsValid() {
		if  == nil {
			// An untyped nil interface{}. Accept as a proper nil value.
			return reflect.ValueOf(nil)
		}
		if canBeNil() {
			// Like above, but use the zero value of the non-nil type.
			return reflect.Zero()
		}
		.errorf("invalid value; expected %s", )
	}
	if  == reflectValueType && .Type() !=  {
		return reflect.ValueOf()
	}
	if  != nil && !.Type().AssignableTo() {
		if .Kind() == reflect.Interface && !.IsNil() {
			 = .Elem()
			if .Type().AssignableTo() {
				return 
			}
			// fallthrough
		}
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
		case .Kind() == reflect.Pointer && .Type().Elem().AssignableTo():
			 = .Elem()
			if !.IsValid() {
				.errorf("dereference of nil pointer of type %s", )
			}
		case reflect.PointerTo(.Type()).AssignableTo() && .CanAddr():
			 = .Addr()
		default:
			.errorf("wrong type for value; expected %s; got %s", , .Type())
		}
	}
	return 
}

func ( *state) ( reflect.Value,  reflect.Type,  parse.Node) reflect.Value {
	.at()
	switch arg := .(type) {
	case *parse.DotNode:
		return .validateType(, )
	case *parse.NilNode:
		if canBeNil() {
			return reflect.Zero()
		}
		.errorf("cannot assign nil to %s", )
	case *parse.FieldNode:
		return .validateType(.evalFieldNode(, , []parse.Node{}, missingVal), )
	case *parse.VariableNode:
		return .validateType(.evalVariableNode(, , nil, missingVal), )
	case *parse.PipeNode:
		return .validateType(.evalPipeline(, ), )
	case *parse.IdentifierNode:
		return .validateType(.evalFunction(, , , nil, missingVal), )
	case *parse.ChainNode:
		return .validateType(.evalChainNode(, , nil, missingVal), )
	}
	switch .Kind() {
	case reflect.Bool:
		return .evalBool(, )
	case reflect.Complex64, reflect.Complex128:
		return .evalComplex(, )
	case reflect.Float32, reflect.Float64:
		return .evalFloat(, )
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return .evalInteger(, )
	case reflect.Interface:
		if .NumMethod() == 0 {
			return .evalEmptyInterface(, )
		}
	case reflect.Struct:
		if  == reflectValueType {
			return reflect.ValueOf(.evalEmptyInterface(, ))
		}
	case reflect.String:
		return .evalString(, )
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return .evalUnsignedInteger(, )
	}
	.errorf("can't handle %s for arg of type %s", , )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	.at()
	if ,  := .(*parse.BoolNode);  {
		 := reflect.New().Elem()
		.SetBool(.True)
		return 
	}
	.errorf("expected bool; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	.at()
	if ,  := .(*parse.StringNode);  {
		 := reflect.New().Elem()
		.SetString(.Text)
		return 
	}
	.errorf("expected string; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	.at()
	if ,  := .(*parse.NumberNode);  && .IsInt {
		 := reflect.New().Elem()
		.SetInt(.Int64)
		return 
	}
	.errorf("expected integer; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	.at()
	if ,  := .(*parse.NumberNode);  && .IsUint {
		 := reflect.New().Elem()
		.SetUint(.Uint64)
		return 
	}
	.errorf("expected unsigned integer; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	.at()
	if ,  := .(*parse.NumberNode);  && .IsFloat {
		 := reflect.New().Elem()
		.SetFloat(.Float64)
		return 
	}
	.errorf("expected float; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Type,  parse.Node) reflect.Value {
	if ,  := .(*parse.NumberNode);  && .IsComplex {
		 := reflect.New().Elem()
		.SetComplex(.Complex128)
		return 
	}
	.errorf("expected complex; found %s", )
	panic("not reached")
}

func ( *state) ( reflect.Value,  parse.Node) reflect.Value {
	.at()
	switch n := .(type) {
	case *parse.BoolNode:
		return reflect.ValueOf(.True)
	case *parse.DotNode:
		return 
	case *parse.FieldNode:
		return .evalFieldNode(, , nil, missingVal)
	case *parse.IdentifierNode:
		return .evalFunction(, , , nil, missingVal)
	case *parse.NilNode:
		// NilNode is handled in evalArg, the only place that calls here.
		.errorf("evalEmptyInterface: nil (can't happen)")
	case *parse.NumberNode:
		return .idealConstant()
	case *parse.StringNode:
		return reflect.ValueOf(.Text)
	case *parse.VariableNode:
		return .evalVariableNode(, , nil, missingVal)
	case *parse.PipeNode:
		return .evalPipeline(, )
	}
	.errorf("can't handle assignment of %s to empty interface argument", )
	panic("not reached")
}

// indirect returns the item at the end of indirection, and a bool to indicate
// if it's nil. If the returned bool is true, the returned value's kind will be
// either a pointer or interface.
func indirect( reflect.Value) ( reflect.Value,  bool) {
	for ; .Kind() == reflect.Pointer || .Kind() == reflect.Interface;  = .Elem() {
		if .IsNil() {
			return , true
		}
	}
	return , false
}

// indirectInterface returns the concrete value in an interface value,
// or else the zero reflect.Value.
// That is, if v represents the interface value x, the result is the same as reflect.ValueOf(x):
// the fact that x was an interface value is forgotten.
func indirectInterface( reflect.Value) reflect.Value {
	if .Kind() != reflect.Interface {
		return 
	}
	if .IsNil() {
		return reflect.Value{}
	}
	return .Elem()
}

// printValue writes the textual representation of the value to the output of
// the template.
func ( *state) ( parse.Node,  reflect.Value) {
	.at()
	,  := printableValue()
	if ! {
		.errorf("can't print %s of type %s", , .Type())
	}
	,  := fmt.Fprint(.wr, )
	if  != nil {
		.writeError()
	}
}

// printableValue returns the, possibly indirected, interface value inside v that
// is best for a call to formatted printer.
func printableValue( reflect.Value) (any, bool) {
	if .Kind() == reflect.Pointer {
		, _ = indirect() // fmt.Fprint handles nil.
	}
	if !.IsValid() {
		return "<no value>", true
	}

	if !.Type().Implements(errorType) && !.Type().Implements(fmtStringerType) {
		if .CanAddr() && (reflect.PointerTo(.Type()).Implements(errorType) || reflect.PointerTo(.Type()).Implements(fmtStringerType)) {
			 = .Addr()
		} else {
			switch .Kind() {
			case reflect.Chan, reflect.Func:
				return nil, false
			}
		}
	}
	return .Interface(), true
}