// 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 (
	
	
	
	
	
	
	
	
	
)

// FuncMap is the type of the map defining the mapping from names to functions.
// Each function must have either a single return value, or two return values of
// which the second has type error. In that case, if the second (error)
// return value evaluates to non-nil during execution, execution terminates and
// Execute returns that error.
//
// Errors returned by Execute wrap the underlying error; call errors.As to
// unwrap them.
//
// When template execution invokes a function with an argument list, that list
// must be assignable to the function's parameter types. Functions meant to
// apply to arguments of arbitrary type can use parameters of type interface{} or
// of type reflect.Value. Similarly, functions meant to return a result of arbitrary
// type can return interface{} or reflect.Value.
type FuncMap map[string]any

// builtins returns the FuncMap.
// It is not a global variable so the linker can dead code eliminate
// more when this isn't called. See golang.org/issue/36021.
// TODO: revert this back to a global map once golang.org/issue/2559 is fixed.
func builtins() FuncMap {
	return FuncMap{
		"and":      and,
		"call":     call,
		"html":     HTMLEscaper,
		"index":    index,
		"slice":    slice,
		"js":       JSEscaper,
		"len":      length,
		"not":      not,
		"or":       or,
		"print":    fmt.Sprint,
		"printf":   fmt.Sprintf,
		"println":  fmt.Sprintln,
		"urlquery": URLQueryEscaper,

		// Comparisons
		"eq": eq, // ==
		"ge": ge, // >=
		"gt": gt, // >
		"le": le, // <=
		"lt": lt, // <
		"ne": ne, // !=
	}
}

var builtinFuncsOnce struct {
	sync.Once
	v map[string]reflect.Value
}

// builtinFuncsOnce lazily computes & caches the builtinFuncs map.
// TODO: revert this back to a global map once golang.org/issue/2559 is fixed.
func builtinFuncs() map[string]reflect.Value {
	builtinFuncsOnce.Do(func() {
		builtinFuncsOnce.v = createValueFuncs(builtins())
	})
	return builtinFuncsOnce.v
}

// createValueFuncs turns a FuncMap into a map[string]reflect.Value
func createValueFuncs( FuncMap) map[string]reflect.Value {
	 := make(map[string]reflect.Value)
	addValueFuncs(, )
	return 
}

// addValueFuncs adds to values the functions in funcs, converting them to reflect.Values.
func addValueFuncs( map[string]reflect.Value,  FuncMap) {
	for ,  := range  {
		if !goodName() {
			panic(fmt.Errorf("function name %q is not a valid identifier", ))
		}
		 := reflect.ValueOf()
		if .Kind() != reflect.Func {
			panic("value for " +  + " not a function")
		}
		if !goodFunc(.Type()) {
			panic(fmt.Errorf("can't install method/function %q with %d results", , .Type().NumOut()))
		}
		[] = 
	}
}

// addFuncs adds to values the functions in funcs. It does no checking of the input -
// call addValueFuncs first.
func addFuncs(,  FuncMap) {
	for ,  := range  {
		[] = 
	}
}

// goodFunc reports whether the function or method has the right result signature.
func goodFunc( reflect.Type) bool {
	// We allow functions with 1 result or 2 results where the second is an error.
	switch {
	case .NumOut() == 1:
		return true
	case .NumOut() == 2 && .Out(1) == errorType:
		return true
	}
	return false
}

// goodName reports whether the function name is a valid identifier.
func goodName( string) bool {
	if  == "" {
		return false
	}
	for ,  := range  {
		switch {
		case  == '_':
		case  == 0 && !unicode.IsLetter():
			return false
		case !unicode.IsLetter() && !unicode.IsDigit():
			return false
		}
	}
	return true
}

// findFunction looks for a function in the template, and global map.
func findFunction( string,  *Template) ( reflect.Value, ,  bool) {
	if  != nil && .common != nil {
		.muFuncs.RLock()
		defer .muFuncs.RUnlock()
		if  := .execFuncs[]; .IsValid() {
			return , false, true
		}
	}
	if  := builtinFuncs()[]; .IsValid() {
		return , true, true
	}
	return reflect.Value{}, false, false
}

