| 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 |
func (t *Template) executeWithState(state *state, value reflect.Value) (err error) { |
| 102 |
defer errRecover(&err) |
| 103 |
if t.Tree == nil || t.Root == nil { |
| 104 |
state.errorf("%q is an incomplete or empty template", t.Name()) |
| 105 |
} |
| 106 |
state.walk(value, t.Root) |
| 107 |
return |
| 108 |
} |
| 109 |
|
| 110 |
// Below are modified structs etc. The changes are marked with "Added for Hugo." |
| 111 |
|
| 112 |
// state represents the state of an execution. It's not part of the |
| 113 |
// template so that multiple executions of the same template |
| 114 |
// can execute in parallel. |
| 115 |
type state struct { |
| 116 |
tmpl *Template |
| 117 |
ctx context.Context // Added for Hugo. The original data context. |
| 118 |
prep Preparer // Added for Hugo. |
| 119 |
helper ExecHelper // Added for Hugo. |
| 120 |
wr io.Writer |
| 121 |
node parse.Node // current node, for errors |
| 122 |
vars []variable // push-down stack of variable values. |
| 123 |
depth int // the height of the stack of executing templates. |
| 124 |
} |
| 125 |
|
| 126 |
func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value { |
| 127 |
s.at(node) |
| 128 |
name := node.Ident |
| 129 |
|
| 130 |
var function reflect.Value |
| 131 |
// Added for Hugo. |
| 132 |
var first reflect.Value |
| 133 |
var ok bool |
| 134 |
var isBuiltin bool |
| 135 |
if s.helper != nil { |
| 136 |
isBuiltin = name == "and" || name == "or" |
| 137 |
function, first, ok = s.helper.GetFunc(s.ctx, s.prep, name) |
| 138 |
} |
| 139 |
|
| 140 |
if !ok { |
| 141 |
function, isBuiltin, ok = findFunction(name, s.tmpl) |
| 142 |
} |
| 143 |
|
| 144 |
if !ok { |
| 145 |
s.errorf("%q is not a defined function", name) |
| 146 |
} |
| 147 |
if first != zero { |
| 148 |
return s.evalCall(dot, function, isBuiltin, cmd, name, args, final, first) |
| 149 |
} |
| 150 |
return s.evalCall(dot, function, isBuiltin, cmd, name, args, final) |
| 151 |
} |
| 152 |
|
| 153 |
// evalField evaluates an expression like (.Field) or (.Field arg1 arg2). |
| 154 |
// The 'final' argument represents the return value from the preceding |
| 155 |
// value of the pipeline, if any. |
| 156 |
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value { |
| 157 |
if !receiver.IsValid() { |
| 158 |
if s.tmpl.option.missingKey == mapError { // Treat invalid value as missing map key. |
| 159 |
s.errorf("nil data; no entry for key %q", fieldName) |
| 160 |
} |
| 161 |
return zero |
| 162 |
} |
| 163 |
typ := receiver.Type() |
| 164 |
receiver, isNil := indirect(receiver) |
| 165 |
if receiver.Kind() == reflect.Interface && isNil { |
| 166 |
// Calling a method on a nil interface can't work. The |
| 167 |
// MethodByName method call below would panic. |
| 168 |
s.errorf("nil pointer evaluating %s.%s", typ, fieldName) |
| 169 |
return zero |
| 170 |
} |
| 171 |
|
| 172 |
// Unless it's an interface, need to get to a value of type *T to guarantee |
| 173 |
// we see all methods of T and *T. |
| 174 |
ptr := receiver |
| 175 |
if ptr.Kind() != reflect.Interface && ptr.Kind() != reflect.Pointer && ptr.CanAddr() { |
| 176 |
ptr = ptr.Addr() |
| 177 |
} |
| 178 |
|
| 179 |
// Added for Hugo. |
| 180 |
var first reflect.Value |
| 181 |
var method reflect.Value |
| 182 |
if s.helper != nil { |
| 183 |
method, first = s.helper.GetMethod(s.ctx, s.prep, ptr, fieldName) |
| 184 |
} else { |
| 185 |
method = ptr.MethodByName(fieldName) |
| 186 |
} |
| 187 |
|
| 188 |
if method.IsValid() { |
| 189 |
if first != zero { |
| 190 |
return s.evalCall(dot, method, false, node, fieldName, args, final, first) |
| 191 |
} |
| 192 |
|
| 193 |
return s.evalCall(dot, method, false, node, fieldName, args, final) |
| 194 |
} |
| 195 |
|
| 196 |
if method := ptr.MethodByName(fieldName); method.IsValid() { |
| 197 |
return s.evalCall(dot, method, false, node, fieldName, args, final) |
| 198 |
} |
| 199 |
hasArgs := len(args) > 1 || final != missingVal |
| 200 |
// It's not a method; must be a field of a struct or an element of a map. |
| 201 |
switch receiver.Kind() { |
| 202 |
case reflect.Struct: |
| 203 |
tField, ok := receiver.Type().FieldByName(fieldName) |
| 204 |
if ok { |
| 205 |
field, err := receiver.FieldByIndexErr(tField.Index) |
| 206 |
if !tField.IsExported() { |
| 207 |
s.errorf("%s is an unexported field of struct type %s", fieldName, typ) |
| 208 |
} |
| 209 |
if err != nil { |
| 210 |
s.errorf("%v", err) |
| 211 |
} |
| 212 |
// If it's a function, we must call it. |
| 213 |
if hasArgs { |
| 214 |
s.errorf("%s has arguments but cannot be invoked as function", fieldName) |
| 215 |
} |
| 216 |
return field |
| 217 |
} |
| 218 |
case reflect.Map: |
| 219 |
// If it's a map, attempt to use the field name as a key. |
| 220 |
nameVal := reflect.ValueOf(fieldName) |
| 221 |
if nameVal.Type().AssignableTo(receiver.Type().Key()) { |
| 222 |
if hasArgs { |
| 223 |
s.errorf("%s is not a method but has arguments", fieldName) |
| 224 |
} |
| 225 |
var result reflect.Value |
| 226 |
if s.helper != nil { |
| 227 |
// Added for Hugo. |
| 228 |
result, _ = s.helper.GetMapValue(s.ctx, s.prep, receiver, nameVal) |
| 229 |
} else { |
| 230 |
result = receiver.MapIndex(nameVal) |
| 231 |
} |
| 232 |
if !result.IsValid() { |
| 233 |
switch s.tmpl.option.missingKey { |
| 234 |
case mapInvalid: |
| 235 |
// Just use the invalid value. |
| 236 |
case mapZeroValue: |
| 237 |
result = reflect.Zero(receiver.Type().Elem()) |
| 238 |
case mapError: |
| 239 |
s.errorf("map has no entry for key %q", fieldName) |
| 240 |
} |
| 241 |
} |
| 242 |
return result |
| 243 |
} |
| 244 |
case reflect.Pointer: |
| 245 |
etyp := receiver.Type().Elem() |
| 246 |
if etyp.Kind() == reflect.Struct { |
| 247 |
if _, ok := etyp.FieldByName(fieldName); !ok { |
| 248 |
// If there's no such field, say "can't evaluate" |
| 249 |
// instead of "nil pointer evaluating". |
| 250 |
break |
| 251 |
} |
| 252 |
} |
| 253 |
if isNil { |
| 254 |
s.errorf("nil pointer evaluating %s.%s", typ, fieldName) |
| 255 |
} |
| 256 |
} |
| 257 |
s.errorf("can't evaluate field %s in type %s", fieldName, typ) |
| 258 |
panic("not reached") |
| 259 |
} |
| 260 |
|
| 261 |
// newErrorWithCause creates a new error with the given cause. |
| 262 |
func newErrorWithCause(err error) *TryError { |
| 263 |
return &TryError{Err: err, Cause: herrors.Cause(err)} |
| 264 |
} |
| 265 |
|
| 266 |
// TryError wraps an error with a cause. |
| 267 |
type TryError struct { |
| 268 |
Err error |
| 269 |
Cause error |
| 270 |
} |
| 271 |
|
| 272 |
func (e *TryError) Error() string { |
| 273 |
return e.Err.Error() |
| 274 |
} |
| 275 |
|
| 276 |
func (e *TryError) Unwrap() error { |
| 277 |
return e.Err |
| 278 |
} |
| 279 |
|
| 280 |
// TryValue is what gets returned when using the "try" keyword. |
| 281 |
type TryValue struct { |
| 282 |
// Value is the value returned by the function or method wrapped with "try". |
| 283 |
// This will always be nil if Err is set. |
| 284 |
Value any |
| 285 |
|
| 286 |
// Err is the error returned by the function or method wrapped with "try". |
| 287 |
// This will always be nil if Value is set. |
| 288 |
Err *TryError |
| 289 |
} |
| 290 |
|
| 291 |
// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so |
| 292 |
// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0] |
| 293 |
// as the function itself. |
| 294 |
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) { |
| 295 |
// Added for Hugo. |
| 296 |
if name == "try" { |
| 297 |
defer func() { |
| 298 |
if r := recover(); r != nil { |
| 299 |
// Cause: herrors.Cause(err) |
| 300 |
if err, ok := r.(error); ok { |
| 301 |
val = reflect.ValueOf(TryValue{Value: nil, Err: newErrorWithCause(err)}) |
| 302 |
} else { |
| 303 |
val = reflect.ValueOf(TryValue{Value: nil, Err: newErrorWithCause(fmt.Errorf("%v", r))}) |
| 304 |
} |
| 305 |
} |
| 306 |
}() |
| 307 |
} |
| 308 |
|
| 309 |
if args != nil { |
| 310 |
args = args[1:] // Zeroth arg is function name/node; not passed to function. |
| 311 |
} |
| 312 |
typ := fun.Type() |
| 313 |
numFirst := len(first) // Added for Hugo |
| 314 |
numIn := len(args) + numFirst // Added for Hugo |
| 315 |
if !isMissing(final) { |
| 316 |
numIn++ |
| 317 |
} |
| 318 |
numFixed := len(args) + len(first) // Adjusted for Hugo |
| 319 |
if typ.IsVariadic() { |
| 320 |
numFixed = typ.NumIn() - 1 // last arg is the variadic one. |
| 321 |
if numIn < numFixed { |
| 322 |
s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args)) |
| 323 |
} |
| 324 |
} else if numIn != typ.NumIn() { |
| 325 |
s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), numIn) |
| 326 |
} |
| 327 |
if err := goodFunc(name, typ); err != nil { |
| 328 |
s.errorf("%v", err) |
| 329 |
} |
| 330 |
|
| 331 |
unwrap := func(v reflect.Value) reflect.Value { |
| 332 |
if v.Type() == reflectValueType { |
| 333 |
v = v.Interface().(reflect.Value) |
| 334 |
} |
| 335 |
return v |
| 336 |
} |
| 337 |
|
| 338 |
// Special case for builtin and/or, which short-circuit. |
| 339 |
if isBuiltin && (name == "and" || name == "or") { |
| 340 |
argType := typ.In(0) |
| 341 |
var v reflect.Value |
| 342 |
for _, arg := range args { |
| 343 |
v = s.evalArg(dot, argType, arg).Interface().(reflect.Value) |
| 344 |
if truth(v) == (name == "or") { |
| 345 |
// This value was already unwrapped |
| 346 |
// by the .Interface().(reflect.Value). |
| 347 |
return v |
| 348 |
} |
| 349 |
} |
| 350 |
if !final.Equal(missingVal) { |
| 351 |
// The last argument to and/or is coming from |
| 352 |
// the pipeline. We didn't short circuit on an earlier |
| 353 |
// argument, so we are going to return this one. |
| 354 |
// We don't have to evaluate final, but we do |
| 355 |
// have to check its type. Then, since we are |
| 356 |
// going to return it, we have to unwrap it. |
| 357 |
v = unwrap(s.validateType(final, argType)) |
| 358 |
} |
| 359 |
return v |
| 360 |
} |
| 361 |
|
| 362 |
// Build the arg list. |
| 363 |
argv := make([]reflect.Value, numIn) |
| 364 |
// Args must be evaluated. Fixed args first. |
| 365 |
i := len(first) // Adjusted for Hugo. |
| 366 |
for ; i < numFixed && i < len(args)+numFirst; i++ { // Adjusted for Hugo. |
| 367 |
argv[i] = s.evalArg(dot, typ.In(i), args[i-numFirst]) // Adjusted for Hugo. |
| 368 |
} |
| 369 |
// Now the ... args. |
| 370 |
if typ.IsVariadic() { |
| 371 |
argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice. |
| 372 |
for ; i < len(args)+numFirst; i++ { // Adjusted for Hugo. |
| 373 |
argv[i] = s.evalArg(dot, argType, args[i-numFirst]) // Adjusted for Hugo. |
| 374 |
} |
| 375 |
} |
| 376 |
// Add final value if necessary. |
| 377 |
if !isMissing(final) { |
| 378 |
t := typ.In(typ.NumIn() - 1) |
| 379 |
if typ.IsVariadic() { |
| 380 |
if numIn-1 < numFixed { |
| 381 |
// The added final argument corresponds to a fixed parameter of the function. |
| 382 |
// Validate against the type of the actual parameter. |
| 383 |
t = typ.In(numIn - 1) |
| 384 |
} else { |
| 385 |
// The added final argument corresponds to the variadic part. |
| 386 |
// Validate against the type of the elements of the variadic slice. |
| 387 |
t = t.Elem() |
| 388 |
} |
| 389 |
} |
| 390 |
argv[i] = s.validateType(final, t) |
| 391 |
} |
| 392 |
|
| 393 |
// Special case for the "call" builtin. |
| 394 |
// Insert the name of the callee function as the first argument. |
| 395 |
if isBuiltin && name == "call" { |
| 396 |
var calleeName string |
| 397 |
if len(args) == 0 { |
| 398 |
// final must be present or we would have errored out above. |
| 399 |
calleeName = final.String() |
| 400 |
} else { |
| 401 |
calleeName = args[0].String() |
| 402 |
} |
| 403 |
argv = append([]reflect.Value{reflect.ValueOf(calleeName)}, argv...) |
| 404 |
fun = reflect.ValueOf(call) |
| 405 |
} |
| 406 |
|
| 407 |
// Added for Hugo |
| 408 |
for i := range first { |
| 409 |
argv[i] = s.validateType(first[i], typ.In(i)) |
| 410 |
} |
| 411 |
|
| 412 |
v, err := safeCall(fun, argv) |
| 413 |
// If we have an error that is not nil, stop execution and return that |
| 414 |
// error to the caller. |
| 415 |
if err != nil { |
| 416 |
s.at(node) |
| 417 |
s.errorf("error calling %s: %w", name, err) |
| 418 |
} |
| 419 |
vv := unwrap(v) |
| 420 |
|
| 421 |
// Added for Hugo |
| 422 |
if s.helper != nil { |
| 423 |
s.helper.OnCalled(s.ctx, s.prep, name, argv, vv) |
| 424 |
} |
| 425 |
|
| 426 |
// Added for Hugo. |
| 427 |
if name == "try" { |
| 428 |
return reflect.ValueOf(TryValue{Value: vv.Interface()}) |
| 429 |
} |
| 430 |
|
| 431 |
return vv |
| 432 |
} |
| 433 |
|
| 434 |
// validateType guarantees that the value is valid and assignable to the type. |
| 435 |
func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value { |
| 436 |
if !value.IsValid() { |
| 437 |
if typ == nil { |
| 438 |
// An untyped nil interface{}. Accept as a proper nil value. |
| 439 |
return reflect.ValueOf(nil) |
| 440 |
} |
| 441 |
if canBeNil(typ) { |
| 442 |
// Like above, but use the zero value of the non-nil type. |
| 443 |
return reflect.Zero(typ) |
| 444 |
} |
| 445 |
s.errorf("invalid value; expected %s", typ) |
| 446 |
} |
| 447 |
if typ == reflectValueType && value.Type() != typ { |
| 448 |
return reflect.ValueOf(value) |
| 449 |
} |
| 450 |
if typ != nil && !value.Type().AssignableTo(typ) { |
| 451 |
if value.Kind() == reflect.Interface && !value.IsNil() { |
| 452 |
value = value.Elem() |
| 453 |
if value.Type().AssignableTo(typ) { |
| 454 |
return value |
| 455 |
} |
| 456 |
// fallthrough |
| 457 |
} |
| 458 |
// Does one dereference or indirection work? We could do more, as we |
| 459 |
// do with method receivers, but that gets messy and method receivers |
| 460 |
// are much more constrained, so it makes more sense there than here. |
| 461 |
// Besides, one is almost always all you need. |
| 462 |
switch { |
| 463 |
case value.Kind() == reflect.Pointer && value.Type().Elem().AssignableTo(typ): |
| 464 |
value = value.Elem() |
| 465 |
if !value.IsValid() { |
| 466 |
s.errorf("dereference of nil pointer of type %s", typ) |
| 467 |
} |
| 468 |
case reflect.PointerTo(value.Type()).AssignableTo(typ) && value.CanAddr(): |
| 469 |
value = value.Addr() |
| 470 |
default: |
| 471 |
// Added for Hugo. |
| 472 |
if v, ok := hreflect.ConvertIfPossible(value, typ); ok { |
| 473 |
value = v |
| 474 |
} else { |
| 475 |
s.errorf("wrong type for value; expected %s; got %s", typ, value.Type()) |
| 476 |
} |
| 477 |
|
| 478 |
} |
| 479 |
} |
| 480 |
return value |
| 481 |
} |
| 482 |
|
| 483 |
func isTrue(val reflect.Value) (truth, ok bool) { |
| 484 |
return hreflect.IsTruthfulValue(val), true |
| 485 |
} |
| 486 |
|
| 487 |
func (t *Template) All() iter.Seq[*Template] { |
| 488 |
return func(yield func(t *Template) bool) { |
| 489 |
if t.common == nil { |
| 490 |
return |
| 491 |
} |
| 492 |
t.muTmpl.RLock() |
| 493 |
defer t.muTmpl.RUnlock() |
| 494 |
for _, v := range t.tmpl { |
| 495 |
if !yield(v) { |
| 496 |
return |
| 497 |
} |
| 498 |
} |
| 499 |
} |
| 500 |
} |