...
Run Format

Source file src/text/template/funcs.go

     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		"bytes"
     9		"errors"
    10		"fmt"
    11		"io"
    12		"net/url"
    13		"reflect"
    14		"strings"
    15		"unicode"
    16		"unicode/utf8"
    17	)
    18	
    19	// FuncMap is the type of the map defining the mapping from names to functions.
    20	// Each function must have either a single return value, or two return values of
    21	// which the second has type error. In that case, if the second (error)
    22	// return value evaluates to non-nil during execution, execution terminates and
    23	// Execute returns that error.
    24	type FuncMap map[string]interface{}
    25	
    26	var builtins = FuncMap{
    27		"and":      and,
    28		"call":     call,
    29		"html":     HTMLEscaper,
    30		"index":    index,
    31		"js":       JSEscaper,
    32		"len":      length,
    33		"not":      not,
    34		"or":       or,
    35		"print":    fmt.Sprint,
    36		"printf":   fmt.Sprintf,
    37		"println":  fmt.Sprintln,
    38		"urlquery": URLQueryEscaper,
    39	
    40		// Comparisons
    41		"eq": eq, // ==
    42		"ge": ge, // >=
    43		"gt": gt, // >
    44		"le": le, // <=
    45		"lt": lt, // <
    46		"ne": ne, // !=
    47	}
    48	
    49	var builtinFuncs = createValueFuncs(builtins)
    50	
    51	// createValueFuncs turns a FuncMap into a map[string]reflect.Value
    52	func createValueFuncs(funcMap FuncMap) map[string]reflect.Value {
    53		m := make(map[string]reflect.Value)
    54		addValueFuncs(m, funcMap)
    55		return m
    56	}
    57	
    58	// addValueFuncs adds to values the functions in funcs, converting them to reflect.Values.
    59	func addValueFuncs(out map[string]reflect.Value, in FuncMap) {
    60		for name, fn := range in {
    61			if !goodName(name) {
    62				panic(fmt.Errorf("function name %s is not a valid identifier", name))
    63			}
    64			v := reflect.ValueOf(fn)
    65			if v.Kind() != reflect.Func {
    66				panic("value for " + name + " not a function")
    67			}
    68			if !goodFunc(v.Type()) {
    69				panic(fmt.Errorf("can't install method/function %q with %d results", name, v.Type().NumOut()))
    70			}
    71			out[name] = v
    72		}
    73	}
    74	
    75	// addFuncs adds to values the functions in funcs. It does no checking of the input -
    76	// call addValueFuncs first.
    77	func addFuncs(out, in FuncMap) {
    78		for name, fn := range in {
    79			out[name] = fn
    80		}
    81	}
    82	
    83	// goodFunc reports whether the function or method has the right result signature.
    84	func goodFunc(typ reflect.Type) bool {
    85		// We allow functions with 1 result or 2 results where the second is an error.
    86		switch {
    87		case typ.NumOut() == 1:
    88			return true
    89		case typ.NumOut() == 2 && typ.Out(1) == errorType:
    90			return true
    91		}
    92		return false
    93	}
    94	
    95	// goodName reports whether the function name is a valid identifier.
    96	func goodName(name string) bool {
    97		if name == "" {
    98			return false
    99		}
   100		for i, r := range name {
   101			switch {
   102			case r == '_':
   103			case i == 0 && !unicode.IsLetter(r):
   104				return false
   105			case !unicode.IsLetter(r) && !unicode.IsDigit(r):
   106				return false
   107			}
   108		}
   109		return true
   110	}
   111	
   112	// findFunction looks for a function in the template, and global map.
   113	func findFunction(name string, tmpl *Template) (reflect.Value, bool) {
   114		if tmpl != nil && tmpl.common != nil {
   115			tmpl.muFuncs.RLock()
   116			defer tmpl.muFuncs.RUnlock()
   117			if fn := tmpl.execFuncs[name]; fn.IsValid() {
   118				return fn, true
   119			}
   120		}
   121		if fn := builtinFuncs[name]; fn.IsValid() {
   122			return fn, true
   123		}
   124		return reflect.Value{}, false
   125	}
   126	
   127	// prepareArg checks if value can be used as an argument of type argType, and
   128	// converts an invalid value to appropriate zero if possible.
   129	func prepareArg(value reflect.Value, argType reflect.Type) (reflect.Value, error) {
   130		if !value.IsValid() {
   131			if !canBeNil(argType) {
   132				return reflect.Value{}, fmt.Errorf("value is nil; should be of type %s", argType)
   133			}
   134			value = reflect.Zero(argType)
   135		}
   136		if !value.Type().AssignableTo(argType) {
   137			return reflect.Value{}, fmt.Errorf("value has type %s; should be %s", value.Type(), argType)
   138		}
   139		return value, nil
   140	}
   141	
   142	// Indexing.
   143	
   144	// index returns the result of indexing its first argument by the following
   145	// arguments.  Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each
   146	// indexed item must be a map, slice, or array.
   147	func index(item interface{}, indices ...interface{}) (interface{}, error) {
   148		v := reflect.ValueOf(item)
   149		if !v.IsValid() {
   150			return nil, fmt.Errorf("index of untyped nil")
   151		}
   152		for _, i := range indices {
   153			index := reflect.ValueOf(i)
   154			var isNil bool
   155			if v, isNil = indirect(v); isNil {
   156				return nil, fmt.Errorf("index of nil pointer")
   157			}
   158			switch v.Kind() {
   159			case reflect.Array, reflect.Slice, reflect.String:
   160				var x int64
   161				switch index.Kind() {
   162				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   163					x = index.Int()
   164				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   165					x = int64(index.Uint())
   166				case reflect.Invalid:
   167					return nil, fmt.Errorf("cannot index slice/array with nil")
   168				default:
   169					return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type())
   170				}
   171				if x < 0 || x >= int64(v.Len()) {
   172					return nil, fmt.Errorf("index out of range: %d", x)
   173				}
   174				v = v.Index(int(x))
   175			case reflect.Map:
   176				index, err := prepareArg(index, v.Type().Key())
   177				if err != nil {
   178					return nil, err
   179				}
   180				if x := v.MapIndex(index); x.IsValid() {
   181					v = x
   182				} else {
   183					v = reflect.Zero(v.Type().Elem())
   184				}
   185			case reflect.Invalid:
   186				// the loop holds invariant: v.IsValid()
   187				panic("unreachable")
   188			default:
   189				return nil, fmt.Errorf("can't index item of type %s", v.Type())
   190			}
   191		}
   192		return v.Interface(), nil
   193	}
   194	
   195	// Length
   196	
   197	// length returns the length of the item, with an error if it has no defined length.
   198	func length(item interface{}) (int, error) {
   199		v := reflect.ValueOf(item)
   200		if !v.IsValid() {
   201			return 0, fmt.Errorf("len of untyped nil")
   202		}
   203		v, isNil := indirect(v)
   204		if isNil {
   205			return 0, fmt.Errorf("len of nil pointer")
   206		}
   207		switch v.Kind() {
   208		case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
   209			return v.Len(), nil
   210		}
   211		return 0, fmt.Errorf("len of type %s", v.Type())
   212	}
   213	
   214	// Function invocation
   215	
   216	// call returns the result of evaluating the first argument as a function.
   217	// The function must return 1 result, or 2 results, the second of which is an error.
   218	func call(fn interface{}, args ...interface{}) (interface{}, error) {
   219		v := reflect.ValueOf(fn)
   220		if !v.IsValid() {
   221			return nil, fmt.Errorf("call of nil")
   222		}
   223		typ := v.Type()
   224		if typ.Kind() != reflect.Func {
   225			return nil, fmt.Errorf("non-function of type %s", typ)
   226		}
   227		if !goodFunc(typ) {
   228			return nil, fmt.Errorf("function called with %d args; should be 1 or 2", typ.NumOut())
   229		}
   230		numIn := typ.NumIn()
   231		var dddType reflect.Type
   232		if typ.IsVariadic() {
   233			if len(args) < numIn-1 {
   234				return nil, fmt.Errorf("wrong number of args: got %d want at least %d", len(args), numIn-1)
   235			}
   236			dddType = typ.In(numIn - 1).Elem()
   237		} else {
   238			if len(args) != numIn {
   239				return nil, fmt.Errorf("wrong number of args: got %d want %d", len(args), numIn)
   240			}
   241		}
   242		argv := make([]reflect.Value, len(args))
   243		for i, arg := range args {
   244			value := reflect.ValueOf(arg)
   245			// Compute the expected type. Clumsy because of variadics.
   246			var argType reflect.Type
   247			if !typ.IsVariadic() || i < numIn-1 {
   248				argType = typ.In(i)
   249			} else {
   250				argType = dddType
   251			}
   252	
   253			var err error
   254			if argv[i], err = prepareArg(value, argType); err != nil {
   255				return nil, fmt.Errorf("arg %d: %s", i, err)
   256			}
   257		}
   258		result := v.Call(argv)
   259		if len(result) == 2 && !result[1].IsNil() {
   260			return result[0].Interface(), result[1].Interface().(error)
   261		}
   262		return result[0].Interface(), nil
   263	}
   264	
   265	// Boolean logic.
   266	
   267	func truth(a interface{}) bool {
   268		t, _ := IsTrue(a)
   269		return t
   270	}
   271	
   272	// and computes the Boolean AND of its arguments, returning
   273	// the first false argument it encounters, or the last argument.
   274	func and(arg0 interface{}, args ...interface{}) interface{} {
   275		if !truth(arg0) {
   276			return arg0
   277		}
   278		for i := range args {
   279			arg0 = args[i]
   280			if !truth(arg0) {
   281				break
   282			}
   283		}
   284		return arg0
   285	}
   286	
   287	// or computes the Boolean OR of its arguments, returning
   288	// the first true argument it encounters, or the last argument.
   289	func or(arg0 interface{}, args ...interface{}) interface{} {
   290		if truth(arg0) {
   291			return arg0
   292		}
   293		for i := range args {
   294			arg0 = args[i]
   295			if truth(arg0) {
   296				break
   297			}
   298		}
   299		return arg0
   300	}
   301	
   302	// not returns the Boolean negation of its argument.
   303	func not(arg interface{}) bool {
   304		return !truth(arg)
   305	}
   306	
   307	// Comparison.
   308	
   309	// TODO: Perhaps allow comparison between signed and unsigned integers.
   310	
   311	var (
   312		errBadComparisonType = errors.New("invalid type for comparison")
   313		errBadComparison     = errors.New("incompatible types for comparison")
   314		errNoComparison      = errors.New("missing argument for comparison")
   315	)
   316	
   317	type kind int
   318	
   319	const (
   320		invalidKind kind = iota
   321		boolKind
   322		complexKind
   323		intKind
   324		floatKind
   325		integerKind
   326		stringKind
   327		uintKind
   328	)
   329	
   330	func basicKind(v reflect.Value) (kind, error) {
   331		switch v.Kind() {
   332		case reflect.Bool:
   333			return boolKind, nil
   334		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   335			return intKind, nil
   336		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   337			return uintKind, nil
   338		case reflect.Float32, reflect.Float64:
   339			return floatKind, nil
   340		case reflect.Complex64, reflect.Complex128:
   341			return complexKind, nil
   342		case reflect.String:
   343			return stringKind, nil
   344		}
   345		return invalidKind, errBadComparisonType
   346	}
   347	
   348	// eq evaluates the comparison a == b || a == c || ...
   349	func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) {
   350		v1 := reflect.ValueOf(arg1)
   351		k1, err := basicKind(v1)
   352		if err != nil {
   353			return false, err
   354		}
   355		if len(arg2) == 0 {
   356			return false, errNoComparison
   357		}
   358		for _, arg := range arg2 {
   359			v2 := reflect.ValueOf(arg)
   360			k2, err := basicKind(v2)
   361			if err != nil {
   362				return false, err
   363			}
   364			truth := false
   365			if k1 != k2 {
   366				// Special case: Can compare integer values regardless of type's sign.
   367				switch {
   368				case k1 == intKind && k2 == uintKind:
   369					truth = v1.Int() >= 0 && uint64(v1.Int()) == v2.Uint()
   370				case k1 == uintKind && k2 == intKind:
   371					truth = v2.Int() >= 0 && v1.Uint() == uint64(v2.Int())
   372				default:
   373					return false, errBadComparison
   374				}
   375			} else {
   376				switch k1 {
   377				case boolKind:
   378					truth = v1.Bool() == v2.Bool()
   379				case complexKind:
   380					truth = v1.Complex() == v2.Complex()
   381				case floatKind:
   382					truth = v1.Float() == v2.Float()
   383				case intKind:
   384					truth = v1.Int() == v2.Int()
   385				case stringKind:
   386					truth = v1.String() == v2.String()
   387				case uintKind:
   388					truth = v1.Uint() == v2.Uint()
   389				default:
   390					panic("invalid kind")
   391				}
   392			}
   393			if truth {
   394				return true, nil
   395			}
   396		}
   397		return false, nil
   398	}
   399	
   400	// ne evaluates the comparison a != b.
   401	func ne(arg1, arg2 interface{}) (bool, error) {
   402		// != is the inverse of ==.
   403		equal, err := eq(arg1, arg2)
   404		return !equal, err
   405	}
   406	
   407	// lt evaluates the comparison a < b.
   408	func lt(arg1, arg2 interface{}) (bool, error) {
   409		v1 := reflect.ValueOf(arg1)
   410		k1, err := basicKind(v1)
   411		if err != nil {
   412			return false, err
   413		}
   414		v2 := reflect.ValueOf(arg2)
   415		k2, err := basicKind(v2)
   416		if err != nil {
   417			return false, err
   418		}
   419		truth := false
   420		if k1 != k2 {
   421			// Special case: Can compare integer values regardless of type's sign.
   422			switch {
   423			case k1 == intKind && k2 == uintKind:
   424				truth = v1.Int() < 0 || uint64(v1.Int()) < v2.Uint()
   425			case k1 == uintKind && k2 == intKind:
   426				truth = v2.Int() >= 0 && v1.Uint() < uint64(v2.Int())
   427			default:
   428				return false, errBadComparison
   429			}
   430		} else {
   431			switch k1 {
   432			case boolKind, complexKind:
   433				return false, errBadComparisonType
   434			case floatKind:
   435				truth = v1.Float() < v2.Float()
   436			case intKind:
   437				truth = v1.Int() < v2.Int()
   438			case stringKind:
   439				truth = v1.String() < v2.String()
   440			case uintKind:
   441				truth = v1.Uint() < v2.Uint()
   442			default:
   443				panic("invalid kind")
   444			}
   445		}
   446		return truth, nil
   447	}
   448	
   449	// le evaluates the comparison <= b.
   450	func le(arg1, arg2 interface{}) (bool, error) {
   451		// <= is < or ==.
   452		lessThan, err := lt(arg1, arg2)
   453		if lessThan || err != nil {
   454			return lessThan, err
   455		}
   456		return eq(arg1, arg2)
   457	}
   458	
   459	// gt evaluates the comparison a > b.
   460	func gt(arg1, arg2 interface{}) (bool, error) {
   461		// > is the inverse of <=.
   462		lessOrEqual, err := le(arg1, arg2)
   463		if err != nil {
   464			return false, err
   465		}
   466		return !lessOrEqual, nil
   467	}
   468	
   469	// ge evaluates the comparison a >= b.
   470	func ge(arg1, arg2 interface{}) (bool, error) {
   471		// >= is the inverse of <.
   472		lessThan, err := lt(arg1, arg2)
   473		if err != nil {
   474			return false, err
   475		}
   476		return !lessThan, nil
   477	}
   478	
   479	// HTML escaping.
   480	
   481	var (
   482		htmlQuot = []byte("&#34;") // shorter than "&quot;"
   483		htmlApos = []byte("&#39;") // shorter than "&apos;" and apos was not in HTML until HTML5
   484		htmlAmp  = []byte("&amp;")
   485		htmlLt   = []byte("&lt;")
   486		htmlGt   = []byte("&gt;")
   487	)
   488	
   489	// HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
   490	func HTMLEscape(w io.Writer, b []byte) {
   491		last := 0
   492		for i, c := range b {
   493			var html []byte
   494			switch c {
   495			case '"':
   496				html = htmlQuot
   497			case '\'':
   498				html = htmlApos
   499			case '&':
   500				html = htmlAmp
   501			case '<':
   502				html = htmlLt
   503			case '>':
   504				html = htmlGt
   505			default:
   506				continue
   507			}
   508			w.Write(b[last:i])
   509			w.Write(html)
   510			last = i + 1
   511		}
   512		w.Write(b[last:])
   513	}
   514	
   515	// HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
   516	func HTMLEscapeString(s string) string {
   517		// Avoid allocation if we can.
   518		if strings.IndexAny(s, `'"&<>`) < 0 {
   519			return s
   520		}
   521		var b bytes.Buffer
   522		HTMLEscape(&b, []byte(s))
   523		return b.String()
   524	}
   525	
   526	// HTMLEscaper returns the escaped HTML equivalent of the textual
   527	// representation of its arguments.
   528	func HTMLEscaper(args ...interface{}) string {
   529		return HTMLEscapeString(evalArgs(args))
   530	}
   531	
   532	// JavaScript escaping.
   533	
   534	var (
   535		jsLowUni = []byte(`\u00`)
   536		hex      = []byte("0123456789ABCDEF")
   537	
   538		jsBackslash = []byte(`\\`)
   539		jsApos      = []byte(`\'`)
   540		jsQuot      = []byte(`\"`)
   541		jsLt        = []byte(`\x3C`)
   542		jsGt        = []byte(`\x3E`)
   543	)
   544	
   545	// JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
   546	func JSEscape(w io.Writer, b []byte) {
   547		last := 0
   548		for i := 0; i < len(b); i++ {
   549			c := b[i]
   550	
   551			if !jsIsSpecial(rune(c)) {
   552				// fast path: nothing to do
   553				continue
   554			}
   555			w.Write(b[last:i])
   556	
   557			if c < utf8.RuneSelf {
   558				// Quotes, slashes and angle brackets get quoted.
   559				// Control characters get written as \u00XX.
   560				switch c {
   561				case '\\':
   562					w.Write(jsBackslash)
   563				case '\'':
   564					w.Write(jsApos)
   565				case '"':
   566					w.Write(jsQuot)
   567				case '<':
   568					w.Write(jsLt)
   569				case '>':
   570					w.Write(jsGt)
   571				default:
   572					w.Write(jsLowUni)
   573					t, b := c>>4, c&0x0f
   574					w.Write(hex[t : t+1])
   575					w.Write(hex[b : b+1])
   576				}
   577			} else {
   578				// Unicode rune.
   579				r, size := utf8.DecodeRune(b[i:])
   580				if unicode.IsPrint(r) {
   581					w.Write(b[i : i+size])
   582				} else {
   583					fmt.Fprintf(w, "\\u%04X", r)
   584				}
   585				i += size - 1
   586			}
   587			last = i + 1
   588		}
   589		w.Write(b[last:])
   590	}
   591	
   592	// JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
   593	func JSEscapeString(s string) string {
   594		// Avoid allocation if we can.
   595		if strings.IndexFunc(s, jsIsSpecial) < 0 {
   596			return s
   597		}
   598		var b bytes.Buffer
   599		JSEscape(&b, []byte(s))
   600		return b.String()
   601	}
   602	
   603	func jsIsSpecial(r rune) bool {
   604		switch r {
   605		case '\\', '\'', '"', '<', '>':
   606			return true
   607		}
   608		return r < ' ' || utf8.RuneSelf <= r
   609	}
   610	
   611	// JSEscaper returns the escaped JavaScript equivalent of the textual
   612	// representation of its arguments.
   613	func JSEscaper(args ...interface{}) string {
   614		return JSEscapeString(evalArgs(args))
   615	}
   616	
   617	// URLQueryEscaper returns the escaped value of the textual representation of
   618	// its arguments in a form suitable for embedding in a URL query.
   619	func URLQueryEscaper(args ...interface{}) string {
   620		return url.QueryEscape(evalArgs(args))
   621	}
   622	
   623	// evalArgs formats the list of arguments into a string. It is therefore equivalent to
   624	//	fmt.Sprint(args...)
   625	// except that each argument is indirected (if a pointer), as required,
   626	// using the same rules as the default string evaluation during template
   627	// execution.
   628	func evalArgs(args []interface{}) string {
   629		ok := false
   630		var s string
   631		// Fast path for simple common case.
   632		if len(args) == 1 {
   633			s, ok = args[0].(string)
   634		}
   635		if !ok {
   636			for i, arg := range args {
   637				a, ok := printableValue(reflect.ValueOf(arg))
   638				if ok {
   639					args[i] = a
   640				} // else let fmt do its thing
   641			}
   642			s = fmt.Sprint(args...)
   643		}
   644		return s
   645	}
   646	

View as plain text