// prepareArg checks if value can be used as an argument of type argType, and
// converts an invalid value to appropriate zero if possible.
func prepareArg( reflect.Value,  reflect.Type) (reflect.Value, error) {
	if !.IsValid() {
		if !canBeNil() {
			return reflect.Value{}, fmt.Errorf("value is nil; should be of type %s", )
		}
		 = reflect.Zero()
	}
	if .Type().AssignableTo() {
		return , nil
	}
	if intLike(.Kind()) && intLike(.Kind()) && .Type().ConvertibleTo() {
		 = .Convert()
		return , nil
	}
	return reflect.Value{}, fmt.Errorf("value has type %s; should be %s", .Type(), )
}

func intLike( reflect.Kind) bool {
	switch  {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return true
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return true
	}
	return false
}

// indexArg checks if a reflect.Value can be used as an index, and converts it to int if possible.
func indexArg( reflect.Value,  int) (int, error) {
	var  int64
	switch .Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		 = .Int()
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		 = int64(.Uint())
	case reflect.Invalid:
		return 0, fmt.Errorf("cannot index slice/array with nil")
	default:
		return 0, fmt.Errorf("cannot index slice/array with type %s", .Type())
	}
	if  < 0 || int() < 0 || int() >  {
		return 0, fmt.Errorf("index out of range: %d", )
	}
	return int(), nil
}

// Indexing.

// index returns the result of indexing its first argument by the following
// arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each
// indexed item must be a map, slice, or array.
func index( reflect.Value,  ...reflect.Value) (reflect.Value, error) {
	 = indirectInterface()
	if !.IsValid() {
		return reflect.Value{}, fmt.Errorf("index of untyped nil")
	}
	for ,  := range  {
		 = indirectInterface()
		var  bool
		if ,  = indirect();  {
			return reflect.Value{}, fmt.Errorf("index of nil pointer")
		}
		switch .Kind() {
		case reflect.Array, reflect.Slice, reflect.String:
			,  := indexArg(, .Len())
			if  != nil {
				return reflect.Value{}, 
			}
			 = .Index()
		case reflect.Map:
			,  := prepareArg(, .Type().Key())
			if  != nil {
				return reflect.Value{}, 
			}
			if  := .MapIndex(); .IsValid() {
				 = 
			} else {
				 = reflect.Zero(.Type().Elem())
			}
		case reflect.Invalid:
			// the loop holds invariant: item.IsValid()
			panic("unreachable")
		default:
			return reflect.Value{}, fmt.Errorf("can't index item of type %s", .Type())
		}
	}
	return , nil
}

// Slicing.

// slice returns the result of slicing its first argument by the remaining
// arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2], while "slice x"
// is x[:], "slice x 1" is x[1:], and "slice x 1 2 3" is x[1:2:3]. The first
// argument must be a string, slice, or array.
func slice( reflect.Value,  ...reflect.Value) (reflect.Value, error) {
	 = indirectInterface()
	if !.IsValid() {
		return reflect.Value{}, fmt.Errorf("slice of untyped nil")
	}
	if len() > 3 {
		return reflect.Value{}, fmt.Errorf("too many slice indexes: %d", len())
	}
	var  int
	switch .Kind() {
	case reflect.String:
		if len() == 3 {
			return reflect.Value{}, fmt.Errorf("cannot 3-index slice a string")
		}
		 = .Len()
	case reflect.Array, reflect.Slice:
		 = .Cap()
	default:
		return reflect.Value{}, fmt.Errorf("can't slice item of type %s", .Type())
	}
	// set default values for cases item[:], item[i:].
	 := [3]int{0, .Len()}
	for ,  := range  {
		,  := indexArg(, )
		if  != nil {
			return reflect.Value{}, 
		}
		[] = 
	}
	// given item[i:j], make sure i <= j.
	if [0] > [1] {
		return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", [0], [1])
	}
	if len() < 3 {
		return .Slice([0], [1]), nil
	}
	// given item[i:j:k], make sure i <= j <= k.
	if [1] > [2] {
		return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", [1], [2])
	}
	return .Slice3([0], [1], [2]), nil
}

