-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathvalue_set.go
590 lines (493 loc) · 15 KB
/
value_set.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package argmapper
import (
"fmt"
"reflect"
"strings"
"github.com/hashicorp/go-argmapper/internal/graph"
)
//go:generate stringer -type=ValueKind
// ValueSet tracks the values either accepted or returned as part of
// a function or converter.
//
// Internally, argmapper converts all functions to a signature of
// `func(Struct) (Struct, error)`. This lets the internals simplify a lot
// by expecting to only set struct fields. On the edges (when calling functions
// or returning values) we convert to and from the true expected arguments.
type ValueSet struct {
// structType is a struct that contains all the settable values.
structType reflect.Type
// structPointers is the number of pointers that wrap structType.
// We use this to construct the correct argument type. Note we only
// support one pointer today, so this will be at most "1" but making it
// an int for the future.
structPointers uint8
// values is the set of values that this ValueSet contains. namedValues,
// typedValues, etc. are convenience maps for looking up values more
// easily.
values []*Value
namedValues map[string]*Value
typedValues map[reflect.Type]*Value
// isLifted is if this represents a lifted struct. A lifted struct
// is one where we automatically converted flat argument lists to
// structs.
isLifted bool
}
// Value represents an input or output of a Func. In normal operation, you
// do not need to interact with Value objects directly. This structure
// is exposed for users who are trying to introspect on functions or manually
// build functions. This is an advanced operation.
//
// A Value represents multiple types of values depending on what fields are
// set. Please read the documentation carefully and use the exported methods
// to assist with checking value types.
type Value struct {
// valueInternal is the internal information for the value. This is only
// set and used by ValueSet.
valueInternal
// Name is the name of the value. This may be empty if this is a type-only
// value. If the name is set, then we will satisfy this input with an arg
// with this name and type.
Name string
// Type is the type of the value. This must be set.
Type reflect.Type
// Subtype is a key that specifies a unique "subtype" for the type.
// This can be used to identify dynamic values such as protobuf Any types
// where the full type isn't available. This is optional. For full details
// on subtype matching see the package docs.
Subtype string
// Value is the known value. This is only ever set if using Func.Redefine
// with an input that was given. Otherwise, this value is invalid.
Value reflect.Value
}
// ValueKind is returned by Value.Kind to designate what kind of value this is:
// a value expecting a type and name, a value with just type matching, etc.
type ValueKind uint
const (
ValueInvalid ValueKind = iota
ValueNamed
ValueTyped
)
type valueInternal struct {
// index is the struct field index for the ValueSet on which to set values.
index int
}
// NewValueSet creates a ValueSet from a list of expected values.
//
// This is primarily used alongside BuildFunc to dynamically build a Func.
func NewValueSet(vs []Value) (*ValueSet, error) {
// Build a dynamic struct based on the value list. The struct is
// only used for input/output mapping.
var sf []reflect.StructField
sf = append(sf, reflect.StructField{
Name: "Struct",
Type: structMarkerType,
Anonymous: true,
})
for i, v := range vs {
if isStruct(v.Type) {
return nil, fmt.Errorf("can't have argmapper.Struct values with custom ValueSet building")
}
// TODO(mitchellh): error on duplicate names, types
// Build our tag.
tags := []string{""}
if v.Name == "" {
tags = append(tags, "typeOnly")
}
if v.Subtype != "" {
tags = append(tags, fmt.Sprintf("subtype=%s", v.Subtype))
}
tag := reflect.StructTag(fmt.Sprintf(`argmapper:"%s"`, strings.Join(tags, ",")))
switch v.Kind() {
case ValueNamed:
sf = append(sf, reflect.StructField{
Name: strings.ToUpper(v.Name),
Type: v.Type,
Tag: tag,
})
case ValueTyped:
sf = append(sf, reflect.StructField{
Name: fmt.Sprintf("V__Type_%d", i),
Type: v.Type,
Tag: tag,
})
default:
panic("unknown kind")
}
}
return newValueSetFromStruct(reflect.StructOf(sf))
}
func newValueSet(count int, get func(int) reflect.Type) (*ValueSet, error) {
// If there are no arguments, then return an empty value set.
if count == 0 {
return &ValueSet{}, nil
}
// If we have exactly one argument, let's check if its a struct. If
// it is then we treat it as the full value.
if count == 1 {
if t := get(0); isStruct(t) {
return newValueSetFromStruct(t)
}
}
// We need to lift the arguments into a "struct".
var sf []reflect.StructField
for i := 0; i < count; i++ {
t := get(i)
if isStruct(t) {
return nil, fmt.Errorf("can't mix argmapper.Struct and non-struct values")
}
sf = append(sf, reflect.StructField{
Name: fmt.Sprintf("V__Type_%d", i),
Type: t,
Tag: reflect.StructTag(`argmapper:",typeOnly"`),
})
}
t, err := newValueSetFromStruct(reflect.StructOf(sf))
if err != nil {
return nil, err
}
t.isLifted = true
return t, nil
}
func newValueSetFromStruct(typ reflect.Type) (*ValueSet, error) {
// Unwrap any pointers around our struct type and count the number of
// pointer derefs. We need to know the count to reconstruct it later.
var ptrCount uint8
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
ptrCount++
}
if ptrCount > 1 {
return nil, fmt.Errorf("struct argument can at most be a single pointer")
}
// Verify our value is a struct
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("struct expected, got %s", typ.Kind())
}
// We will accumulate our results here
result := &ValueSet{
structType: typ,
structPointers: ptrCount,
values: []*Value{},
namedValues: map[string]*Value{},
typedValues: map[reflect.Type]*Value{},
}
// Go through the fields and record them all
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
// Ignore unexported fields and our struct marker
if sf.PkgPath != "" || isStructField(sf) {
continue
}
// name is the name of the value to inject.
name := sf.Name
// Parse out the tag if there is one
var options map[string]string
if tag := sf.Tag.Get("argmapper"); tag != "" {
parts := strings.Split(tag, ",")
// If we have a name set, then override the name
if parts[0] != "" {
name = parts[0]
}
// If we have fields set after the comma, then we want to
// parse those as values.
options = make(map[string]string)
for _, v := range parts[1:] {
idx := strings.Index(v, "=")
if idx == -1 {
options[v] = ""
} else {
options[v[:idx]] = v[idx+1:]
}
}
}
// Name is always lowercase
name = strings.ToLower(name)
if _, ok := options["typeOnly"]; ok {
name = ""
}
// Record it
value := Value{
Name: name,
Type: sf.Type,
Subtype: options["subtype"],
valueInternal: valueInternal{
index: i,
},
}
result.values = append(result.values, &value)
switch value.Kind() {
case ValueNamed:
result.namedValues[value.Name] = &value
case ValueTyped:
result.typedValues[value.Type] = &value
}
}
return result, nil
}
// Values returns the values in this ValueSet. This does not return
// pointers so any modifications to the values will not impact any values
// in this set. Please call Named, Typed, etc. directly to make modifications.
func (vs *ValueSet) Values() []Value {
result := make([]Value, len(vs.values))
for i, v := range vs.values {
result[i] = *v
}
return result
}
// Args returns all of the values in this ValueSet as a slice of Arg to
// make it easier to pass to Call. This is equivalent to iterating over
// the Values result and accumulating Arg results.
func (vs *ValueSet) Args() []Arg {
vals := vs.Values()
args := make([]Arg, len(vals))
for i, v := range vals {
args[i] = v.Arg()
}
return args
}
// Named returns a pointer to the value with the given name, or nil if
// it doesn't exist.
func (vs *ValueSet) Named(n string) *Value {
return vs.namedValues[n]
}
// Typed returns a pointer to the value with the given type, or nil
// if it doesn't exist. If there is no typed value directly, a random
// type with the matching subtype will be chosen. If you want an exact
// match with no subtype, use TypedSubtype.
func (vs *ValueSet) Typed(t reflect.Type) *Value {
// TODO: subtype
return vs.typedValues[t]
}
// TypedSubtype returns a pointer to the value that matches the type
// and subtype exactly.
func (vs *ValueSet) TypedSubtype(t reflect.Type, st string) *Value {
for _, v := range vs.values {
if v.Type == t && v.Subtype == st {
return v
}
}
return nil
}
// Signature returns the type signature that this ValueSet will map to/from.
// This is used for making dynamic types with reflect.FuncOf to take or return
// this valueset.
func (vs *ValueSet) Signature() []reflect.Type {
// If our value set is nil then we have no arguments.
if vs == nil {
return nil
}
if !vs.lifted() {
// This happens if the value has no values at all. In this case,
// our signature is also empty.
if vs.structType == nil {
return nil
}
return []reflect.Type{vs.structType}
}
result := make([]reflect.Type, len(vs.typedValues))
for _, v := range vs.typedValues {
result[v.index] = v.Type
}
return result
}
// SignatureValues returns the values that match the Signature type list,
// based on the values set in this set. If a value isn't set, the zero
// value is used.
func (vs *ValueSet) SignatureValues() []reflect.Value {
// If typ is nil then there is no values
if vs == nil || vs.structType == nil {
return nil
}
// If we're lifted, we just return directly based on values
if vs.lifted() {
result := make([]reflect.Value, len(vs.typedValues))
for _, v := range vs.typedValues {
result[v.index] = v.valueOrZero()
}
return result
}
// Not lifted, meaning we return a struct
structOut := reflect.New(vs.structType).Elem()
for _, f := range vs.values {
structOut.Field(f.index).Set(f.valueOrZero())
}
return []reflect.Value{structOut}
}
// FromSignature sets the values in this ValueSet based on the values list.
// The values list must match the type signature returned from vs.Signature.
// This usually comes from calling a function directly.
func (vs *ValueSet) FromSignature(values []reflect.Value) error {
// If we're lifted, then first set the values onto the struct.
if vs.lifted() {
// If we are lifted, then we need to translate the output arguments
// to their proper types in a struct.
structOut := reflect.New(vs.structType).Elem()
for _, f := range vs.typedValues {
structOut.Field(f.index).Set(values[f.index])
}
values = []reflect.Value{structOut}
}
// Get our first result which should be our struct
structVal := values[0]
for i, v := range vs.values {
vs.values[i].Value = structVal.Field(v.index)
}
return nil
}
// FromResult sets the values in this set based on a Result. This will
// return an error if the result represents an error.
func (vs *ValueSet) FromResult(r Result) error {
if err := r.Err(); err != nil {
return err
}
return vs.FromSignature(r.out)
}
// New returns a new structValue that can be used for value population.
func (t *ValueSet) newStructValue() *structValue {
result := &structValue{typ: t}
if t.structType != nil {
result.value = reflect.New(t.structType).Elem()
}
return result
}
// lifted returns true if this field is lifted.
func (t *ValueSet) lifted() bool {
return t.isLifted
}
func (t *ValueSet) empty() bool {
return t.structType == nil || len(t.values) == 0
}
// result takes the result that matches this struct type and adapts it
// if necessary (if the struct type is lifted or so on).
func (t *ValueSet) result(r Result) Result {
// If we aren't lifted, we return the direct struct. We have to unwrap
// any pointers. We know this to be true already since we analyzed the
// function earlier.
if !t.lifted() {
for i := uint8(0); i < t.structPointers; i++ {
r.out[0] = r.out[0].Elem()
}
// A nil result is equivalent to zero values, allocate the struct.
// This happens if there are pointer results and the user returns nil.
if !r.out[0].IsValid() {
r.out[0] = reflect.New(t.structType).Elem()
}
return r
}
// If we are lifted, then we need to translate the output arguments
// to their proper types in a struct.
structOut := reflect.New(t.structType).Elem()
for _, f := range t.typedValues {
structOut.Field(f.index).Set(r.out[f.index])
}
r.out = []reflect.Value{structOut}
return r
}
func newValueFromVertex(v graph.Vertex) *Value {
switch v := v.(type) {
case *valueVertex:
return &Value{
Name: v.Name,
Type: v.Type,
Subtype: v.Subtype,
Value: v.Value,
}
case *typedOutputVertex:
return &Value{
Type: v.Type,
Subtype: v.Subtype,
Value: v.Value,
}
}
return nil
}
// Arg returns an Arg that can be used with Func.Call to send this value.
// This only works if the Value's Value field is set.
func (v *Value) Arg() Arg {
switch v.Kind() {
case ValueNamed:
return NamedSubtype(v.Name, v.Value.Interface(), v.Subtype)
case ValueTyped:
return TypedSubtype(v.Value.Interface(), v.Subtype)
default:
panic("unknown kind: " + v.Kind().String())
}
}
// Kind returns the ValueKind that this Value represents.
func (v *Value) Kind() ValueKind {
if v.Name != "" {
return ValueNamed
}
return ValueTyped
}
func (v *Value) String() string {
switch v.Kind() {
case ValueNamed:
if v.Subtype == "" {
return fmt.Sprintf("name: %q (type: %s)", v.Name, v.Type)
} else {
return fmt.Sprintf("name: %q (type: %s, subtype: %s)", v.Name, v.Type, v.Subtype)
}
case ValueTyped:
if v.Subtype == "" {
return fmt.Sprintf("type: %s", v.Type)
} else {
return fmt.Sprintf("type: %s (subtype: %s)", v.Type, v.Subtype)
}
default:
return fmt.Sprintf("%#v", v)
}
}
func (v *Value) valueOrZero() reflect.Value {
if !v.Value.IsValid() {
return reflect.Zero(v.Type)
}
return v.Value
}
func (v *Value) vertex() graph.Vertex {
switch v.Kind() {
case ValueNamed:
return &valueVertex{
Name: v.Name,
Type: v.Type,
Subtype: v.Subtype,
}
case ValueTyped:
return &typedArgVertex{
Type: v.Type,
Subtype: v.Subtype,
}
default:
panic(fmt.Sprintf("unknown value kind: %s", v.Kind()))
}
}
type structValue struct {
typ *ValueSet
value reflect.Value
}
func (v *structValue) Field(idx int) reflect.Value {
return v.value.Field(idx)
}
func (v *structValue) CallIn() []reflect.Value {
// If typ is nil then there is no inputs
if v.typ.structType == nil {
return nil
}
// If this is not lifted, return it as-is.
if !v.typ.lifted() {
// We do need to wrap the value in some pointers
val := v.value
for i := uint8(0); i < v.typ.structPointers; i++ {
val = val.Addr()
}
return []reflect.Value{val}
}
// This is lifted, so we need to unpack them in order.
result := make([]reflect.Value, len(v.typ.typedValues))
for _, f := range v.typ.typedValues {
result[f.index] = v.value.Field(f.index)
}
return result
}