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