// Length

// length returns the length of the item, with an error if it has no defined length.
func length( reflect.Value) (int, error) {
	,  := indirect()
	if  {
		return 0, fmt.Errorf("len of nil pointer")
	}
	switch .Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
		return .Len(), nil
	}
	return 0, fmt.Errorf("len of type %s", .Type())
}

// Function invocation

// call returns the result of evaluating the first argument as a function.
// The function must return 1 result, or 2 results, the second of which is an error.
func call( reflect.Value,  ...reflect.Value) (reflect.Value, error) {
	 = indirectInterface()
	if !.IsValid() {
		return reflect.Value{}, fmt.Errorf("call of nil")
	}
	 := .Type()
	if .Kind() != reflect.Func {
		return reflect.Value{}, fmt.Errorf("non-function of type %s", )
	}
	if !goodFunc() {
		return reflect.Value{}, fmt.Errorf("function called with %d args; should be 1 or 2", .NumOut())
	}
	 := .NumIn()
	var  reflect.Type
	if .IsVariadic() {
		if len() < -1 {
			return reflect.Value{}, fmt.Errorf("wrong number of args: got %d want at least %d", len(), -1)
		}
		 = .In( - 1).Elem()
	} else {
		if len() !=  {
			return reflect.Value{}, fmt.Errorf("wrong number of args: got %d want %d", len(), )
		}
	}
	 := make([]reflect.Value, len())
	for ,  := range  {
		 = indirectInterface()
		// Compute the expected type. Clumsy because of variadics.
		 := 
		if !.IsVariadic() ||  < -1 {
			 = .In()
		}

		var  error
		if [],  = prepareArg(, );  != nil {
			return reflect.Value{}, fmt.Errorf("arg %d: %w", , )
		}
	}
	return safeCall(, )
}

// safeCall runs fun.Call(args), and returns the resulting value and error, if
// any. If the call panics, the panic value is returned as an error.
func safeCall( reflect.Value,  []reflect.Value) ( reflect.Value,  error) {
	defer func() {
		if  := recover();  != nil {
			if ,  := .(error);  {
				 = 
			} else {
				 = fmt.Errorf("%v", )
			}
		}
	}()
	 := .Call()
	if len() == 2 && ![1].IsNil() {
		return [0], [1].Interface().(error)
	}
	return [0], nil
}

// Boolean logic.

func truth( reflect.Value) bool {
	,  := isTrue(indirectInterface())
	return 
}

// and computes the Boolean AND of its arguments, returning
// the first false argument it encounters, or the last argument.
func and( reflect.Value,  ...reflect.Value) reflect.Value {
	panic("unreachable") // implemented as a special case in evalCall
}

// or computes the Boolean OR of its arguments, returning
// the first true argument it encounters, or the last argument.
func or( reflect.Value,  ...reflect.Value) reflect.Value {
	panic("unreachable") // implemented as a special case in evalCall
}

// not returns the Boolean negation of its argument.
func not( reflect.Value) bool {
	return !truth()
}

// Comparison.

// TODO: Perhaps allow comparison between signed and unsigned integers.

var (
	errBadComparisonType = errors.New("invalid type for comparison")
	errBadComparison     = errors.New("incompatible types for comparison")
	errNoComparison      = errors.New("missing argument for comparison")
)

type kind int

const (
	invalidKind kind = iota
	boolKind
	complexKind
	intKind
	floatKind
	stringKind
	uintKind
)

func basicKind( reflect.Value) (kind, error) {
	switch .Kind() {
	case reflect.Bool:
		return boolKind, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return intKind, nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return uintKind, nil
	case reflect.Float32, reflect.Float64:
		return floatKind, nil
	case reflect.Complex64, reflect.Complex128:
		return complexKind, nil
	case reflect.String:
		return stringKind, nil
	}
	return invalidKind, errBadComparisonType
}

// isNil returns true if v is the zero reflect.Value, or nil of its type.
func isNil( reflect.Value) bool {
	if !.IsValid() {
		return true
	}
	switch .Kind() {
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
		return .IsNil()
	}
	return false
}

