-
Notifications
You must be signed in to change notification settings - Fork 2
/
nject.go
386 lines (355 loc) · 9.25 KB
/
nject.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
package nject
import (
"errors"
"fmt"
"reflect"
"strings"
"sync/atomic"
)
var idCounter int32
// provider is an annotated reference to a provider
//
//nolint:recvcheck // some provider methods use a pointer, some do not
type provider struct {
origin string
index int
fn interface{}
id int32
// user annotations (match these in debug.go)
nonFinal bool
cacheable bool
mustCache bool
required bool
callsInner bool
memoize bool
loose bool
reorder bool
overridesError bool
desired bool
shun bool
notCacheable bool
mustConsume bool
consumptionOptional bool
singleton bool
cluster int32
parallel bool
replaceByName string
insertBeforeName string
insertAfterName string
// added by characterize
memoized bool
class classType
group groupType
flows flowMapType
isSynthetic bool
mapKeyCheck func([]reflect.Value) bool
// added during include calculations
cannotInclude error
wanted bool
whyIncluded string
upRmap map[typeCode]typeCode // overrides types of returned parameters
downRmap map[typeCode]typeCode // overrides types of input parameters
bypassRmap map[typeCode]typeCode // overrides types of returning parameters
include bool
d includeWorkingData
chainPosition int
// added during binding
mustZeroIfRemainderSkipped []typeCode
mustZeroIfInnerNotCalled []typeCode
vmapCount int
// added when generating
wrapWrapper func(valueCollection, func(valueCollection)) // added in generate
wrapStaticInjector func(valueCollection) error // added in generate
wrapFallibleInjector func(valueCollection) bool // added in generate
wrapEndpoint func(valueCollection) // added in generate
}
// copy does not copy wrappers or flows.
// It only copies the base, user annotations, and characterize annotations;
// it does not not copy include calculations, binding, or generating.
func (fm *provider) copy() *provider {
if fm == nil {
return nil
}
return &provider{
origin: fm.origin,
index: fm.index,
fn: fm.fn,
id: fm.id,
nonFinal: fm.nonFinal,
cacheable: fm.cacheable,
mustCache: fm.mustCache,
required: fm.required,
callsInner: fm.callsInner,
memoize: fm.memoize,
loose: fm.loose,
reorder: fm.reorder,
overridesError: fm.overridesError,
desired: fm.desired,
shun: fm.shun,
notCacheable: fm.notCacheable,
mustConsume: fm.mustConsume,
consumptionOptional: fm.consumptionOptional,
singleton: fm.singleton,
cluster: fm.cluster,
parallel: fm.parallel,
memoized: fm.memoized,
class: fm.class,
group: fm.group,
flows: fm.flows,
isSynthetic: fm.isSynthetic,
mapKeyCheck: fm.mapKeyCheck,
replaceByName: fm.replaceByName,
insertBeforeName: fm.insertBeforeName,
insertAfterName: fm.insertAfterName,
}
}
type thing interface {
modify(func(*provider)) thing
flatten() []*provider
DownFlows() (inputs []reflect.Type, outputs []reflect.Type)
UpFlows() (consume []reflect.Type, produce []reflect.Type)
String() string
}
func newThing(fn interface{}) thing {
switch v := fn.(type) {
case *provider:
return v
case provider:
return v
case *Collection:
return v
case Collection:
return v
default:
return newProvider(fn, -1, "")
}
}
func newProvider(fn interface{}, index int, origin string) *provider {
if fn == nil {
return nil
}
if fm, isFuncO := fn.(*provider); isFuncO {
return fm.copy()
}
if c, isCollection := fn.(*Collection); isCollection {
if len(c.contents) == 1 {
return newProvider(c.contents[0], index, origin)
}
panic("Cannot turn Collection into a function")
}
return &provider{
origin: origin,
index: index,
fn: fn,
id: atomic.AddInt32(&idCounter, 1),
}
}
func (fm provider) String() string {
t := func() string {
if fm.fn == nil {
return "nil"
}
if _, ok := fm.fn.(Reflective); ok {
if s, ok := fm.fn.(fmt.Stringer); ok {
return s.String()
}
}
return reflect.TypeOf(fm.fn).String()
}()
class := ""
if fm.class != unsetClassType {
class = fm.class.String() + ": "
}
if fm.index >= 0 {
return fmt.Sprintf("%s%s(%d) [%s]", class, fm.origin, fm.index, t)
}
return fmt.Sprintf("%s%s [%s]", class, fm.origin, t)
}
func (fm provider) errorf(format string, args ...interface{}) error {
return errors.New(fm.String() + ": " + fmt.Sprintf(format, args...))
}
// This characterizes all the providers and flattens the collection into
// a couple of lists of providers: providers that run before invoke; and
// providers that run after invoke.
func (c Collection) characterizeAndFlatten(nonStaticTypes map[typeCode]bool) ([]*provider, []*provider, error) {
debugln("BEGIN characterizeAndFlatten")
defer debugln("END characterizeAndFlatten")
afterInit := make([]*provider, 0, len(c.contents))
afterInvoke := make([]*provider, 0, len(c.contents))
err := c.handleReplaceByName()
if err != nil {
return nil, nil, err
}
c.reorderNonFinal()
// Handle mutations
var mutated bool
for i := 0; i < len(c.contents); i++ {
fm := c.contents[i]
g, ok := fm.fn.(generatedFromInjectionChain)
if !ok {
continue
}
replacement, err := g.ReplaceSelf(
Collection{
name: "before",
contents: c.contents[:i],
},
Collection{
name: "after",
contents: c.contents[i+1:],
})
if err != nil {
return nil, nil, err
}
flat := replacement.flatten()
if len(flat) == 1 {
c.contents[i] = flat[0]
} else {
n := make([]*provider, 0, len(c.contents)+len(flat)-1)
n = append(n, c.contents[:i]...)
n = append(n, flat...)
n = append(n, c.contents[i+1:]...)
c.contents = n
}
}
if mutated {
c.reorderNonFinal()
}
for ii, fm := range c.contents {
cc := charContext{
isLast: ii == len(c.contents)-1,
inputsAreStatic: true,
}
var err error
fm, err = characterizeFunc(fm, cc)
if err != nil {
return nil, nil, err
}
if fm.group == staticGroup {
for _, in := range fm.flows[inputParams] {
if nonStaticTypes[in] {
cc.inputsAreStatic = false
fm, err = characterizeFunc(fm, cc)
if err != nil {
return nil, nil, err
}
break
}
}
}
// nolint:exhaustive
switch fm.group {
case runGroup, invokeGroup:
for _, out := range fm.flows[outputParams] {
nonStaticTypes[out] = true
}
}
// nolint:exhaustive
switch fm.group {
case staticGroup, literalGroup:
afterInit = append(afterInit, fm)
case finalGroup, runGroup:
afterInvoke = append(afterInvoke, fm)
default:
return nil, nil, fmt.Errorf("internal error: not expecting %s group", fm.group)
}
}
return afterInit, afterInvoke, nil
}
func newCollection(name string, funcs ...interface{}) *Collection {
var contents []*provider
for i, fn := range funcs {
if fn == nil {
continue
}
switch v := fn.(type) {
case *Collection:
if v != nil {
contents = append(contents, v.contents...)
}
case Collection:
contents = append(contents, v.contents...)
case *provider:
if v != nil {
contents = append(contents, v.renameIfEmpty(i, name))
}
case provider:
contents = append(contents, v.renameIfEmpty(i, name))
default:
contents = append(contents, newProvider(fn, i, name))
}
}
return &Collection{
name: name,
contents: contents,
}
}
func (c Collection) String() string {
return c.string("")
}
func (c Collection) string(indent string) string {
var buf strings.Builder
_, _ = buf.WriteString(indent + c.name + ":\n")
for _, fm := range c.contents {
if s, ok := fm.fn.(interface{ String() string }); ok {
_, _ = buf.WriteString(indent + s.String())
} else {
_, _ = buf.WriteString(fmt.Sprintf("%s %T\n", indent, fm.fn))
}
}
return buf.String()
}
func (fm provider) renameIfEmpty(i int, name string) *provider {
if fm.origin == "" {
nfm := fm.copy()
nfm.origin = name
if nfm.index == -1 {
nfm.index = i
}
return nfm
}
return &fm
}
func (fm provider) flatten() []*provider {
return []*provider{&fm}
}
func (c Collection) flatten() []*provider {
return c.contents
}
func (fm provider) modify(f func(*provider)) thing {
nfm := fm.copy()
f(nfm)
return nfm
}
func (c Collection) modify(f func(*provider)) thing {
n := make([]*provider, len(c.contents))
for i, fm := range c.contents {
fm = fm.copy()
f(fm)
n[i] = fm
}
return &Collection{
name: c.name,
contents: n,
}
}
// Reorder collection to handle providers marked nonFinal by shifting
// the last provider that isn't marked nonFinal to the end of the slice.
func (c Collection) reorderNonFinal() {
for i := len(c.contents) - 1; i >= 0; i-- {
fm := c.contents[i]
if fm.nonFinal {
continue
}
if i == len(c.contents)-1 {
// no re-ordering required
return
}
final := c.contents[i]
for j := i; j < len(c.contents)-1; j++ {
c.contents[j] = c.contents[j+1]
}
c.contents[len(c.contents)-1] = final
return
}
}