-
Notifications
You must be signed in to change notification settings - Fork 2
/
characterize.go
600 lines (556 loc) · 15 KB
/
characterize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package nject
import (
"fmt"
"reflect"
"strings"
"github.com/muir/reflectutils"
)
type charContext struct {
isLast bool
inputsAreStatic bool
}
type flowMapType [lastFlowType]typeCodes
type characterization struct {
name string
tests predicates
mutate func(testArgs)
}
type typeRegistry []characterization
type testArgs struct {
cc charContext
fm *provider
t reflectType
isNil bool
}
type predicateType struct {
message string
test func(a testArgs) bool
}
type predicates []predicateType
func hasAnonymousFuncs(params []reflect.Type, ignoreFirst bool) bool {
for i, in := range params {
if in.Kind() == reflect.Func && in.Name() == "" && !(i == 0 && ignoreFirst) {
return true
}
}
return false
}
func typesIn(t reflectType) []reflect.Type {
if t.Kind() != reflect.Func {
return nil
}
in := make([]reflect.Type, t.NumIn())
for i := 0; i < t.NumIn(); i++ {
in[i] = t.In(i)
}
return in
}
func typesOut(t reflectType) []reflect.Type {
if t.Kind() != reflect.Func {
return nil
}
out := make([]reflect.Type, t.NumOut())
for i := 0; i < t.NumOut(); i++ {
out[i] = t.Out(i)
}
return out
}
func remapTerminalError(in []reflect.Type) []reflect.Type {
out := make([]reflect.Type, len(in))
for i, t := range in {
if t == terminalErrorType {
t = errorType
}
out[i] = t
}
return out
}
func redactTerminalError(in []reflect.Type) []reflect.Type {
var out []reflect.Type
for _, t := range in {
if t == terminalErrorType {
continue
}
out = append(out, t)
}
return out
}
func toTypeCodes(in []reflect.Type) []typeCode {
out := make([]typeCode, len(in))
for i, t := range in {
out[i] = getTypeCode(t)
}
return out
}
func mappable(inputs ...reflect.Type) bool {
ok := true
for _, in := range inputs {
// nolint:exhaustive
switch in.Kind() {
case reflect.Map, reflect.Slice, reflect.Func:
ok = false
case reflect.Array:
ok = mappable(in.Elem())
case reflect.Struct:
fa := make([]reflect.Type, 0, in.NumField())
reflectutils.WalkStructElements(in, func(f reflect.StructField) bool {
fa = append(fa, f.Type)
return true
})
ok = mappable(fa...)
}
if !ok {
break
}
}
return ok
}
// predicate tests a provider. The message is used when the provider
// fails that test so the message should be the opposite of what the
// provider does.
func predicate(message string, test func(a testArgs) bool) predicateType {
return predicateType{
message: message,
test: test,
}
}
var (
notNil = predicate("is nil", func(a testArgs) bool { return !a.isNil })
notFunc = predicate("is a function", func(a testArgs) bool { return a.t.Kind() != reflect.Func })
isFunc = predicate("is not a function", func(a testArgs) bool { return a.t.Kind() == reflect.Func })
isLast = predicate("is not the final item in the provider chain", func(a testArgs) bool { return a.cc.isLast })
notLast = predicate("must not be last", func(a testArgs) bool { return !a.cc.isLast })
unstaticOkay = predicate("is marked MustCache", func(a testArgs) bool { return !a.fm.mustCache })
inStatic = predicate("is after invoke", func(a testArgs) bool { return a.cc.inputsAreStatic })
hasOutputs = predicate("does not have outputs", func(a testArgs) bool { return a.t.NumOut() != 0 })
mustNotMemoize = predicate("is marked Memoized", func(a testArgs) bool { return !a.fm.memoize })
markedMemoized = predicate("is not marked Memoized", func(a testArgs) bool { return a.fm.memoize })
markedCacheable = predicate("is not marked Cacheable", func(a testArgs) bool { return a.fm.cacheable })
markedSingleton = predicate("is not marked Singleton", func(a testArgs) bool { return a.fm.singleton })
notMarkedReorder = predicate("is marked Reorder", func(a testArgs) bool { return !a.fm.reorder })
notMarkedSingleton = predicate("is marked Singleton", func(a testArgs) bool { return !a.fm.singleton })
notMarkedNoCache = predicate("is marked NotCacheable", func(a testArgs) bool { return !a.fm.notCacheable })
mappableInputs = predicate("has inputs that cannot be map keys", func(a testArgs) bool { return mappable(typesIn(a.t)...) })
possibleMapKey = predicate("type is not cacheable", func(a testArgs) bool { p, _ := canBeMapKey(typesIn(a.t)); return p })
returnsTerminalError = predicate("does not return TerminalError", func(a testArgs) bool {
for _, out := range typesOut(a.t) {
if out == terminalErrorType {
return true
}
}
return false
})
)
var noAnonymousFuncs = predicate("has an untyped functional argument", func(a testArgs) bool {
if _, ok := a.fm.fn.(ReflectiveWrapper); ok {
return false
}
return !hasAnonymousFuncs(typesIn(a.t), false) &&
!hasAnonymousFuncs(typesOut(a.t), false)
})
var noAnonymousExceptFirstInput = predicate("has extra untyped functional arguments", func(a testArgs) bool {
return !hasAnonymousFuncs(typesIn(a.t), true) &&
!hasAnonymousFuncs(typesOut(a.t), false)
})
var hasInner = predicate("does not have an Inner function (untyped functional argument in the 1st position)", func(a testArgs) bool {
return isWrapper(a.t, a.fm.fn)
})
func isWrapper(t reflectType, fn interface{}) bool {
if _, ok := fn.(ReflectiveWrapper); ok {
return true
}
return t.Kind() == reflect.Func && t.NumIn() > 0 && t.In(0).Kind() == reflect.Func
}
var isFuncPointer = predicate("is not a pointer to a function", func(a testArgs) bool {
switch a.fm.fn.(type) {
case ReflectiveInvoker:
return true
case Reflective, ReflectiveArgs:
return false
default:
t := a.t
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func
}
})
var isNotFuncPointer = predicate("is a pointer to a function", func(a testArgs) bool {
return !isFuncPointer.test(a)
})
var invokeRegistry = typeRegistry{
{
name: "init func",
tests: predicates{
notNil,
inStatic,
isFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = invokeGroup
a.fm.class = initFunc
if _, ok := a.fm.fn.(ReflectiveInvoker); ok {
a.fm.flows[outputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[bypassParams] = toTypeCodes(typesOut(a.t))
} else {
a.fm.flows[outputParams] = toTypeCodes(typesIn(a.t.Elem()))
a.fm.flows[bypassParams] = toTypeCodes(typesOut(a.t.Elem()))
}
a.fm.required = true
a.fm.isSynthetic = true
},
},
{
name: "invoke func",
tests: predicates{
notNil,
isFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = invokeGroup
a.fm.class = invokeFunc
if _, ok := a.fm.fn.(ReflectiveInvoker); ok {
a.fm.flows[outputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[receivedParams] = toTypeCodes(typesOut(a.t))
} else {
a.fm.flows[outputParams] = toTypeCodes(typesIn(a.t.Elem()))
a.fm.flows[receivedParams] = toTypeCodes(typesOut(a.t.Elem()))
}
a.fm.required = true
a.fm.isSynthetic = true
},
},
}
var handlerRegistry = typeRegistry{
{
name: "literal value",
tests: predicates{
notFunc,
inStatic,
notLast,
},
mutate: func(a testArgs) {
a.fm.group = literalGroup
a.fm.class = literalValue
// the cast is safe because when the value is a Reflective, we look like
// like a func and this code only runs for non-funcs.
//nolint:errcheck // we know that a.t can convert to a reflect.Type
a.fm.flows[outputParams] = toTypeCodes([]reflect.Type{a.t.(reflect.Type)})
},
},
{
name: "fallable singleton injector",
tests: predicates{
markedSingleton,
isFunc,
inStatic,
markedCacheable,
noAnonymousFuncs,
returnsTerminalError,
notLast,
mappableInputs,
notMarkedNoCache,
mustNotMemoize,
notMarkedReorder,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = fallibleStaticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(remapTerminalError(typesOut(a.t)))
},
},
{
name: "singleton injector",
tests: predicates{
markedSingleton,
isFunc,
inStatic,
markedCacheable,
noAnonymousFuncs,
notLast,
mappableInputs,
notMarkedNoCache,
mustNotMemoize,
notMarkedReorder,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = staticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(remapTerminalError(typesOut(a.t)))
},
},
{
name: "fallible memoized static injector",
tests: predicates{
markedMemoized,
isFunc,
inStatic,
markedCacheable,
noAnonymousFuncs,
returnsTerminalError,
notLast,
mappableInputs,
notMarkedNoCache,
possibleMapKey,
notMarkedSingleton,
notMarkedReorder,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = fallibleStaticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(remapTerminalError(typesOut(a.t)))
a.fm.memoized = true
_, a.fm.mapKeyCheck = canBeMapKey(typesIn(a.t))
},
},
{
name: "static memoized injector",
tests: predicates{
isFunc,
markedMemoized,
markedCacheable,
inStatic,
notLast,
hasOutputs,
mappableInputs,
noAnonymousFuncs,
notMarkedNoCache,
possibleMapKey,
notMarkedSingleton,
notMarkedReorder,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = staticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(typesOut(a.t))
a.fm.memoized = true
_, a.fm.mapKeyCheck = canBeMapKey(typesIn(a.t))
},
},
{
name: "fallible static injector",
tests: predicates{
isFunc,
returnsTerminalError,
markedCacheable,
inStatic,
notLast,
noAnonymousFuncs,
mustNotMemoize,
notMarkedNoCache,
notMarkedSingleton,
notMarkedReorder,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = fallibleStaticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(remapTerminalError(typesOut(a.t)))
_, a.fm.mapKeyCheck = canBeMapKey(typesIn(a.t))
},
},
{
name: "fallible memoized injector",
tests: predicates{
isFunc,
noAnonymousFuncs,
returnsTerminalError,
notLast,
markedMemoized,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = runGroup
a.fm.class = fallibleInjectorFunc
a.fm.memoized = true
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(redactTerminalError(typesOut(a.t)))
a.fm.flows[returnParams] = toTypeCodes([]reflect.Type{errorType})
},
},
{
name: "fallible injector",
tests: predicates{
isFunc,
noAnonymousFuncs,
returnsTerminalError,
notLast,
mustNotMemoize,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = runGroup
a.fm.class = fallibleInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(redactTerminalError(typesOut(a.t)))
a.fm.flows[returnParams] = toTypeCodes([]reflect.Type{errorType})
},
},
{
name: "static injector",
tests: predicates{
isFunc,
markedCacheable,
inStatic,
noAnonymousFuncs,
notLast,
hasOutputs,
mustNotMemoize,
notMarkedNoCache,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = staticGroup
a.fm.class = staticInjectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(typesOut(a.t))
},
},
{
name: "memoized injector",
tests: predicates{
isFunc,
noAnonymousFuncs,
notLast,
markedMemoized,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = runGroup
a.fm.class = injectorFunc
a.fm.memoized = true
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(typesOut(a.t))
},
},
{
name: "injector",
tests: predicates{
isFunc,
noAnonymousFuncs,
notLast,
mustNotMemoize,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = runGroup
a.fm.class = injectorFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[outputParams] = toTypeCodes(typesOut(a.t))
},
},
{
name: "middleware/wrapper",
tests: predicates{
isFunc,
hasInner,
noAnonymousExceptFirstInput,
notLast,
mustNotMemoize,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
in := typesIn(a.t)
in[0] = reflect.TypeOf(noTypeExampleValue)
a.fm.group = runGroup
a.fm.class = wrapperFunc
a.fm.flows[inputParams] = toTypeCodes(in)
a.fm.flows[returnParams] = toTypeCodes(typesOut(a.t))
var inner reflectType
if w, ok := a.fm.fn.(ReflectiveWrapper); ok {
inner = wrappedReflective{w.Inner()}
} else {
inner = a.t.In(0)
}
a.fm.flows[outputParams] = toTypeCodes(typesIn(inner))
a.fm.flows[receivedParams] = toTypeCodes(typesOut(inner))
},
},
{
name: "final/last/endpoint func",
tests: predicates{
isFunc,
isLast,
noAnonymousFuncs,
mustNotMemoize,
unstaticOkay,
notMarkedSingleton,
isNotFuncPointer,
},
mutate: func(a testArgs) {
a.fm.group = finalGroup
a.fm.class = finalFunc
a.fm.flows[inputParams] = toTypeCodes(typesIn(a.t))
a.fm.flows[returnParams] = toTypeCodes(typesOut(a.t))
a.fm.required = true
},
},
}
// characterizeFuncDetails returns an annotated copy of the incoming *provider.
func (reg typeRegistry) characterizeFuncDetails(fm *provider, cc charContext) (*provider, error) {
var rejectReasons []string
var a testArgs
if r, ok := fm.fn.(ReflectiveArgs); ok {
a = testArgs{
fm: fm.copy(),
t: wrappedReflective{r},
isNil: false,
cc: cc,
}
} else {
v := reflect.ValueOf(fm.fn)
var isNil bool
// nolint:exhaustive
switch v.Type().Kind() {
case reflect.Chan, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
isNil = v.IsNil()
default:
isNil = false
}
a = testArgs{
fm: fm.copy(),
t: v.Type(),
cc: cc,
isNil: isNil,
}
}
Match:
for _, match := range reg {
for _, predicate := range match.tests {
if !predicate.test(a) {
rejectReasons = append(rejectReasons, fmt.Sprintf("%s: %s", match.name, predicate.message))
continue Match
}
}
a.fm.upRmap = make(map[typeCode]typeCode)
a.fm.downRmap = make(map[typeCode]typeCode)
a.fm.flows = [lastFlowType]typeCodes{}
match.mutate(a)
return a.fm, nil
}
// panic(fmt.Sprintf("%s: %s - %s", fm.describe(), t, strings.Join(rejectReasons, "; ")))
return nil, fm.errorf("Could not match type %s to any prototype: %s", a.t, strings.Join(rejectReasons, "; "))
}
func characterizeInitInvoke(fm *provider, context charContext) (*provider, error) {
return invokeRegistry.characterizeFuncDetails(fm, context)
}
func characterizeFunc(fm *provider, context charContext) (*provider, error) {
return handlerRegistry.characterizeFuncDetails(fm, context)
}