// canCompare reports whether v1 and v2 are both the same kind, or one is nil.
// Called only when dealing with nillable types, or there's about to be an error.
func canCompare(,  reflect.Value) bool {
	 := .Kind()
	 := .Kind()
	if  ==  {
		return true
	}
	// We know the type can be compared to nil.
	return  == reflect.Invalid ||  == reflect.Invalid
}

// eq evaluates the comparison a == b || a == c || ...
func eq( reflect.Value,  ...reflect.Value) (bool, error) {
	 = indirectInterface()
	if len() == 0 {
		return false, errNoComparison
	}
	,  := basicKind()
	for ,  := range  {
		 = indirectInterface()
		,  := basicKind()
		 := false
		if  !=  {
			// Special case: Can compare integer values regardless of type's sign.
			switch {
			case  == intKind &&  == uintKind:
				 = .Int() >= 0 && uint64(.Int()) == .Uint()
			case  == uintKind &&  == intKind:
				 = .Int() >= 0 && .Uint() == uint64(.Int())
			default:
				if .IsValid() && .IsValid() {
					return false, errBadComparison
				}
			}
		} else {
			switch  {
			case boolKind:
				 = .Bool() == .Bool()
			case complexKind:
				 = .Complex() == .Complex()
			case floatKind:
				 = .Float() == .Float()
			case intKind:
				 = .Int() == .Int()
			case stringKind:
				 = .String() == .String()
			case uintKind:
				 = .Uint() == .Uint()
			default:
				if !canCompare(, ) {
					return false, fmt.Errorf("non-comparable types %s: %v, %s: %v", , .Type(), .Type(), )
				}
				if isNil() || isNil() {
					 = isNil() == isNil()
				} else {
					if !.Type().Comparable() {
						return false, fmt.Errorf("non-comparable type %s: %v", , .Type())
					}
					 = .Interface() == .Interface()
				}
			}
		}
		if  {
			return true, nil
		}
	}
	return false, nil
}

// ne evaluates the comparison a != b.
func ne(,  reflect.Value) (bool, error) {
	// != is the inverse of ==.
	,  := eq(, )
	return !, 
}

// lt evaluates the comparison a < b.
func lt(,  reflect.Value) (bool, error) {
	 = indirectInterface()
	,  := basicKind()
	if  != nil {
		return false, 
	}
	 = indirectInterface()
	,  := basicKind()
	if  != nil {
		return false, 
	}
	 := false
	if  !=  {
		// Special case: Can compare integer values regardless of type's sign.
		switch {
		case  == intKind &&  == uintKind:
			 = .Int() < 0 || uint64(.Int()) < .Uint()
		case  == uintKind &&  == intKind:
			 = .Int() >= 0 && .Uint() < uint64(.Int())
		default:
			return false, errBadComparison
		}
	} else {
		switch  {
		case boolKind, complexKind:
			return false, errBadComparisonType
		case floatKind:
			 = .Float() < .Float()
		case intKind:
			 = .Int() < .Int()
		case stringKind:
			 = .String() < .String()
		case uintKind:
			 = .Uint() < .Uint()
		default:
			panic("invalid kind")
		}
	}
	return , nil
}

// le evaluates the comparison <= b.
func le(,  reflect.Value) (bool, error) {
	// <= is < or ==.
	,  := lt(, )
	if  ||  != nil {
		return , 
	}
	return eq(, )
}

// gt evaluates the comparison a > b.
func gt(,  reflect.Value) (bool, error) {
	// > is the inverse of <=.
	,  := le(, )
	if  != nil {
		return false, 
	}
	return !, nil
}

// ge evaluates the comparison a >= b.
func ge(,  reflect.Value) (bool, error) {
	// >= is the inverse of <.
	,  := lt(, )
	if  != nil {
		return false, 
	}
	return !, nil
}

// HTML escaping.

