Debian Codegraph @

tpl/internal/go_templates/texttemplate/hugo_template.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package template
15
16 import (
17 "context"
18 "fmt"
19 "io"
20 "iter"
21 "reflect"
22
23 "github.com/gohugoio/hugo/common/herrors"
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/hreflect"
26
27 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
28 )
29
30 /*
31
32 This files contains the Hugo related addons. All the other files in this
33 package is auto generated.
34
35 */
36
37 // Export it so we can populate Hugo's func map with it, which makes it faster.
38 var GoFuncs = builtinFuncs()
39
40 // Preparer prepares the template before execution.
41 type Preparer interface {
42 Prepare() (*Template, error)
43 }
44
45 // ExecHelper allows some custom eval hooks.
46 type ExecHelper interface {
47 Init(ctx context.Context, tmpl Preparer)
48 GetFunc(ctx context.Context, tmpl Preparer, name string) (reflect.Value, reflect.Value, bool)
49 GetMethod(ctx context.Context, tmpl Preparer, receiver reflect.Value, name string) (method reflect.Value, firstArg reflect.Value)
50 GetMapValue(ctx context.Context, tmpl Preparer, receiver, key reflect.Value) (reflect.Value, bool)
51 OnCalled(ctx context.Context, tmpl Preparer, name string, args []reflect.Value, result reflect.Value)
52 }
53
54 // Executer executes a given template.
55 type Executer interface {
56 ExecuteWithContext(ctx context.Context, p Preparer, wr io.Writer, data any) error
57 }
58
59 type executer struct {
60 helper ExecHelper
61 }
62
63 func NewExecuter(helper ExecHelper) Executer {
64 return &executer{helper: helper}
65 }
66
67 // Note: The context is currently not fully implemented in Hugo. This is a work in progress.
68 func (t *executer) ExecuteWithContext(ctx context.Context, p Preparer, wr io.Writer, data any) error {
69 if ctx == nil {
70 panic("nil context")
71 }
72
73 tmpl, err := p.Prepare()
74 if err != nil {
75 return err
76 }
77
78 value, ok := data.(reflect.Value)
79 if !ok {
80 value = reflect.ValueOf(data)
81 }
82
83 state := &state{
84 ctx: ctx,
85 helper: t.helper,
86 prep: p,
87 tmpl: tmpl,
88 wr: wr,
89 vars: []variable{{"$", value}},
90 }
91
92 t.helper.Init(ctx, p)
93
94 return tmpl.executeWithState(state, value)
95 }
96
97 // Prepare returns a template ready for execution.
98 func (t *Template) Prepare() (*Template, error) {
99 return t, nil
100 }
101
102 // ReturnError is the sentinel used by the return keyword
103 // to signal an early exit from a template.
104 // A bare {{ return }} is trapped at the nearest template boundary,
105 // a {{ return <value> }} must be trapped by a partial invocation.
106 type ReturnError struct {
107 Value any
108 HasValue bool
109 }
110
111 func (r *ReturnError) Error() string {
112 return "return with a value is only supported in partials"
113 }
114
115 func (t *Template) executeWithState(state *state, value reflect.Value) (err error) {
116 defer errRecover(&err)
117 // Added for Hugo. Trap the return sentinel.
118 defer func() {
119 if r := recover(); r != nil {
120 if rerr, ok := r.(*ReturnError); ok {
121 if rerr.HasValue {
122 err = rerr
123 }
124 return
125 }
126 panic(r)
127 }
128 }()
129 if t.Tree == nil || t.Root == nil {
130 state.errorf("%q is an incomplete or empty template", t.Name())
131 }
132 state.walk(value, t.Root)
133 return
134 }
135
136 // Below are modified structs etc. The changes are marked with "Added for Hugo."
137
138 // state represents the state of an execution. It's not part of the
139 // template so that multiple executions of the same template
140 // can execute in parallel.
141 type state struct {
142 tmpl *Template
143 ctx context.Context // Added for Hugo. The original data context.
144 prep Preparer // Added for Hugo.
145 helper ExecHelper // Added for Hugo.
146 wr io.Writer
147 node parse.Node // current node, for errors
148 vars []variable // push-down stack of variable values.
149 depth int // the height of the stack of executing templates.
150 }
151
152 // newReturnError evaluates any return value and creates the return sentinel.
153 // Everything after the return keyword is evaluated as a command,
154 // so both {{ return $v }} and {{ return add . 42 }} work.
155 func (s *state) newReturnError(dot reflect.Value, cmd parse.Node, args []parse.Node, final reflect.Value) *ReturnError {
156 rerr := &ReturnError{}
157
158 toValue := func(v reflect.Value) any {
159 if v.IsValid() && v.Type() == reflectValueType {
160 v = v.Interface().(reflect.Value)
161 }
162 if !v.IsValid() {
163 return nil
164 }
165 return v.Interface()
166 }
167
168 switch {
169 case len(args) > 1:
170 rerr.HasValue = true
171 if _, ok := args[1].(*parse.NilNode); ok && len(args) == 2 && isMissing(final) {
172 // {{ return nil }}
173 break
174 }
175 c := *(cmd.(*parse.CommandNode))
176 c.Args = args[1:]
177 rerr.Value = toValue(s.evalCommand(dot, &c, final))
178 case !isMissing(final):
179 rerr.HasValue = true
180 rerr.Value = toValue(final)
181 }
182
183 return rerr
184 }
185
186 // walkTemplate traps any bare return so it only ends the execution of the
187 // included template.
188 func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
189 defer func() {
190 if r := recover(); r != nil {
191 if rerr, ok := r.(*ReturnError); ok && !rerr.HasValue {
192 return
193 }
194 panic(r)
195 }
196 }()
197 s.walkTemplateOld(dot, t)
198 }
199
200 func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
201 s.at(node)
202 name := node.Ident
203
204 // Added for Hugo.
205 if name == "return" {
206 panic(s.newReturnError(dot, cmd, args, final))
207 }
208
209 var function reflect.Value
210 // Added for Hugo.
211 var first reflect.Value
212 var ok bool
213 var isBuiltin bool
214 if s.helper != nil {
215 isBuiltin = name == "and" || name == "or"
216 function, first, ok = s.helper.GetFunc(s.ctx, s.prep, name)
217 }
218
219 if !ok {
220 function, isBuiltin, ok = findFunction(name, s.tmpl)
221 }
222
223 if !ok {
224 s.errorf("%q is not a defined function", name)
225 }
226 if first != zero {
227 return s.evalCall(dot, function, isBuiltin, cmd, name, args, final, first)
228 }
229 return s.evalCall(dot, function, isBuiltin, cmd, name, args, final)
230 }
231
232 // evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
233 // The 'final' argument represents the return value from the preceding
234 // value of the pipeline, if any.
235 func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
236 if !receiver.IsValid() {
237 if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key.
238 s.errorf("nil data; no entry for key %q", fieldName)
239 }
240 return zero
241 }
242 typ := receiver.Type()
243 receiver, isNil := indirect(receiver)
244 if receiver.Kind() == reflect.Interface && isNil {
245 // Calling a method on a nil interface can't work. The
246 // MethodByName method call below would panic.
247 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
248 return zero
249 }
250
251 // Unless it's an interface, need to get to a value of type *T to guarantee
252 // we see all methods of T and *T.
253 ptr := receiver
254 if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Pointer && ptr.CanAddr() {
255 ptr = ptr.Addr()
256 }
257
258 // Added for Hugo.
259 var first reflect.Value
260 var method reflect.Value
261 if s.helper != nil {
262 method, first = s.helper.GetMethod(s.ctx, s.prep, ptr, fieldName)
263 } else {
264 method = ptr.MethodByName(fieldName)
265 }
266
267 if method.IsValid() {
268 if first != zero {
269 return s.evalCall(dot, method, false, node, fieldName, args, final, first)
270 }
271
272 return s.evalCall(dot, method, false, node, fieldName, args, final)
273 }
274
275 if method := ptr.MethodByName(fieldName); method.IsValid() {
276 return s.evalCall(dot, method, false, node, fieldName, args, final)
277 }
278 hasArgs := len(args) > 1 || final != missingVal
279 // It's not a method; must be a field of a struct or an element of a map.
280 switch receiver.Kind() {
281 case reflect.Struct:
282 tField, ok := receiver.Type().FieldByName(fieldName)
283 if ok {
284 field, err := receiver.FieldByIndexErr(tField.Index)
285 if !tField.IsExported() {
286 s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
287 }
288 if err != nil {
289 s.errorf("%v", err)
290 }
291 // If it's a function, we must call it.
292 if hasArgs {
293 s.errorf("%s has arguments but cannot be invoked as function", fieldName)
294 }
295 return field
296 }
297 case reflect.Map:
298 // If it's a map, attempt to use the field name as a key.
299 nameVal := reflect.ValueOf(fieldName)
300 if nameVal.Type().AssignableTo(receiver.Type().Key()) {
301 if hasArgs {
302 s.errorf("%s is not a method but has arguments", fieldName)
303 }
304 var result reflect.Value
305 if s.helper != nil {
306 // Added for Hugo.
307 result, _ = s.helper.GetMapValue(s.ctx, s.prep, receiver, nameVal)
308 } else {
309 result = receiver.MapIndex(nameVal)
310 }
311 if !result.IsValid() {
312 switch s.tmpl.option.missingKey {
313 case mapInvalid:
314 // Just use the invalid value.
315 case mapZeroValue:
316 result = reflect.Zero(receiver.Type().Elem())
317 case mapError:
318 s.errorf("map has no entry for key %q", fieldName)
319 }
320 }
321 return result
322 }
323 case reflect.Pointer:
324 etyp := receiver.Type().Elem()
325 if etyp.Kind() == reflect.Struct {
326 if _, ok := etyp.FieldByName(fieldName); !ok {
327 // If there's no such field, say "can't evaluate"
328 // instead of "nil pointer evaluating".
329 break
330 }
331 }
332 if isNil {
333 s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
334 }
335 }
336 s.errorf("can't evaluate field %s in type %s", fieldName, typ)
337 panic("not reached")
338 }
339
340 // newErrorWithCause creates a new error with the given cause.
341 func newErrorWithCause(err error) *TryError {
342 return &TryError{Err: err, Cause: herrors.Cause(err)}
343 }
344
345 // TryError wraps an error with a cause.
346 type TryError struct {
347 Err error
348 Cause error
349 }
350
351 func (e *TryError) Error() string {
352 return e.Err.Error()
353 }
354
355 func (e *TryError) Unwrap() error {
356 return e.Err
357 }
358
359 // TryValue is what gets returned when using the "try" keyword.
360 type TryValue struct {
361 // Value is the value returned by the function or method wrapped with "try".
362 // This will always be nil if Err is set.
363 Value any
364
365 // Err is the error returned by the function or method wrapped with "try".
366 // This will always be nil if Value is set.
367 Err *TryError
368 }
369
370 // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
371 // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
372 // as the function itself.
373 func (s *state) evalCall(dot, fun reflect.Value, isBuiltin bool, node parse.Node, name string, args []parse.Node, final reflect.Value, first ...reflect.Value) (val reflect.Value) {
374 // Added for Hugo.
375 if name == "try" {
376 defer func() {
377 if r := recover(); r != nil {
378 if _, ok := r.(*ReturnError); ok {
379 panic(r)
380 }
381 // Cause: herrors.Cause(err)
382 if err, ok := r.(error); ok {
383 val = reflect.ValueOf(TryValue{Value: nil, Err: newErrorWithCause(err)})
384 } else {
385 val = reflect.ValueOf(TryValue{Value: nil, Err: newErrorWithCause(fmt.Errorf("%v", r))})
386 }
387 }
388 }()
389 }
390
391 if args != nil {
392 args = args[1:] // Zeroth arg is function name/node; not passed to function.
393 }
394 typ := fun.Type()
395 numFirst := len(first) // Added for Hugo
396 numIn := len(args) + numFirst // Added for Hugo
397 if !isMissing(final) {
398 numIn++
399 }
400 numFixed := len(args) + len(first) // Adjusted for Hugo
401 if typ.IsVariadic() {
402 numFixed = typ.NumIn() - 1 // last arg is the variadic one.
403 if numIn < numFixed {
404 s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
405 }
406 } else if numIn != typ.NumIn() {
407 s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn)
408 }
409 if err := goodFunc(name, typ); err != nil {
410 s.errorf("%v", err)
411 }
412
413 unwrap := func(v reflect.Value) reflect.Value {
414 if v.Type() == reflectValueType {
415 v = v.Interface().(reflect.Value)
416 }
417 return v
418 }
419
420 // Special case for builtin and/or, which short-circuit.
421 if isBuiltin && (name == "and" || name == "or") {
422 argType := typ.In(0)
423 var v reflect.Value
424 for _, arg := range args {
425 v = s.evalArg(dot, argType, arg).Interface().(reflect.Value)
426 if truth(v) == (name == "or") {
427 // This value was already unwrapped
428 // by the .Interface().(reflect.Value).
429 return v
430 }
431 }
432 if !final.Equal(missingVal) {
433 // The last argument to and/or is coming from
434 // the pipeline. We didn't short circuit on an earlier
435 // argument, so we are going to return this one.
436 // We don't have to evaluate final, but we do
437 // have to check its type. Then, since we are
438 // going to return it, we have to unwrap it.
439 v = unwrap(s.validateType(final, argType))
440 }
441 return v
442 }
443
444 // Build the arg list.
445 argv := make([]reflect.Value, numIn)
446 // Args must be evaluated. Fixed args first.
447 i := len(first) // Adjusted for Hugo.
448 for ; i < numFixed && i < len(args)+numFirst; i++ { // Adjusted for Hugo.
449 argv[i] = s.evalArg(dot, typ.In(i), args[i-numFirst]) // Adjusted for Hugo.
450 }
451 // Now the ... args.
452 if typ.IsVariadic() {
453 argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
454 for ; i < len(args)+numFirst; i++ { // Adjusted for Hugo.
455 argv[i] = s.evalArg(dot, argType, args[i-numFirst]) // Adjusted for Hugo.
456 }
457 }
458 // Add final value if necessary.
459 if !isMissing(final) {
460 t := typ.In(typ.NumIn() - 1)
461 if typ.IsVariadic() {
462 if numIn-1 < numFixed {
463 // The added final argument corresponds to a fixed parameter of the function.
464 // Validate against the type of the actual parameter.
465 t = typ.In(numIn - 1)
466 } else {
467 // The added final argument corresponds to the variadic part.
468 // Validate against the type of the elements of the variadic slice.
469 t = t.Elem()
470 }
471 }
472 argv[i] = s.validateType(final, t)
473 }
474
475 // Special case for the "call" builtin.
476 // Insert the name of the callee function as the first argument.
477 if isBuiltin && name == "call" {
478 var calleeName string
479 if len(args) == 0 {
480 // final must be present or we would have errored out above.
481 calleeName = final.String()
482 } else {
483 calleeName = args[0].String()
484 }
485 argv = append([]reflect.Value{reflect.ValueOf(calleeName)}, argv...)
486 fun = reflect.ValueOf(call)
487 }
488
489 // Added for Hugo
490 for i := range first {
491 argv[i] = s.validateType(first[i], typ.In(i))
492 }
493
494 v, err := safeCall(fun, argv)
495 // If we have an error that is not nil, stop execution and return that
496 // error to the caller.
497 if err != nil {
498 s.at(node)
499 s.errorf("error calling %s: %w", name, err)
500 }
501 vv := unwrap(v)
502
503 // Added for Hugo
504 if s.helper != nil {
505 s.helper.OnCalled(s.ctx, s.prep, name, argv, vv)
506 }
507
508 // Added for Hugo.
509 if name == "try" {
510 return reflect.ValueOf(TryValue{Value: vv.Interface()})
511 }
512
513 return vv
514 }
515
516 // validateType guarantees that the value is valid and assignable to the type.
517 func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
518 if !value.IsValid() {
519 if typ == nil {
520 // An untyped nil interface{}. Accept as a proper nil value.
521 return reflect.ValueOf(nil)
522 }
523 if canBeNil(typ) {
524 // Like above, but use the zero value of the non-nil type.
525 return reflect.Zero(typ)
526 }
527 s.errorf("invalid value; expected %s", typ)
528 }
529 if typ == reflectValueType && value.Type() != typ {
530 return reflect.ValueOf(value)
531 }
532 if typ != nil && !value.Type().AssignableTo(typ) {
533 if value.Kind() == reflect.Interface && !value.IsNil() {
534 value = value.Elem()
535 if value.Type().AssignableTo(typ) {
536 return value
537 }
538 // fallthrough
539 }
540 // Does one dereference or indirection work? We could do more, as we
541 // do with method receivers, but that gets messy and method receivers
542 // are much more constrained, so it makes more sense there than here.
543 // Besides, one is almost always all you need.
544 switch {
545 case value.Kind() == reflect.Pointer && value.Type().Elem().AssignableTo(typ):
546 value = value.Elem()
547 if !value.IsValid() {
548 s.errorf("dereference of nil pointer of type %s", typ)
549 }
550 case reflect.PointerTo(value.Type()).AssignableTo(typ) && value.CanAddr():
551 value = value.Addr()
552 default:
553 // Added for Hugo.
554 if v, ok := hreflect.ConvertIfPossible(value, typ); ok {
555 value = v
556 } else {
557 s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
558 }
559
560 }
561 }
562 return value
563 }
564
565 func isTrue(val reflect.Value) (truth, ok bool) {
566 return hreflect.IsTruthfulValue(val), true
567 }
568
569 func (t *Template) All() iter.Seq[*Template] {
570 return func(yield func(t *Template) bool) {
571 if t.common == nil {
572 return
573 }
574 t.muTmpl.RLock()
575 defer t.muTmpl.RUnlock()
576 for _, v := range t.tmpl {
577 if !yield(v) {
578 return
579 }
580 }
581 }
582 }
583
584 var (
585 anyType = reflect.TypeFor[any]()
586 funcVariadicAnyString = reflect.TypeFor[func(...any) string]()
587 funcString = reflect.TypeFor[func() string]()
588 funcCtxVariadicAnyAnyErr = reflect.TypeFor[func(context.Context, ...any) (any, error)]()
589 funcAnyVariadicAnyBool = reflect.TypeFor[func(any, ...any) bool]()
590 funcParams = reflect.TypeFor[func() hmaps.Params]()
591 funcAnyAnyBoolErr = reflect.TypeFor[func(any, any) (bool, error)]()
592 funcAnyStringErr = reflect.TypeFor[func(any) (string, error)]()
593 funcCtxStringVariadicAny = reflect.TypeFor[func(context.Context, string, ...any) (any, error)]()
594 funcReflectValueBool = reflect.TypeFor[func(reflect.Value) bool]()
595 funcMap = reflect.TypeFor[func() map[string]any]()
596 funcVariadicAnyMapErr = reflect.TypeFor[func(...any) (map[string]any, error)]()
597 funcAny = reflect.TypeFor[func() any]()
598 funcBool = reflect.TypeFor[func() bool]()
599 funcStringVariadicAny = reflect.TypeFor[func(string, ...any) string]()
600 funcAnyVariadicAnyAnyErr = reflect.TypeFor[func(any, ...any) (any, error)]()
601 )
602
603 // safeCall runs fun with args and returns the result and error, if any.
604 // If the call panics, the panic value is returned as an error.
605 // This replaces the upstream safeCall and calls the most common function
606 // signatures directly, avoiding the allocations in reflect.Value.Call.
607 // See issue 15385.
608 func safeCall(fun reflect.Value, args []reflect.Value) (val reflect.Value, err error) {
609 defer func() {
610 if r := recover(); r != nil {
611 if e, ok := r.(error); ok {
612 err = e
613 } else {
614 err = fmt.Errorf("%v", r)
615 }
616 }
617 }()
618
619 switch fun.Type() {
620 case funcVariadicAnyString:
621 f, _ := reflect.TypeAssert[func(...any) string](fun)
622 return reflect.ValueOf(f(anyArgs(args)...)), nil
623 case funcString:
624 f, _ := reflect.TypeAssert[func() string](fun)
625 return reflect.ValueOf(f()), nil
626 case funcCtxVariadicAnyAnyErr:
627 f, _ := reflect.TypeAssert[func(context.Context, ...any) (any, error)](fun)
628 ctx, _ := args[0].Interface().(context.Context)
629 v, err := f(ctx, anyArgs(args[1:])...)
630 return anyValue(v), err
631 case funcAnyVariadicAnyBool:
632 f, _ := reflect.TypeAssert[func(any, ...any) bool](fun)
633 return reflect.ValueOf(f(args[0].Interface(), anyArgs(args[1:])...)), nil
634 case funcParams:
635 f, _ := reflect.TypeAssert[func() hmaps.Params](fun)
636 return reflect.ValueOf(f()), nil
637 case funcAnyAnyBoolErr:
638 f, _ := reflect.TypeAssert[func(any, any) (bool, error)](fun)
639 v, err := f(args[0].Interface(), args[1].Interface())
640 return reflect.ValueOf(v), err
641 case funcAnyStringErr:
642 f, _ := reflect.TypeAssert[func(any) (string, error)](fun)
643 v, err := f(args[0].Interface())
644 return reflect.ValueOf(v), err
645 case funcCtxStringVariadicAny:
646 f, _ := reflect.TypeAssert[func(context.Context, string, ...any) (any, error)](fun)
647 ctx, _ := args[0].Interface().(context.Context)
648 v, err := f(ctx, args[1].String(), anyArgs(args[2:])...)
649 return anyValue(v), err
650 case funcReflectValueBool:
651 f, _ := reflect.TypeAssert[func(reflect.Value) bool](fun)
652 v, _ := reflect.TypeAssert[reflect.Value](args[0])
653 return reflect.ValueOf(f(v)), nil
654 case funcMap:
655 f, _ := reflect.TypeAssert[func() map[string]any](fun)
656 return reflect.ValueOf(f()), nil
657 case funcVariadicAnyMapErr:
658 f, _ := reflect.TypeAssert[func(...any) (map[string]any, error)](fun)
659 v, err := f(anyArgs(args)...)
660 return reflect.ValueOf(v), err
661 case funcAny:
662 f, _ := reflect.TypeAssert[func() any](fun)
663 return anyValue(f()), nil
664 case funcBool:
665 f, _ := reflect.TypeAssert[func() bool](fun)
666 return reflect.ValueOf(f()), nil
667 case funcStringVariadicAny:
668 f, _ := reflect.TypeAssert[func(string, ...any) string](fun)
669 return reflect.ValueOf(f(args[0].String(), anyArgs(args[1:])...)), nil
670 case funcAnyVariadicAnyAnyErr:
671 f, _ := reflect.TypeAssert[func(any, ...any) (any, error)](fun)
672 v, err := f(args[0].Interface(), anyArgs(args[1:])...)
673 return anyValue(v), err
674 }
675
676 ret := fun.Call(args)
677 if len(ret) == 2 && !ret[1].IsNil() {
678 return ret[0], ret[1].Interface().(error)
679 }
680 return ret[0], nil
681 }
682
683 func anyArgs(args []reflect.Value) []any {
684 s := make([]any, len(args))
685 for i, arg := range args {
686 s[i] = arg.Interface()
687 }
688 return s
689 }
690
691 // anyValue returns a valid reflect.Value also for nil, matching what
692 // reflect.Value.Call returns for an any result.
693 func anyValue(v any) reflect.Value {
694 if v == nil {
695 return reflect.Zero(anyType)
696 }
697 return reflect.ValueOf(v)
698 }