func.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jet
  15. import (
  16. "fmt"
  17. "reflect"
  18. )
  19. // Arguments holds the arguments passed to jet.Func.
  20. type Arguments struct {
  21. runtime *Runtime
  22. argExpr []Expression
  23. argVal []reflect.Value
  24. }
  25. // Get gets an argument by index.
  26. func (a *Arguments) Get(argumentIndex int) reflect.Value {
  27. if argumentIndex < len(a.argVal) {
  28. return a.argVal[argumentIndex]
  29. }
  30. if argumentIndex < len(a.argVal)+len(a.argExpr) {
  31. return a.runtime.evalPrimaryExpressionGroup(a.argExpr[argumentIndex-len(a.argVal)])
  32. }
  33. return reflect.Value{}
  34. }
  35. // Panicf panics with formatted error message.
  36. func (a *Arguments) Panicf(format string, v ...interface{}) {
  37. panic(fmt.Errorf(format, v...))
  38. }
  39. // RequireNumOfArguments panics if the number of arguments is not in the range specified by min and max.
  40. // In case there is no minimum pass -1, in case there is no maximum pass -1 respectively.
  41. func (a *Arguments) RequireNumOfArguments(funcname string, min, max int) {
  42. num := len(a.argExpr) + len(a.argVal)
  43. if min >= 0 && num < min {
  44. a.Panicf("unexpected number of arguments in a call to %s", funcname)
  45. } else if max >= 0 && num > max {
  46. a.Panicf("unexpected number of arguments in a call to %s", funcname)
  47. }
  48. }
  49. // NumOfArguments returns the number of arguments
  50. func (a *Arguments) NumOfArguments() int {
  51. return len(a.argExpr) + len(a.argVal)
  52. }
  53. // Runtime get the Runtime context
  54. func (a *Arguments) Runtime() *Runtime {
  55. return a.runtime
  56. }
  57. // Func function implementing this type is called directly, which is faster than calling through reflect.
  58. // If a function is being called many times in the execution of a template, you may consider implementing
  59. // a wrapper for that function implementing a Func.
  60. type Func func(Arguments) reflect.Value