Debian Codegraph @

internal/hooks/hooks.go

raw
1 // Copyright (c) 2020, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package hooks
8
9 import (
10 "errors"
11 "fmt"
12 "reflect"
13 "sync"
14
15 "github.com/maxatome/go-testdeep/internal/types"
16 )
17
18 type properties struct {
19 cmp reflect.Value
20 smuggle reflect.Value
21 ignoreUnexported bool
22 useEqual bool
23 }
24
25 // Info gathers all hooks information.
26 type Info struct {
27 sync.Mutex
28 props map[reflect.Type]properties
29 }
30
31 // NewInfo returns a new instance of *Info.
32 func NewInfo() *Info {
33 return &Info{
34 props: map[reflect.Type]properties{},
35 }
36 }
37
38 var ErrBoolean = errors.New("CmpHook(got, expected) failed")
39
40 // Copy returns a new instance of [*Info] with the same hooks as i. As
41 // a special case, if i is nil, returned instance is non-nil.
42 func (i *Info) Copy() *Info {
43 ni := NewInfo()
44
45 if i == nil {
46 return ni
47 }
48
49 i.Lock()
50 defer i.Unlock()
51
52 if len(i.props) == 0 {
53 return ni
54 }
55
56 ni.props = make(map[reflect.Type]properties, len(i.props))
57 for t, p := range i.props {
58 ni.props[t] = p
59 }
60
61 return ni
62 }
63
64 // AddCmpHooks records new Cmp hooks using functions contained in fns.
65 //
66 // Each function in fns has to be a function with the following
67 // possible signatures:
68 //
69 // func (got A, expected A) bool
70 // func (got A, expected A) error
71 //
72 // First arg is always “got”, and second is always “expected”.
73 //
74 // A cannot be an interface. This retriction can be removed in the
75 // future, if really needed.
76 //
77 // It returns an error if an item of fns is not a function or if its
78 // signature does not match the expected ones.
79 func (i *Info) AddCmpHooks(fns []any) error {
80 for n, fn := range fns {
81 vfn := reflect.ValueOf(fn)
82
83 if vfn.Kind() != reflect.Func {
84 return fmt.Errorf("expects a function, not a %s (@%d)", vfn.Kind(), n)
85 }
86
87 ft := vfn.Type()
88 if !ft.IsVariadic() &&
89 ft.NumIn() == 2 &&
90 ft.NumOut() == 1 &&
91 ft.In(0) == ft.In(1) &&
92 ft.In(0).Kind() != reflect.Interface &&
93 (ft.Out(0) == types.Bool || ft.Out(0) == types.Error) {
94 i.Lock()
95 prop := i.props[ft.In(0)]
96 prop.cmp = vfn
97 i.props[ft.In(0)] = prop
98 i.Unlock()
99 continue
100 }
101
102 return fmt.Errorf("expects: func (T, T) bool|error not %s (@%d)", ft, n)
103 }
104 return nil
105 }
106
107 // Cmp checks if a Cmp hook exists matching got and expected types.
108 //
109 // If no, it returns (false, nil)
110 //
111 // If yes, it calls it and returns (true, nil) if it succeeds,
112 // (true, <an error>) if it fails. If the hook returns a false bool, the
113 // error returned is [ErrBoolean].
114 func (i *Info) Cmp(got, expected reflect.Value) (bool, error) {
115 if i == nil {
116 return false, nil
117 }
118
119 tg := got.Type()
120
121 i.Lock()
122 prop, ok := i.props[tg]
123 i.Unlock()
124 if !ok || !prop.cmp.IsValid() {
125 return false, nil
126 }
127
128 if !expected.Type().AssignableTo(prop.cmp.Type().In(1)) {
129 return false, nil
130 }
131
132 res := prop.cmp.Call([]reflect.Value{got, expected})[0]
133 if res.Kind() == reflect.Bool {
134 if res.Bool() {
135 return true, nil
136 }
137 return true, ErrBoolean
138 }
139 err, _ := res.Interface().(error)
140 return true, err
141 }
142
143 // AddSmuggleHooks records new Smuggle hooks using functions contained
144 // in fns.
145 //
146 // Each function in fns has to be a function with the following
147 // possible signatures:
148 //
149 // func (got A) B
150 // func (got A) (B, error)
151 //
152 // A cannot be an interface. This retriction can be removed in the
153 // future, if really needed.
154 //
155 // B can be an interface.
156 //
157 // It returns an error if an item of fns is not a function or if its
158 // signature does not match the expected ones.
159 func (i *Info) AddSmuggleHooks(fns []any) error {
160 for n, fn := range fns {
161 vfn := reflect.ValueOf(fn)
162
163 if vfn.Kind() != reflect.Func {
164 return fmt.Errorf("expects a function, not a %s (@%d)", vfn.Kind(), n)
165 }
166
167 ft := vfn.Type()
168 if !ft.IsVariadic() &&
169 ft.NumIn() == 1 &&
170 ft.In(0).Kind() != reflect.Interface &&
171 (ft.NumOut() == 1 || (ft.NumOut() == 2 && ft.Out(1) == types.Error)) {
172 i.Lock()
173 prop := i.props[ft.In(0)]
174 prop.smuggle = vfn
175 i.props[ft.In(0)] = prop
176 i.Unlock()
177 continue
178 }
179
180 return fmt.Errorf("expects: func (A) (B[, error]) not %s (@%d)", ft, n)
181 }
182 return nil
183 }
184
185 // Smuggle checks if a Smuggle hook exists matching *got type.
186 //
187 // If no, it returns (false, nil)
188 //
189 // If yes, it calls it and returns (true, nil) if it succeeds,
190 // (true, <an error>) if it fails.
191 func (i *Info) Smuggle(got *reflect.Value) (bool, error) {
192 if i == nil {
193 return false, nil
194 }
195
196 tg := got.Type()
197
198 i.Lock()
199 prop, ok := i.props[tg]
200 i.Unlock()
201 if !ok || !prop.smuggle.IsValid() {
202 return false, nil
203 }
204
205 res := prop.smuggle.Call([]reflect.Value{*got})
206 if len(res) == 2 {
207 if err, _ := res[1].Interface().(error); err != nil {
208 return true, err
209 }
210 }
211
212 *got = res[0]
213 return true, nil
214 }
215
216 // AddUseEqual records types of values contained in ts as using
217 // Equal method. ts can also contain [reflect.Type] instances.
218 func (i *Info) AddUseEqual(ts []any) error {
219 if len(ts) == 0 {
220 return nil
221 }
222 for n, typ := range ts {
223 t, ok := typ.(reflect.Type)
224 if !ok {
225 t = reflect.TypeOf(typ)
226 ts[n] = t
227 }
228
229 equal, ok := t.MethodByName("Equal")
230 if !ok {
231 return fmt.Errorf("expects type %s owns an Equal method (@%d)", t, n)
232 }
233
234 ft := equal.Type
235 if ft.IsVariadic() ||
236 ft.NumIn() != 2 ||
237 ft.NumOut() != 1 ||
238 !ft.In(0).AssignableTo(ft.In(1)) ||
239 ft.Out(0) != types.Bool {
240 return fmt.Errorf("expects type %[1]s Equal method signature be Equal(%[1]s) bool (@%[2]d)", t, n)
241 }
242 }
243
244 i.Lock()
245 defer i.Unlock()
246
247 for _, typ := range ts {
248 t := typ.(reflect.Type)
249 prop := i.props[t]
250 prop.useEqual = true
251 i.props[t] = prop
252 }
253 return nil
254 }
255
256 // UseEqual returns true if the type t needs to use its Equal method
257 // to be compared.
258 func (i *Info) UseEqual(t reflect.Type) bool {
259 if i == nil {
260 return false
261 }
262
263 i.Lock()
264 defer i.Unlock()
265 return i.props[t].useEqual
266 }
267
268 // AddIgnoreUnexported records types of values contained in ts as ignoring
269 // unexported struct fields. ts can also contain [reflect.Type] instances.
270 func (i *Info) AddIgnoreUnexported(ts []any) error {
271 if len(ts) == 0 {
272 return nil
273 }
274 for n, typ := range ts {
275 t, ok := typ.(reflect.Type)
276 if !ok {
277 t = reflect.TypeOf(typ)
278 ts[n] = t
279 }
280
281 if t.Kind() != reflect.Struct {
282 return fmt.Errorf("expects type %s be a struct, not a %s (@%d)", t, t.Kind(), n)
283 }
284 }
285
286 i.Lock()
287 defer i.Unlock()
288
289 for _, typ := range ts {
290 t := typ.(reflect.Type)
291 prop := i.props[t]
292 prop.ignoreUnexported = true
293 i.props[t] = prop
294 }
295 return nil
296 }
297
298 // IgnoreUnexported returns true if the unexported fields of the type
299 // t have to be ignored.
300 func (i *Info) IgnoreUnexported(t reflect.Type) bool {
301 if i == nil {
302 return false
303 }
304
305 i.Lock()
306 defer i.Unlock()
307 return i.props[t].ignoreUnexported
308 }