-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
253 lines (216 loc) · 7.16 KB
/
result.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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package dig
import (
"fmt"
"reflect"
)
// The result interface represents a result produced by a constructor.
//
// The following implementations exist:
// resultList All values returned by the constructor.
// resultSingle An explicitly requested type.
// resultError An error returned by the constructor.
// resultObject dig.Out struct where each field in the struct can be
// another result.
type result interface {
// Extracts the values for this result from the provided value and
// stores them in the container.
//
// This MAY panic if the result does not consume a single value.
Extract(*Container, reflect.Value) error
Produces() map[key]struct{}
}
var (
_ result = resultSingle{}
_ result = resultError{}
_ result = resultObject{}
_ result = resultList{}
)
// newResult builds a result from the given type.
func newResult(t reflect.Type) (result, error) {
switch {
case IsIn(t) || (t.Kind() == reflect.Ptr && IsIn(t.Elem())) || embedsType(t, _inPtrType):
return nil, fmt.Errorf("cannot provide parameter objects: %v embeds a dig.In", t)
case isError(t):
return resultError{}, nil
case IsOut(t):
return newResultObject(t)
case embedsType(t, _outPtrType):
return nil, fmt.Errorf(
"cannot build a result object by embedding *dig.Out, embed dig.Out instead: "+
"%v embeds *dig.Out", t)
case t.Kind() == reflect.Ptr && IsOut(t.Elem()):
return nil, fmt.Errorf(
"cannot return a pointer to a result object, use a value instead: "+
"%v is a pointer to a struct that embeds dig.Out", t)
default:
return resultSingle{Type: t}, nil
}
}
// resultList holds all values returned by the constructor as results.
type resultList struct {
ctype reflect.Type
produces map[key]struct{}
Results []result
}
func newResultList(ctype reflect.Type) (resultList, error) {
rl := resultList{
ctype: ctype,
Results: make([]result, ctype.NumOut()),
produces: make(map[key]struct{}),
}
for i := 0; i < ctype.NumOut(); i++ {
r, err := newResult(ctype.Out(i))
if err != nil {
return rl, errWrapf(err, "bad result %d", i+1)
}
rl.Results[i] = r
for k := range r.Produces() {
if _, ok := rl.produces[k]; ok {
return rl, fmt.Errorf("returns multiple %v", k)
}
rl.produces[k] = struct{}{}
}
}
if len(rl.produces) == 0 {
return rl, fmt.Errorf("%v must provide at least one non-error type", ctype)
}
return rl, nil
}
func (rl resultList) Produces() map[key]struct{} { return rl.produces }
func (resultList) Extract(*Container, reflect.Value) error {
panic("It looks like you have found a bug in dig. " +
"Please file an issue at https://github.com/uber-go/dig/issues/ " +
"and provide the following message: " +
"resultList.Extract() must never be called")
}
func (rl resultList) ExtractList(c *Container, values []reflect.Value) error {
for i, r := range rl.Results {
if err := r.Extract(c, values[i]); err != nil {
return err
}
}
return nil
}
// resultError is an error returned by a constructor.
type resultError struct{}
// resultError doesn't produce anything
func (resultError) Produces() map[key]struct{} { return nil }
func (resultError) Extract(_ *Container, v reflect.Value) error {
err, _ := v.Interface().(error)
return err
}
// resultSingle is an explicit value produced by a constructor, optionally
// with a name.
//
// This object will be added to the graph as-is.
type resultSingle struct {
Name string
Type reflect.Type
}
func (rs resultSingle) Produces() map[key]struct{} {
return map[key]struct{}{
{name: rs.Name, t: rs.Type}: {},
}
}
func (rs resultSingle) Extract(c *Container, v reflect.Value) error {
c.cache[key{name: rs.Name, t: rs.Type}] = v
return nil
}
// resultObjectField is a single field inside a dig.Out struct.
type resultObjectField struct {
// Name of the field in the struct.
FieldName string
// Index of the field in the struct.
//
// We need to track this separately because not all fields of the struct
// map to results.
FieldIndex int
// Result produced by this field.
Result result
}
// resultObject is a dig.Out struct where each field is another result.
//
// This object is not added to the graph. Its fields are interpreted as
// results and added to the graph if needed.
type resultObject struct {
produces map[key]struct{}
Type reflect.Type
Fields []resultObjectField
}
func newResultObject(t reflect.Type) (resultObject, error) {
ro := resultObject{Type: t, produces: make(map[key]struct{})}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Type == _outType {
// Skip over the dig.Out embed.
continue
}
if f.PkgPath != "" {
return ro, fmt.Errorf(
"unexported fields not allowed in dig.Out, did you mean to export %q (%v) from %v?",
f.Name, f.Type, t)
}
if isError(f.Type) {
return ro, fmt.Errorf(
"cannot return errors from dig.Out, return it from the constructor instead: "+
"field %q (%v) of %v is an error field",
f.Name, f.Type, t)
}
r, err := newResult(f.Type)
if err != nil {
return ro, errWrapf(err, "bad field %q of %v", f.Name, t)
}
name := f.Tag.Get(_nameTag)
if rs, ok := r.(resultSingle); ok {
// field tags apply only if the result is "simple"
rs.Name = name
r = rs
}
for k := range r.Produces() {
if _, ok := ro.produces[k]; ok {
return ro, fmt.Errorf("returns multiple %v", k)
}
ro.produces[k] = struct{}{}
}
ro.Fields = append(ro.Fields, resultObjectField{
FieldName: f.Name,
FieldIndex: i,
Result: r,
})
}
return ro, nil
}
func (ro resultObject) Produces() map[key]struct{} { return ro.produces }
func (ro resultObject) Extract(c *Container, v reflect.Value) error {
for _, f := range ro.Fields {
if err := f.Result.Extract(c, v.Field(f.FieldIndex)); err != nil {
// In reality, this will never fail because none of the fields of
// a resultObject can be resultError.
panic(fmt.Sprintf(
"It looks like you have found a bug in dig. "+
"Please file an issue at https://github.com/uber-go/dig/issues/ "+
"and provide the following message: "+
"result.Extract() encountered an error: %v", err))
}
}
return nil
}