Debian Codegraph @

tpl/collections/where.go

raw
1 // Copyright 2017 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 collections
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "reflect"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/hmaps"
24 "github.com/gohugoio/hugo/common/hreflect"
25 "github.com/gohugoio/hugo/common/hstrings"
26 "github.com/gohugoio/hugo/compare"
27 )
28
29 // Where returns a filtered subset of collection c.
30 func (ns *Namespace) Where(ctx context.Context, c, key any, args ...any) (any, error) {
31 seqv, isNil := hreflect.Indirect(reflect.ValueOf(c))
32 if isNil {
33 return nil, errors.New("can't iterate over a nil value of type " + reflect.ValueOf(c).Type().String())
34 }
35
36 mv, op, err := parseWhereArgs(args...)
37 if err != nil {
38 return nil, err
39 }
40
41 ctxv := reflect.ValueOf(ctx)
42
43 var path []string
44 kv := reflect.ValueOf(key)
45 if kv.Kind() == reflect.String {
46 path = strings.Split(strings.Trim(kv.String(), "."), ".")
47 }
48
49 switch seqv.Kind() {
50 case reflect.Array, reflect.Slice:
51 return ns.checkWhereArray(ctxv, seqv, kv, mv, path, op)
52 case reflect.Map:
53 return ns.checkWhereMap(ctxv, seqv, kv, mv, path, op)
54 default:
55 return nil, fmt.Errorf("can't iterate over %T", c)
56 }
57 }
58
59 func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error) {
60 v, vIsNil := hreflect.Indirect(v)
61 if !v.IsValid() {
62 vIsNil = true
63 }
64
65 mv, mvIsNil := hreflect.Indirect(mv)
66 if !mv.IsValid() {
67 mvIsNil = true
68 }
69 if vIsNil || mvIsNil {
70 switch op {
71 case "", "=", "==", "eq":
72 return vIsNil == mvIsNil, nil
73 case "!=", "<>", "ne":
74 return vIsNil != mvIsNil, nil
75 }
76 return false, nil
77 }
78
79 if v.Kind() == reflect.Bool && mv.Kind() == reflect.Bool {
80 switch op {
81 case "", "=", "==", "eq":
82 return v.Bool() == mv.Bool(), nil
83 case "!=", "<>", "ne":
84 return v.Bool() != mv.Bool(), nil
85 }
86 return false, nil
87 }
88
89 switch op {
90 case "", "=", "==", "eq", "!=", "<>", "ne":
91 if eq, ok := tryEq(v, mv); ok {
92 if op == "!=" || op == "<>" || op == "ne" {
93 return !eq, nil
94 }
95 return eq, nil
96 }
97 }
98
99 var ivp, imvp *int64
100 var svp, smvp *string
101 var slv, slmv any
102 var nv, nmv any
103 var ima []int64
104 var sma []string
105
106 if c, ok := hreflect.CompareNumbers(v, mv); ok {
107 // Feed the result through the int64 comparisons below.
108 iv, imv := int64(c), int64(0)
109 ivp, imvp = &iv, &imv
110 } else if mv.Kind() == v.Kind() {
111 switch v.Kind() {
112 case reflect.String:
113 sv := v.String()
114 svp = &sv
115 smv := mv.String()
116 smvp = &smv
117 case reflect.Struct:
118 if hreflect.IsTime(v.Type()) {
119 iv := ns.toTimeUnix(v)
120 ivp = &iv
121 imv := ns.toTimeUnix(mv)
122 imvp = &imv
123 }
124 case reflect.Array, reflect.Slice:
125 slv = v.Interface()
126 slmv = mv.Interface()
127 }
128 } else {
129 if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice {
130 return false, nil
131 }
132
133 if mv.Len() == 0 {
134 if op == "not in" {
135 return true, nil
136 }
137 return false, nil
138 }
139
140 switch {
141 case hreflect.IsNumber(v.Kind()):
142 nv = v.Interface()
143 nmv = mv.Interface()
144 case v.Kind() == reflect.String:
145 sv := v.String()
146 svp = &sv
147 for i := range mv.Len() {
148 if aString, err := hreflect.ToStringE(mv.Index(i)); err == nil {
149 sma = append(sma, aString)
150 }
151 }
152 case hreflect.IsTime(v.Type()):
153 iv := ns.toTimeUnix(v)
154 ivp = &iv
155 for i := range mv.Len() {
156 if t, ok := hreflect.AsTime(mv.Index(i), ns.loc); ok {
157 ima = append(ima, t.Unix())
158 }
159 }
160 case v.Kind() == reflect.Array, v.Kind() == reflect.Slice:
161 slv = v.Interface()
162 slmv = mv.Interface()
163 }
164 }
165
166 switch op {
167 case "", "=", "==", "eq":
168 switch {
169 case ivp != nil && imvp != nil:
170 return *ivp == *imvp, nil
171 case svp != nil && smvp != nil:
172 return *svp == *smvp, nil
173 }
174 case "!=", "<>", "ne":
175 switch {
176 case ivp != nil && imvp != nil:
177 return *ivp != *imvp, nil
178 case svp != nil && smvp != nil:
179 return *svp != *smvp, nil
180 }
181 case ">=", "ge":
182 switch {
183 case ivp != nil && imvp != nil:
184 return *ivp >= *imvp, nil
185 case svp != nil && smvp != nil:
186 return *svp >= *smvp, nil
187 }
188 case ">", "gt":
189 switch {
190 case ivp != nil && imvp != nil:
191 return *ivp > *imvp, nil
192 case svp != nil && smvp != nil:
193 return *svp > *smvp, nil
194 }
195 case "<=", "le":
196 switch {
197 case ivp != nil && imvp != nil:
198 return *ivp <= *imvp, nil
199 case svp != nil && smvp != nil:
200 return *svp <= *smvp, nil
201 }
202 case "<", "lt":
203 switch {
204 case ivp != nil && imvp != nil:
205 return *ivp < *imvp, nil
206 case svp != nil && smvp != nil:
207 return *svp < *smvp, nil
208 }
209 case "in", "not in":
210 var r bool
211 switch {
212 case nv != nil:
213 r, _ = ns.In(nmv, nv)
214 case ivp != nil && len(ima) > 0:
215 r, _ = ns.In(ima, *ivp)
216 case svp != nil:
217 if len(sma) > 0 {
218 r, _ = ns.In(sma, *svp)
219 } else if smvp != nil {
220 r, _ = ns.In(*smvp, *svp)
221 }
222 default:
223 return false, nil
224 }
225 if op == "not in" {
226 return !r, nil
227 }
228 return r, nil
229 case "intersect":
230 r, err := ns.Intersect(slv, slmv)
231 if err != nil {
232 return false, err
233 }
234
235 if reflect.TypeOf(r).Kind() == reflect.Slice {
236 s := reflect.ValueOf(r)
237
238 if s.Len() > 0 {
239 return true, nil
240 }
241 return false, nil
242 }
243 return false, errors.New("invalid intersect values")
244 case "like":
245 if svp != nil && smvp != nil {
246 re, err := hstrings.GetOrCompileRegexp(*smvp)
247 if err != nil {
248 return false, err
249 }
250 if re.MatchString(*svp) {
251 return true, nil
252 }
253 return false, nil
254 }
255 default:
256 return false, errors.New("no such operator")
257 }
258 return false, nil
259 }
260
261 func evaluateSubElem(ctx, obj reflect.Value, elemName string) (reflect.Value, error) {
262 if !obj.IsValid() {
263 return zero, errors.New("can't evaluate an invalid value")
264 }
265
266 typ := obj.Type()
267 obj, isNil := hreflect.Indirect(obj)
268
269 // first, check whether obj has a method. In this case, obj is
270 // a struct or its pointer. If obj is a struct,
271 // to check all T and *T method, use obj pointer type Value
272 objPtr := obj
273 if !hreflect.IsInterfaceOrPointer(objPtr.Kind()) && objPtr.CanAddr() {
274 objPtr = objPtr.Addr()
275 }
276
277 mt := hreflect.GetMethodByNameForType(objPtr.Type(), elemName)
278 if mt.Func.IsValid() {
279 // Receiver is the first argument.
280 args := []reflect.Value{objPtr}
281 num := mt.Type.NumIn()
282 maxNumIn := 1
283 if num > 1 && hreflect.IsContextType(mt.Type.In(1)) {
284 args = append(args, ctx)
285 maxNumIn = 2
286 }
287
288 switch {
289 case mt.PkgPath != "":
290 return zero, fmt.Errorf("%s is an unexported method of type %s", elemName, typ)
291 case mt.Type.NumIn() > maxNumIn:
292 return zero, fmt.Errorf("%s is a method of type %s but requires more than %d parameter", elemName, typ, maxNumIn)
293 case mt.Type.NumOut() == 0:
294 return zero, fmt.Errorf("%s is a method of type %s but returns no output", elemName, typ)
295 case mt.Type.NumOut() > 2:
296 return zero, fmt.Errorf("%s is a method of type %s but returns more than 2 outputs", elemName, typ)
297 case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType):
298 return zero, fmt.Errorf("%s is a method of type %s but only returns an error type", elemName, typ)
299 case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType):
300 return zero, fmt.Errorf("%s is a method of type %s returning two values but the second value is not an error type", elemName, typ)
301 }
302 res := mt.Func.Call(args)
303 if len(res) == 2 && !res[1].IsNil() {
304 return zero, fmt.Errorf("error at calling a method %s of type %s: %s", elemName, typ, res[1].Interface().(error))
305 }
306 return res[0], nil
307 }
308
309 // elemName isn't a method so next start to check whether it is
310 // a struct field or a map value. In both cases, it mustn't be
311 // a nil value
312 if isNil {
313 return zero, fmt.Errorf("can't evaluate a nil pointer of type %s by a struct field or map key name %s", typ, elemName)
314 }
315 obj = reflect.Indirect(obj)
316 switch obj.Kind() {
317 case reflect.Struct:
318 ft, ok := obj.Type().FieldByName(elemName)
319 if ok {
320 if ft.PkgPath != "" && !ft.Anonymous {
321 return zero, fmt.Errorf("%s is an unexported field of struct type %s", elemName, typ)
322 }
323 return obj.FieldByIndex(ft.Index), nil
324 }
325 return zero, fmt.Errorf("%s isn't a field of struct type %s", elemName, typ)
326 case reflect.Map:
327 kv := reflect.ValueOf(elemName)
328 if kv.Type().AssignableTo(obj.Type().Key()) {
329 return obj.MapIndex(kv), nil
330 }
331 return zero, fmt.Errorf("%s isn't a key of map type %s", elemName, typ)
332 }
333 return zero, fmt.Errorf("%s is neither a struct field, a method nor a map element of type %s", elemName, typ)
334 }
335
336 // parseWhereArgs parses the end arguments to the where function. Return a
337 // match value and an operator, if one is defined.
338 func parseWhereArgs(args ...any) (mv reflect.Value, op string, err error) {
339 switch len(args) {
340 case 1:
341 mv = reflect.ValueOf(args[0])
342 case 2:
343 var ok bool
344 if op, ok = args[0].(string); !ok {
345 err = errors.New("operator argument must be string type")
346 return
347 }
348 op = strings.TrimSpace(strings.ToLower(op))
349 mv = reflect.ValueOf(args[1])
350 default:
351 err = errors.New("can't evaluate the array by no match argument or more than or equal to two arguments")
352 }
353 return
354 }
355
356 // elemResolver resolves a sub-element from a reflect.Value.
357 // Built once before the loop to avoid repeated type checks and reflect.ValueOf allocations.
358 type elemResolver func(reflect.Value) (reflect.Value, error)
359
360 // newElemResolver returns a resolver optimized for the given element type and path.
361 // Returns nil if optimization isn't possible, in which case the caller should
362 // fall back to evaluateSubElem.
363 func (ns *Namespace) newElemResolver(ctxv reflect.Value, elemType reflect.Type, path []string) elemResolver {
364 if elemType.Kind() == reflect.Interface {
365 if len(path) != 1 {
366 return nil
367 }
368 return ns.newInterfaceMethodResolver(ctxv, elemType, path[0])
369 }
370
371 baseType := elemType
372 isPtr := baseType.Kind() == reflect.Pointer
373 if isPtr {
374 baseType = baseType.Elem()
375 }
376
377 if baseType == reflect.TypeFor[hmaps.Params]() {
378 return func(v reflect.Value) (reflect.Value, error) {
379 if isPtr {
380 if v.IsNil() {
381 return zero, nil
382 }
383 v = v.Elem()
384 }
385 params := v.Interface().(hmaps.Params)
386 return reflect.ValueOf(params.GetNested(path...)), nil
387 }
388 }
389
390 if len(path) != 1 {
391 return nil
392 }
393 name := path[0]
394
395 // Check for method first, matching evaluateSubElem order.
396 ptrType := baseType
397 if !hreflect.IsInterfaceOrPointer(ptrType.Kind()) {
398 ptrType = reflect.PointerTo(baseType)
399 }
400 mt := hreflect.GetMethodByNameForType(ptrType, name)
401 if mt.Func.IsValid() {
402 return ns.newMethodResolver(ctxv, elemType, mt)
403 }
404
405 switch baseType.Kind() {
406 case reflect.Map:
407 if baseType.Key().Kind() == reflect.String {
408 kv := reflect.ValueOf(name)
409 return func(v reflect.Value) (reflect.Value, error) {
410 if isPtr {
411 if v.IsNil() {
412 return zero, nil
413 }
414 v = v.Elem()
415 }
416 return v.MapIndex(kv), nil
417 }
418 }
419 case reflect.Struct:
420 ft, ok := baseType.FieldByName(name)
421 if ok {
422 if ft.PkgPath != "" && !ft.Anonymous {
423 return func(v reflect.Value) (reflect.Value, error) {
424 return zero, fmt.Errorf("%s is an unexported field of struct type %s", name, elemType)
425 }
426 }
427 idx := ft.Index
428 return func(v reflect.Value) (reflect.Value, error) {
429 if isPtr {
430 if v.IsNil() {
431 return zero, nil
432 }
433 v = v.Elem()
434 }
435 return v.FieldByIndex(idx), nil
436 }
437 }
438 }
439
440 return nil
441 }
442
443 func (ns *Namespace) newMethodResolver(ctxv reflect.Value, elemType reflect.Type, mt reflect.Method) elemResolver {
444 if mt.PkgPath != "" {
445 return func(v reflect.Value) (reflect.Value, error) {
446 return zero, fmt.Errorf("%s is an unexported method of type %s", mt.Name, elemType)
447 }
448 }
449
450 numIn := mt.Type.NumIn()
451 maxNumIn := 1
452 needsCtx := numIn > 1 && hreflect.IsContextType(mt.Type.In(1))
453 if needsCtx {
454 maxNumIn = 2
455 }
456
457 switch {
458 case mt.Type.NumIn() > maxNumIn:
459 return nil
460 case mt.Type.NumOut() == 0:
461 return nil
462 case mt.Type.NumOut() > 2:
463 return nil
464 case mt.Type.NumOut() == 1 && mt.Type.Out(0).Implements(errorType):
465 return nil
466 case mt.Type.NumOut() == 2 && !mt.Type.Out(1).Implements(errorType):
467 return nil
468 }
469
470 fn := mt.Func
471 hasErrOut := mt.Type.NumOut() == 2
472 isPtr := elemType.Kind() == reflect.Pointer
473
474 var callArgs []reflect.Value
475 if needsCtx {
476 callArgs = make([]reflect.Value, 2)
477 callArgs[1] = ctxv
478 } else {
479 callArgs = make([]reflect.Value, 1)
480 }
481
482 return func(v reflect.Value) (reflect.Value, error) {
483 if isPtr && v.IsNil() {
484 return zero, nil
485 }
486 recv := v
487 if !isPtr && !hreflect.IsInterfaceOrPointer(recv.Kind()) && recv.CanAddr() {
488 recv = recv.Addr()
489 }
490 callArgs[0] = recv
491 res := fn.Call(callArgs)
492 if hasErrOut && !res[1].IsNil() {
493 return zero, res[1].Interface().(error)
494 }
495 return res[0], nil
496 }
497 }
498
499 // newInterfaceMethodResolver returns a method resolver or nil if not possible, in which the caller should fall back to evaluateSubElem.
500 func (ns *Namespace) newInterfaceMethodResolver(ctxv reflect.Value, ifaceType reflect.Type, name string) elemResolver {
501 mt, ok := ifaceType.MethodByName(name)
502 if !ok {
503 return nil
504 }
505
506 // For interface methods, Type does not include the receiver.
507 mType := mt.Type
508 numIn := mType.NumIn()
509 maxNumIn := 0
510 needsCtx := numIn > 0 && hreflect.IsContextType(mType.In(0))
511 if needsCtx {
512 maxNumIn = 1
513 }
514
515 switch {
516 case mType.NumIn() > maxNumIn:
517 return nil
518 case mType.NumOut() == 0:
519 return nil
520 case mType.NumOut() > 2:
521 return nil
522 case mType.NumOut() == 1 && mType.Out(0).Implements(errorType):
523 return nil
524 case mType.NumOut() == 2 && !mType.Out(1).Implements(errorType):
525 return nil
526 }
527
528 index := mt.Index
529 hasErrOut := mType.NumOut() == 2
530
531 var callArgs []reflect.Value
532 if needsCtx {
533 callArgs = []reflect.Value{ctxv}
534 }
535
536 return func(v reflect.Value) (reflect.Value, error) {
537 if v.IsNil() {
538 return zero, nil
539 }
540 res := v.Method(index).Call(callArgs)
541 if hasErrOut && !res[1].IsNil() {
542 return zero, res[1].Interface().(error)
543 }
544 return res[0], nil
545 }
546 }
547
548 // checkWhereArray handles the where-matching logic when the seqv value is an
549 // Array or Slice.
550 func (ns *Namespace) checkWhereArray(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) {
551 rv := reflect.MakeSlice(seqv.Type(), 0, 0)
552
553 var resolve elemResolver
554 if kv.Kind() == reflect.String && len(path) > 0 {
555 resolve = ns.newElemResolver(ctxv, seqv.Type().Elem(), path)
556 }
557
558 for i := range seqv.Len() {
559 var vvv reflect.Value
560 rvv := seqv.Index(i)
561
562 if resolve != nil {
563 var err error
564 vvv, err = resolve(rvv)
565 if err != nil {
566 return nil, err
567 }
568 } else if kv.Kind() == reflect.String {
569 if params, ok := rvv.Interface().(hmaps.Params); ok {
570 vvv = reflect.ValueOf(params.GetNested(path...))
571 } else {
572 vvv = rvv
573 for i, elemName := range path {
574 var err error
575 vvv, err = evaluateSubElem(ctxv, vvv, elemName)
576 if err != nil {
577 continue
578 }
579
580 if i < len(path)-1 && vvv.IsValid() {
581 if params, ok := vvv.Interface().(hmaps.Params); ok {
582 vvv = reflect.ValueOf(params.GetNested(path[i+1:]...))
583 break
584 }
585 }
586 }
587 }
588 } else {
589 vv, _ := hreflect.Indirect(rvv)
590 if vv.Kind() == reflect.Map && kv.Type().AssignableTo(vv.Type().Key()) {
591 vvv = vv.MapIndex(kv)
592 }
593 }
594
595 if ok, err := ns.checkCondition(vvv, mv, op); ok {
596 rv = reflect.Append(rv, rvv)
597 } else if err != nil {
598 return nil, err
599 }
600 }
601 return rv.Interface(), nil
602 }
603
604 // checkWhereMap handles the where-matching logic when the seqv value is a Map.
605 func (ns *Namespace) checkWhereMap(ctxv, seqv, kv, mv reflect.Value, path []string, op string) (any, error) {
606 rv := reflect.MakeMap(seqv.Type())
607 k := reflect.New(seqv.Type().Key()).Elem()
608 elemv := reflect.New(seqv.Type().Elem()).Elem()
609 iter := seqv.MapRange()
610 for iter.Next() {
611 k.SetIterKey(iter)
612 elemv.SetIterValue(iter)
613 switch elemv.Kind() {
614 case reflect.Array, reflect.Slice:
615 r, err := ns.checkWhereArray(ctxv, elemv, kv, mv, path, op)
616 if err != nil {
617 return nil, err
618 }
619
620 switch rr := reflect.ValueOf(r); rr.Kind() {
621 case reflect.Slice:
622 if rr.Len() > 0 {
623 rv.SetMapIndex(k, elemv)
624 }
625 }
626 case reflect.Interface:
627 elemvv, isNil := hreflect.Indirect(elemv)
628 if isNil {
629 continue
630 }
631
632 switch elemvv.Kind() {
633 case reflect.Array, reflect.Slice:
634 r, err := ns.checkWhereArray(ctxv, elemvv, kv, mv, path, op)
635 if err != nil {
636 return nil, err
637 }
638
639 switch rr := reflect.ValueOf(r); rr.Kind() {
640 case reflect.Slice:
641 if rr.Len() > 0 {
642 rv.SetMapIndex(k, elemv)
643 }
644 }
645 }
646 }
647 }
648 return rv.Interface(), nil
649 }
650
651 // toString returns the string value if possible, "" if not.
652
653 // tryEq returns the equality of v and mv via the compare.Eqer interface
654 // if either side implements it. The second return value reports whether
655 // such a comparison was possible.
656 func tryEq(v, mv reflect.Value) (bool, bool) {
657 if !v.CanInterface() || !mv.CanInterface() {
658 return false, false
659 }
660 vi, mvi := v.Interface(), mv.Interface()
661 if e, ok := vi.(compare.Eqer); ok {
662 return e.Eq(mvi), true
663 }
664 if e, ok := mvi.(compare.Eqer); ok {
665 return e.Eq(vi), true
666 }
667 return false, false
668 }
669
670 func (ns *Namespace) toTimeUnix(v reflect.Value) int64 {
671 t, ok := hreflect.AsTime(v, ns.loc)
672 if !ok {
673 panic("coding error: argument must be time.Time type reflect Value")
674 }
675 return t.Unix()
676 }