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