| 1 |
// Copyright 2025 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 hreflect contains reflect helpers. |
| 15 |
package hreflect |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"reflect" |
| 20 |
"sync" |
| 21 |
"time" |
| 22 |
|
| 23 |
"github.com/gohugoio/hugo/common/hmaps" |
| 24 |
"github.com/gohugoio/hugo/common/htime" |
| 25 |
"github.com/gohugoio/hugo/common/types" |
| 26 |
) |
| 27 |
|
| 28 |
// IsInterfaceOrPointer returns whether the given kind is an interface or a pointer. |
| 29 |
func IsInterfaceOrPointer(kind reflect.Kind) bool { |
| 30 |
return kind == reflect.Interface || kind == reflect.Pointer |
| 31 |
} |
| 32 |
|
| 33 |
// TODO(bep) replace the private versions in /tpl with these. |
| 34 |
// IsNumber returns whether the given kind is a number. |
| 35 |
func IsNumber(kind reflect.Kind) bool { |
| 36 |
return IsInt(kind) || IsUint(kind) || IsFloat(kind) |
| 37 |
} |
| 38 |
|
| 39 |
// IsInt returns whether the given kind is an int. |
| 40 |
func IsInt(kind reflect.Kind) bool { |
| 41 |
switch kind { |
| 42 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 43 |
return true |
| 44 |
default: |
| 45 |
return false |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// IsUint returns whether the given kind is an uint. |
| 50 |
func IsUint(kind reflect.Kind) bool { |
| 51 |
switch kind { |
| 52 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 53 |
return true |
| 54 |
default: |
| 55 |
return false |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// IsFloat returns whether the given kind is a float. |
| 60 |
func IsFloat(kind reflect.Kind) bool { |
| 61 |
switch kind { |
| 62 |
case reflect.Float32, reflect.Float64: |
| 63 |
return true |
| 64 |
default: |
| 65 |
return false |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
// IsString returns whether the given kind is a string. |
| 70 |
func IsString(kind reflect.Kind) bool { |
| 71 |
return kind == reflect.String |
| 72 |
} |
| 73 |
|
| 74 |
// IsTruthful returns whether in represents a truthful value. |
| 75 |
// See IsTruthfulValue |
| 76 |
func IsTruthful(in any) bool { |
| 77 |
switch v := in.(type) { |
| 78 |
case reflect.Value: |
| 79 |
return IsTruthfulValue(v) |
| 80 |
default: |
| 81 |
return IsTruthfulValue(reflect.ValueOf(in)) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
// IsMap reports whether v is a map. |
| 86 |
func IsMap(v any) bool { |
| 87 |
return reflect.ValueOf(v).Kind() == reflect.Map |
| 88 |
} |
| 89 |
|
| 90 |
// IsSlice reports whether v is a slice. |
| 91 |
func IsSlice(v any) bool { |
| 92 |
return reflect.ValueOf(v).Kind() == reflect.Slice |
| 93 |
} |
| 94 |
|
| 95 |
var zeroType = reflect.TypeFor[types.Zeroer]() |
| 96 |
|
| 97 |
var isZeroCache sync.Map |
| 98 |
|
| 99 |
func implementsIsZero(tp reflect.Type) bool { |
| 100 |
v, ok := isZeroCache.Load(tp) |
| 101 |
if ok { |
| 102 |
return v.(bool) |
| 103 |
} |
| 104 |
implements := tp.Implements(zeroType) |
| 105 |
isZeroCache.Store(tp, implements) |
| 106 |
return implements |
| 107 |
} |
| 108 |
|
| 109 |
// IsTruthfulValue returns whether the given value has a meaningful truth value. |
| 110 |
// This is based on template.IsTrue in Go's stdlib, but also considers |
| 111 |
// IsZero and any interface value will be unwrapped before it's considered |
| 112 |
// for truthfulness. |
| 113 |
// |
| 114 |
// Based on: |
| 115 |
// https://github.com/golang/go/blob/178a2c42254166cffed1b25fb1d3c7a5727cada6/src/text/template/exec.go#L306 |
| 116 |
func IsTruthfulValue(val reflect.Value) (truth bool) { |
| 117 |
val, isNil := Indirect(val) |
| 118 |
|
| 119 |
if !val.IsValid() { |
| 120 |
// Something like: var x any, never set. It's a form of nil. |
| 121 |
return |
| 122 |
} |
| 123 |
|
| 124 |
if val.Kind() == reflect.Pointer && isNil { |
| 125 |
return |
| 126 |
} |
| 127 |
|
| 128 |
if implementsIsZero(val.Type()) { |
| 129 |
return !val.Interface().(types.Zeroer).IsZero() |
| 130 |
} |
| 131 |
|
| 132 |
switch val.Kind() { |
| 133 |
case reflect.Array, reflect.Map, reflect.Slice, reflect.String: |
| 134 |
truth = val.Len() > 0 |
| 135 |
case reflect.Bool: |
| 136 |
truth = val.Bool() |
| 137 |
case reflect.Complex64, reflect.Complex128: |
| 138 |
truth = val.Complex() != 0 |
| 139 |
case reflect.Chan, reflect.Func, reflect.Pointer, reflect.UnsafePointer, reflect.Interface: |
| 140 |
truth = !val.IsNil() |
| 141 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 142 |
truth = val.Int() != 0 |
| 143 |
case reflect.Float32, reflect.Float64: |
| 144 |
truth = val.Float() != 0 |
| 145 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 146 |
truth = val.Uint() != 0 |
| 147 |
case reflect.Struct: |
| 148 |
truth = true // Struct values are always true. |
| 149 |
default: |
| 150 |
return |
| 151 |
} |
| 152 |
|
| 153 |
return |
| 154 |
} |
| 155 |
|
| 156 |
type methodKey struct { |
| 157 |
typ reflect.Type |
| 158 |
name string |
| 159 |
} |
| 160 |
|
| 161 |
var ( |
| 162 |
methodIndexCache sync.Map |
| 163 |
methodCache sync.Map |
| 164 |
) |
| 165 |
|
| 166 |
// GetMethodByNameForType returns the method with the given name for the given type, |
| 167 |
// or a zero Method if no such method exists. |
| 168 |
// It panics if tp is an interface type. |
| 169 |
// It caches the lookup. |
| 170 |
func GetMethodByNameForType(tp reflect.Type, name string) reflect.Method { |
| 171 |
if tp.Kind() == reflect.Interface { |
| 172 |
// Func field is nil for interface types. |
| 173 |
panic("not supported for interface types") |
| 174 |
} |
| 175 |
k := methodKey{tp, name} |
| 176 |
v, found := methodCache.Load(k) |
| 177 |
if found { |
| 178 |
return v.(reflect.Method) |
| 179 |
} |
| 180 |
m, _ := tp.MethodByName(name) |
| 181 |
methodCache.Store(k, m) |
| 182 |
return m |
| 183 |
} |
| 184 |
|
| 185 |
// GetMethodByName is the same as reflect.Value.MethodByName, but it caches the lookup. |
| 186 |
func GetMethodByName(v reflect.Value, name string) reflect.Value { |
| 187 |
index := GetMethodIndexByName(v.Type(), name) |
| 188 |
|
| 189 |
if index == -1 { |
| 190 |
return reflect.Value{} |
| 191 |
} |
| 192 |
|
| 193 |
return v.Method(index) |
| 194 |
} |
| 195 |
|
| 196 |
// GetMethodIndexByName returns the index of the method with the given name, or |
| 197 |
// -1 if no such method exists. |
| 198 |
func GetMethodIndexByName(tp reflect.Type, name string) int { |
| 199 |
k := methodKey{tp, name} |
| 200 |
v, found := methodIndexCache.Load(k) |
| 201 |
if found { |
| 202 |
return v.(int) |
| 203 |
} |
| 204 |
m, ok := tp.MethodByName(name) |
| 205 |
index := m.Index |
| 206 |
if !ok { |
| 207 |
index = -1 |
| 208 |
} |
| 209 |
methodIndexCache.Store(k, index) |
| 210 |
|
| 211 |
if !ok { |
| 212 |
return -1 |
| 213 |
} |
| 214 |
|
| 215 |
return m.Index |
| 216 |
} |
| 217 |
|
| 218 |
var ( |
| 219 |
timeType = reflect.TypeFor[time.Time]() |
| 220 |
asTimeProviderType = reflect.TypeFor[htime.AsTimeProvider]() |
| 221 |
) |
| 222 |
|
| 223 |
// IsTime returns whether tp is a time.Time type or if it can be converted into one |
| 224 |
// in ToTime. |
| 225 |
func IsTime(tp reflect.Type) bool { |
| 226 |
if tp == timeType { |
| 227 |
return true |
| 228 |
} |
| 229 |
|
| 230 |
if tp.Implements(asTimeProviderType) { |
| 231 |
return true |
| 232 |
} |
| 233 |
return false |
| 234 |
} |
| 235 |
|
| 236 |
// IsValid returns whether v is not nil and a valid value. |
| 237 |
func IsValid(v reflect.Value) bool { |
| 238 |
if !v.IsValid() { |
| 239 |
return false |
| 240 |
} |
| 241 |
|
| 242 |
switch v.Kind() { |
| 243 |
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: |
| 244 |
return !v.IsNil() |
| 245 |
} |
| 246 |
|
| 247 |
return true |
| 248 |
} |
| 249 |
|
| 250 |
// AsTime returns v as a time.Time if possible. |
| 251 |
// The given location is only used if the value implements AsTimeProvider (e.g. go-toml local). |
| 252 |
// A zero Time and false is returned if this isn't possible. |
| 253 |
// Note that this function does not accept string dates. |
| 254 |
func AsTime(v reflect.Value, loc *time.Location) (time.Time, bool) { |
| 255 |
if v.Kind() == reflect.Interface { |
| 256 |
return AsTime(v.Elem(), loc) |
| 257 |
} |
| 258 |
|
| 259 |
if v.Type() == timeType { |
| 260 |
return v.Interface().(time.Time), true |
| 261 |
} |
| 262 |
|
| 263 |
if v.Type().Implements(asTimeProviderType) { |
| 264 |
return v.Interface().(htime.AsTimeProvider).AsTime(loc), true |
| 265 |
} |
| 266 |
|
| 267 |
return time.Time{}, false |
| 268 |
} |
| 269 |
|
| 270 |
// ToSliceAny converts the given value to a slice of any if possible. |
| 271 |
func ToSliceAny(v any) ([]any, bool) { |
| 272 |
if v == nil { |
| 273 |
return nil, false |
| 274 |
} |
| 275 |
switch vv := v.(type) { |
| 276 |
case []any: |
| 277 |
return vv, true |
| 278 |
default: |
| 279 |
vvv := reflect.ValueOf(v) |
| 280 |
if vvv.Kind() == reflect.Slice { |
| 281 |
out := make([]any, vvv.Len()) |
| 282 |
for i := range vvv.Len() { |
| 283 |
out[i] = vvv.Index(i).Interface() |
| 284 |
} |
| 285 |
return out, true |
| 286 |
} |
| 287 |
} |
| 288 |
return nil, false |
| 289 |
} |
| 290 |
|
| 291 |
// CallMethodByName calls the method with the given name on v. |
| 292 |
func CallMethodByName(cxt context.Context, name string, v reflect.Value) []reflect.Value { |
| 293 |
fn := v.MethodByName(name) |
| 294 |
var args []reflect.Value |
| 295 |
tp := fn.Type() |
| 296 |
if tp.NumIn() > 0 { |
| 297 |
if tp.NumIn() > 1 { |
| 298 |
panic("not supported") |
| 299 |
} |
| 300 |
first := tp.In(0) |
| 301 |
if IsContextType(first) { |
| 302 |
args = append(args, reflect.ValueOf(cxt)) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
return fn.Call(args) |
| 307 |
} |
| 308 |
|
| 309 |
// Indirect unwraps interfaces and pointers until it finds a non-interface/pointer value. |
| 310 |
// If a nil is encountered, the second return value is true. |
| 311 |
// If a pointer to a struct is encountered, it is not unwrapped. |
| 312 |
func Indirect(v reflect.Value) (vv reflect.Value, isNil bool) { |
| 313 |
for ; IsInterfaceOrPointer(v.Kind()); v = v.Elem() { |
| 314 |
if IsNil(v) { |
| 315 |
return v, true |
| 316 |
} |
| 317 |
if v.Kind() != reflect.Interface { |
| 318 |
// A pointer. |
| 319 |
if v.NumMethod() > 0 { |
| 320 |
break |
| 321 |
} |
| 322 |
if v.Elem().Kind() == reflect.Struct { |
| 323 |
// Avoid unwrapping pointers to structs. |
| 324 |
break |
| 325 |
} |
| 326 |
} |
| 327 |
} |
| 328 |
return v, false |
| 329 |
} |
| 330 |
|
| 331 |
// IndirectElem is like Indirect, but if the final value is a pointer, it unwraps it. |
| 332 |
func IndirectElem(v reflect.Value) (vv reflect.Value, isNil bool) { |
| 333 |
vv, isNil = Indirect(v) |
| 334 |
if isNil { |
| 335 |
return vv, isNil |
| 336 |
} |
| 337 |
if vv.Kind() == reflect.Pointer { |
| 338 |
vv = vv.Elem() |
| 339 |
} |
| 340 |
return vv, isNil |
| 341 |
} |
| 342 |
|
| 343 |
// IsNil reports whether v is nil. |
| 344 |
// Based on reflect.Value.IsNil, but also considers invalid values as nil. |
| 345 |
func IsNil(v reflect.Value) bool { |
| 346 |
if !v.IsValid() { |
| 347 |
return true |
| 348 |
} |
| 349 |
switch v.Kind() { |
| 350 |
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: |
| 351 |
return v.IsNil() |
| 352 |
} |
| 353 |
return false |
| 354 |
} |
| 355 |
|
| 356 |
var contextInterface = reflect.TypeFor[context.Context]() |
| 357 |
|
| 358 |
var isContextCache = hmaps.NewCache[reflect.Type, bool]() |
| 359 |
|
| 360 |
type k string |
| 361 |
|
| 362 |
var contextTypeValue = reflect.TypeOf(context.WithValue(context.Background(), k("key"), 32)) |
| 363 |
|
| 364 |
// IsContextType returns whether tp is a context.Context type. |
| 365 |
func IsContextType(tp reflect.Type) bool { |
| 366 |
if tp == contextTypeValue { |
| 367 |
return true |
| 368 |
} |
| 369 |
if tp == contextInterface { |
| 370 |
return true |
| 371 |
} |
| 372 |
|
| 373 |
isContext, _ := isContextCache.GetOrCreate(tp, func() (bool, error) { |
| 374 |
return tp.Implements(contextInterface), nil |
| 375 |
}) |
| 376 |
return isContext |
| 377 |
} |