var (
	htmlQuot = []byte("&#34;") // shorter than "&quot;"
	htmlApos = []byte("&#39;") // shorter than "&apos;" and apos was not in HTML until HTML5
	htmlAmp  = []byte("&amp;")
	htmlLt   = []byte("&lt;")
	htmlGt   = []byte("&gt;")
	htmlNull = []byte("\uFFFD")
)

// HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
func ( io.Writer,  []byte) {
	 := 0
	for ,  := range  {
		var  []byte
		switch  {
		case '\000':
			 = htmlNull
		case '"':
			 = htmlQuot
		case '\'':
			 = htmlApos
		case '&':
			 = htmlAmp
		case '<':
			 = htmlLt
		case '>':
			 = htmlGt
		default:
			continue
		}
		.Write([:])
		.Write()
		 =  + 1
	}
	.Write([:])
}

// HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
func ( string) string {
	// Avoid allocation if we can.
	if !strings.ContainsAny(, "'\"&<>\000") {
		return 
	}
	var  strings.Builder
	HTMLEscape(&, []byte())
	return .String()
}

// HTMLEscaper returns the escaped HTML equivalent of the textual
// representation of its arguments.
func ( ...any) string {
	return HTMLEscapeString(evalArgs())
}

// JavaScript escaping.

var (
	jsLowUni = []byte(`\u00`)
	hex      = []byte("0123456789ABCDEF")

	jsBackslash = []byte(`\\`)
	jsApos      = []byte(`\'`)
	jsQuot      = []byte(`\"`)
	jsLt        = []byte(`\u003C`)
	jsGt        = []byte(`\u003E`)
	jsAmp       = []byte(`\u0026`)
	jsEq        = []byte(`\u003D`)
)

// JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
func ( io.Writer,  []byte) {
	 := 0
	for  := 0;  < len(); ++ {
		 := []

		if !jsIsSpecial(rune()) {
			// fast path: nothing to do
			continue
		}
		.Write([:])

		if  < utf8.RuneSelf {
			// Quotes, slashes and angle brackets get quoted.
			// Control characters get written as \u00XX.
			switch  {
			case '\\':
				.Write(jsBackslash)
			case '\'':
				.Write(jsApos)
			case '"':
				.Write(jsQuot)
			case '<':
				.Write(jsLt)
			case '>':
				.Write(jsGt)
			case '&':
				.Write(jsAmp)
			case '=':
				.Write(jsEq)
			default:
				.Write(jsLowUni)
				,  := >>4, &0x0f
				.Write(hex[ : +1])
				.Write(hex[ : +1])
			}
		} else {
			// Unicode rune.
			,  := utf8.DecodeRune([:])
			if unicode.IsPrint() {
				.Write([ : +])
			} else {
				fmt.Fprintf(, "\\u%04X", )
			}
			 +=  - 1
		}
		 =  + 1
	}
	.Write([:])
}

// JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
func ( string) string {
	// Avoid allocation if we can.
	if strings.IndexFunc(, jsIsSpecial) < 0 {
		return 
	}
	var  strings.Builder
	JSEscape(&, []byte())
	return .String()
}

func jsIsSpecial( rune) bool {
	switch  {
	case '\\', '\'', '"', '<', '>', '&', '=':
		return true
	}
	return  < ' ' || utf8.RuneSelf <= 
}

// JSEscaper returns the escaped JavaScript equivalent of the textual
// representation of its arguments.
func ( ...any) string {
	return JSEscapeString(evalArgs())
}

// URLQueryEscaper returns the escaped value of the textual representation of
// its arguments in a form suitable for embedding in a URL query.
func ( ...any) string {
	return url.QueryEscape(evalArgs())
}

// evalArgs formats the list of arguments into a string. It is therefore equivalent to
//
//	fmt.Sprint(args...)
//
// except that each argument is indirected (if a pointer), as required,
// using the same rules as the default string evaluation during template
// execution.
func evalArgs( []any) string {
	 := false
	var  string
	// Fast path for simple common case.
	if len() == 1 {
		,  = [0].(string)
	}
	if ! {
		for ,  := range  {
			,  := printableValue(reflect.ValueOf())
			if  {
				[] = 
			} // else let fmt do its thing
		}
		 = fmt.Sprint(...)
	}
	return 
}