github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/text/template/funcs.go (about) 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 stringKind 326 uintKind 327 ) 328 329 func basicKind(v reflect.Value) (kind, error) { 330 switch v.Kind() { 331 case reflect.Bool: 332 return boolKind, nil 333 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 334 return intKind, nil 335 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 336 return uintKind, nil 337 case reflect.Float32, reflect.Float64: 338 return floatKind, nil 339 case reflect.Complex64, reflect.Complex128: 340 return complexKind, nil 341 case reflect.String: 342 return stringKind, nil 343 } 344 return invalidKind, errBadComparisonType 345 } 346 347 // eq evaluates the comparison a == b || a == c || ... 348 func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) { 349 v1 := reflect.ValueOf(arg1) 350 k1, err := basicKind(v1) 351 if err != nil { 352 return false, err 353 } 354 if len(arg2) == 0 { 355 return false, errNoComparison 356 } 357 for _, arg := range arg2 { 358 v2 := reflect.ValueOf(arg) 359 k2, err := basicKind(v2) 360 if err != nil { 361 return false, err 362 } 363 truth := false 364 if k1 != k2 { 365 // Special case: Can compare integer values regardless of type's sign. 366 switch { 367 case k1 == intKind && k2 == uintKind: 368 truth = v1.Int() >= 0 && uint64(v1.Int()) == v2.Uint() 369 case k1 == uintKind && k2 == intKind: 370 truth = v2.Int() >= 0 && v1.Uint() == uint64(v2.Int()) 371 default: 372 return false, errBadComparison 373 } 374 } else { 375 switch k1 { 376 case boolKind: 377 truth = v1.Bool() == v2.Bool() 378 case complexKind: 379 truth = v1.Complex() == v2.Complex() 380 case floatKind: 381 truth = v1.Float() == v2.Float() 382 case intKind: 383 truth = v1.Int() == v2.Int() 384 case stringKind: 385 truth = v1.String() == v2.String() 386 case uintKind: 387 truth = v1.Uint() == v2.Uint() 388 default: 389 panic("invalid kind") 390 } 391 } 392 if truth { 393 return true, nil 394 } 395 } 396 return false, nil 397 } 398 399 // ne evaluates the comparison a != b. 400 func ne(arg1, arg2 interface{}) (bool, error) { 401 // != is the inverse of ==. 402 equal, err := eq(arg1, arg2) 403 return !equal, err 404 } 405 406 // lt evaluates the comparison a < b. 407 func lt(arg1, arg2 interface{}) (bool, error) { 408 v1 := reflect.ValueOf(arg1) 409 k1, err := basicKind(v1) 410 if err != nil { 411 return false, err 412 } 413 v2 := reflect.ValueOf(arg2) 414 k2, err := basicKind(v2) 415 if err != nil { 416 return false, err 417 } 418 truth := false 419 if k1 != k2 { 420 // Special case: Can compare integer values regardless of type's sign. 421 switch { 422 case k1 == intKind && k2 == uintKind: 423 truth = v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() 424 case k1 == uintKind && k2 == intKind: 425 truth = v2.Int() >= 0 && v1.Uint() < uint64(v2.Int()) 426 default: 427 return false, errBadComparison 428 } 429 } else { 430 switch k1 { 431 case boolKind, complexKind: 432 return false, errBadComparisonType 433 case floatKind: 434 truth = v1.Float() < v2.Float() 435 case intKind: 436 truth = v1.Int() < v2.Int() 437 case stringKind: 438 truth = v1.String() < v2.String() 439 case uintKind: 440 truth = v1.Uint() < v2.Uint() 441 default: 442 panic("invalid kind") 443 } 444 } 445 return truth, nil 446 } 447 448 // le evaluates the comparison <= b. 449 func le(arg1, arg2 interface{}) (bool, error) { 450 // <= is < or ==. 451 lessThan, err := lt(arg1, arg2) 452 if lessThan || err != nil { 453 return lessThan, err 454 } 455 return eq(arg1, arg2) 456 } 457 458 // gt evaluates the comparison a > b. 459 func gt(arg1, arg2 interface{}) (bool, error) { 460 // > is the inverse of <=. 461 lessOrEqual, err := le(arg1, arg2) 462 if err != nil { 463 return false, err 464 } 465 return !lessOrEqual, nil 466 } 467 468 // ge evaluates the comparison a >= b. 469 func ge(arg1, arg2 interface{}) (bool, error) { 470 // >= is the inverse of <. 471 lessThan, err := lt(arg1, arg2) 472 if err != nil { 473 return false, err 474 } 475 return !lessThan, nil 476 } 477 478 // HTML escaping. 479 480 var ( 481 htmlQuot = []byte(""") // shorter than """ 482 htmlApos = []byte("'") // shorter than "'" and apos was not in HTML until HTML5 483 htmlAmp = []byte("&") 484 htmlLt = []byte("<") 485 htmlGt = []byte(">") 486 ) 487 488 // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b. 489 func HTMLEscape(w io.Writer, b []byte) { 490 last := 0 491 for i, c := range b { 492 var html []byte 493 switch c { 494 case '"': 495 html = htmlQuot 496 case '\'': 497 html = htmlApos 498 case '&': 499 html = htmlAmp 500 case '<': 501 html = htmlLt 502 case '>': 503 html = htmlGt 504 default: 505 continue 506 } 507 w.Write(b[last:i]) 508 w.Write(html) 509 last = i + 1 510 } 511 w.Write(b[last:]) 512 } 513 514 // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s. 515 func HTMLEscapeString(s string) string { 516 // Avoid allocation if we can. 517 if !strings.ContainsAny(s, `'"&<>`) { 518 return s 519 } 520 var b bytes.Buffer 521 HTMLEscape(&b, []byte(s)) 522 return b.String() 523 } 524 525 // HTMLEscaper returns the escaped HTML equivalent of the textual 526 // representation of its arguments. 527 func HTMLEscaper(args ...interface{}) string { 528 return HTMLEscapeString(evalArgs(args)) 529 } 530 531 // JavaScript escaping. 532 533 var ( 534 jsLowUni = []byte(`\u00`) 535 hex = []byte("0123456789ABCDEF") 536 537 jsBackslash = []byte(`\\`) 538 jsApos = []byte(`\'`) 539 jsQuot = []byte(`\"`) 540 jsLt = []byte(`\x3C`) 541 jsGt = []byte(`\x3E`) 542 ) 543 544 // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b. 545 func JSEscape(w io.Writer, b []byte) { 546 last := 0 547 for i := 0; i < len(b); i++ { 548 c := b[i] 549 550 if !jsIsSpecial(rune(c)) { 551 // fast path: nothing to do 552 continue 553 } 554 w.Write(b[last:i]) 555 556 if c < utf8.RuneSelf { 557 // Quotes, slashes and angle brackets get quoted. 558 // Control characters get written as \u00XX. 559 switch c { 560 case '\\': 561 w.Write(jsBackslash) 562 case '\'': 563 w.Write(jsApos) 564 case '"': 565 w.Write(jsQuot) 566 case '<': 567 w.Write(jsLt) 568 case '>': 569 w.Write(jsGt) 570 default: 571 w.Write(jsLowUni) 572 t, b := c>>4, c&0x0f 573 w.Write(hex[t : t+1]) 574 w.Write(hex[b : b+1]) 575 } 576 } else { 577 // Unicode rune. 578 r, size := utf8.DecodeRune(b[i:]) 579 if unicode.IsPrint(r) { 580 w.Write(b[i : i+size]) 581 } else { 582 fmt.Fprintf(w, "\\u%04X", r) 583 } 584 i += size - 1 585 } 586 last = i + 1 587 } 588 w.Write(b[last:]) 589 } 590 591 // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s. 592 func JSEscapeString(s string) string { 593 // Avoid allocation if we can. 594 if strings.IndexFunc(s, jsIsSpecial) < 0 { 595 return s 596 } 597 var b bytes.Buffer 598 JSEscape(&b, []byte(s)) 599 return b.String() 600 } 601 602 func jsIsSpecial(r rune) bool { 603 switch r { 604 case '\\', '\'', '"', '<', '>': 605 return true 606 } 607 return r < ' ' || utf8.RuneSelf <= r 608 } 609 610 // JSEscaper returns the escaped JavaScript equivalent of the textual 611 // representation of its arguments. 612 func JSEscaper(args ...interface{}) string { 613 return JSEscapeString(evalArgs(args)) 614 } 615 616 // URLQueryEscaper returns the escaped value of the textual representation of 617 // its arguments in a form suitable for embedding in a URL query. 618 func URLQueryEscaper(args ...interface{}) string { 619 return url.QueryEscape(evalArgs(args)) 620 } 621 622 // evalArgs formats the list of arguments into a string. It is therefore equivalent to 623 // fmt.Sprint(args...) 624 // except that each argument is indirected (if a pointer), as required, 625 // using the same rules as the default string evaluation during template 626 // execution. 627 func evalArgs(args []interface{}) string { 628 ok := false 629 var s string 630 // Fast path for simple common case. 631 if len(args) == 1 { 632 s, ok = args[0].(string) 633 } 634 if !ok { 635 for i, arg := range args { 636 a, ok := printableValue(reflect.ValueOf(arg)) 637 if ok { 638 args[i] = a 639 } // else let fmt do its thing 640 } 641 s = fmt.Sprint(args...) 642 } 643 return s 644 }