-
-
Notifications
You must be signed in to change notification settings - Fork 314
/
value.go
1382 lines (1175 loc) · 38.7 KB
/
value.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Mgmt
// Copyright (C) 2013-2021+ James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package types
import (
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"github.com/purpleidea/mgmt/util/errwrap"
)
var (
// ErrNilValue is returned when ValueOf() attempts to represent a nil
// pointer as an mcl value. This is not supported in mcl.
ErrNilValue = errors.New("cannot represent a nil Golang value in mcl")
// ErrInvalidValue is returned when ValueOf() is called on an invalid or
// zero reflect.Value.
ErrInvalidValue = errors.New("cannot represent invalid reflect.Value")
)
// Value represents an interface to get values out of each type. It is similar
// to the reflection interfaces used in the golang standard library.
type Value interface {
fmt.Stringer // String() string (for display purposes)
Type() *Type
Less(Value) bool // to find the smaller of the two values (for sort)
Cmp(Value) error // error if the two values aren't the same
Copy() Value // returns a copy of this value
Value() interface{}
Bool() bool
Str() string
Int() int64
Float() float64
List() []Value
Map() map[Value]Value // keys must all have same type, same for values
Struct() map[string]Value
Func() func([]Value) (Value, error)
}
// ValueOfGolang is a helper that takes a golang value, and produces the mcl
// equivalent internal representation. This is very useful for writing tests. A
// reminder that if you pass in a nil value, or something containing a nil
// value, then you won't get what you want. See our documentation for ValueOf.
func ValueOfGolang(i interface{}) (Value, error) {
return ValueOf(reflect.ValueOf(i))
}
// ValueOf takes a reflect.Value and returns an equivalent Value. Remember that
// the mcl type system currently can't represent certain values that *are*
// possible in golang. This is intentional. For example, mcl can't represent a
// *string (pointer to a string) where as this is quite common in golang. This
// is because mcl has no `nil/null` values. It is designed this way to avoid the
// well-known expensive "null-pointer-exception" style bugs. A version two of
// the language might consider an "Optional" type. In the meantime, you can
// still represent an "undefined" value, but only so far as when it's passed to
// a resource field. This is done with our "elvis" operator. When using this
// function, if you pass in something with a nil value, then expect a panic or
// an error if you're lucky.
func ValueOf(v reflect.Value) (Value, error) {
// Gracefully handle invalid values instead of panic(). Invalid
// reflect.Value values can come from nil values, or the zero value.
if !v.IsValid() {
return nil, ErrInvalidValue
}
value := v
typ := value.Type()
kind := typ.Kind()
for kind == reflect.Ptr {
// Prevent panic() if value is a nil pointer and return an error.
if value.IsNil() {
return nil, ErrNilValue
}
typ = typ.Elem() // un-nest one pointer
kind = typ.Kind()
// un-nest value from pointer
value = value.Elem() // XXX: is this correct?
}
switch kind { // match on destination field kind
case reflect.Bool:
return &BoolValue{V: value.Bool()}, nil
case reflect.String:
return &StrValue{V: value.String()}, nil
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
return &IntValue{V: value.Int()}, nil
case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
return &IntValue{V: int64(value.Uint())}, nil
case reflect.Float64, reflect.Float32:
return &FloatValue{V: value.Float()}, nil
case reflect.Array, reflect.Slice:
values := []Value{}
for i := 0; i < value.Len(); i++ {
x := value.Index(i)
v, err := ValueOf(x) // recurse
if err != nil {
return nil, err
}
values = append(values, v)
}
t, err := TypeOf(value.Type().Elem()) // type of contents
if err != nil {
return nil, errwrap.Wrapf(err, "can't determine type of %+v", value)
}
return &ListValue{
T: NewType(fmt.Sprintf("[]%s", t.String())),
V: values,
}, nil
case reflect.Map:
m := make(map[Value]Value)
// loop through the list of map keys in undefined order
for _, mk := range value.MapKeys() {
mv := value.MapIndex(mk)
k, err := ValueOf(mk) // recurse
if err != nil {
return nil, err
}
v, err := ValueOf(mv) // recurse
if err != nil {
return nil, err
}
m[k] = v
}
kt, err := TypeOf(value.Type().Key()) // type of key
if err != nil {
return nil, errwrap.Wrapf(err, "can't determine key type of %+v", value)
}
vt, err := TypeOf(value.Type().Elem()) // type of value
if err != nil {
return nil, errwrap.Wrapf(err, "can't determine value type of %+v", value)
}
return &MapValue{
T: NewType(fmt.Sprintf("map{%s: %s}", kt.String(), vt.String())),
V: m,
}, nil
case reflect.Struct:
// TODO: we could take this simpler "get the full type" approach
// for all the values, but I think that building them up when
// possible for the other cases is a more robust approach!
t, err := TypeOf(value.Type())
if err != nil {
return nil, errwrap.Wrapf(err, "can't determine type of %+v", value)
}
l := value.NumField() // number of struct fields according to value
if l != len(t.Ord) {
// programming error?
return nil, fmt.Errorf("incompatible number of fields")
}
values := make(map[string]Value)
for i := 0; i < l; i++ {
x := value.Field(i)
v, err := ValueOf(x) // recurse
if err != nil {
return nil, err
}
name := t.Ord[i] // how else can we get the field name?
values[name] = v
}
return &StructValue{
T: t,
V: values,
}, nil
case reflect.Func:
t, err := TypeOf(value.Type())
if err != nil {
return nil, errwrap.Wrapf(err, "can't determine type of %+v", value)
}
if t.Out == nil {
return nil, fmt.Errorf("cannot only represent functions with one output value")
}
f := func(args []Value) (Value, error) {
in := []reflect.Value{}
for _, x := range args {
// TODO: should we build this method instead?
//v := x.Reflect() // types.Value -> reflect.Value
v := reflect.ValueOf(x.Value())
in = append(in, v)
}
// FIXME: can we trap panic's ?
out := value.Call(in) // []reflect.Value
if len(out) != 1 { // TODO: panic, b/c already checked in TypeOf?
return nil, fmt.Errorf("cannot only represent functions with one output value")
}
return ValueOf(out[0]) // recurse
}
return &FuncValue{
T: t,
V: f,
}, nil
default:
return nil, fmt.Errorf("unable to represent value of %+v", v)
}
}
// Into mutates the given reflect.Value with the data represented by the Value.
//
// Container types like map/list (and to a certain extent structs) will be
// cleared before adding the contained data such that the existing data doesn't
// affect the outcome, and the output reflect.Value directly maps to the input
// Value.
//
// In almost every case, it is likely that the reflect.Value will be modified,
// instantiating nil pointers and even potentially partially filling data before
// returning an error. It should be assumed that if this returns an error, the
// reflect.Value passed in has been trashed and should be discarded before
// reuse.
func Into(v Value, rv reflect.Value) error {
typ := rv.Type()
kind := typ.Kind()
for kind == reflect.Ptr {
typ = typ.Elem() // un-nest one pointer
kind = typ.Kind()
// if pointer was nil, instantiate the destination type and point
// at it to prevent nil pointer dereference when setting values
if rv.IsNil() {
rv.Set(reflect.New(typ))
}
rv = rv.Elem() // un-nest rv from pointer
}
// capture rv and v in a closure that is static for the scope of this Into() call
// mustInto ensures rv is in a list of compatible types before attempting to reflect it
mustInto := func(kinds ...reflect.Kind) error {
// sigh. Go can be so elegant, and then it makes you do this
for _, n := range kinds {
if kind == n {
return nil
}
}
// No matching kind found, must be an incompatible conversion
return fmt.Errorf("cannot Into() %+v of type %s into %s", v, v.Type(), typ)
}
switch v := v.(type) {
case *BoolValue:
if err := mustInto(reflect.Bool); err != nil {
return err
}
rv.SetBool(v.V)
return nil
case *StrValue:
if err := mustInto(reflect.String); err != nil {
return err
}
rv.SetString(v.V)
return nil
case *IntValue:
// overflow check
switch kind { // match on destination field kind
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
ff := reflect.Zero(typ) // test on a non-ptr equivalent
if ff.OverflowInt(v.V) { // this is valid!
return fmt.Errorf("%+v is an `%s`, and rv `%d` will overflow it", rv.Interface(), rv.Kind(), v.V)
}
rv.SetInt(v.V)
return nil
case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
ff := reflect.Zero(typ)
if ff.OverflowUint(uint64(v.V)) { // TODO: is this correct?
return fmt.Errorf("%+v is an `%s`, and rv `%d` will overflow it", rv.Interface(), rv.Kind(), v.V)
}
rv.SetUint(uint64(v.V))
return nil
default:
return fmt.Errorf("cannot Into() %+v of type %s into %s", v, v.Type(), typ)
}
case *FloatValue:
if err := mustInto(reflect.Float32, reflect.Float64); err != nil {
return err
}
ff := reflect.Zero(typ)
if ff.OverflowFloat(v.V) {
return fmt.Errorf("%+v is an `%s`, and value `%f` will overflow it", rv.Interface(), rv.Kind(), v.V)
}
rv.SetFloat(v.V)
return nil
case *ListValue:
count := len(v.V)
switch kind {
case reflect.Slice:
pow := nextPowerOfTwo(uint32(count))
nval := reflect.MakeSlice(rv.Type(), count, int(pow))
rv.Set(nval)
case reflect.Array:
if count > rv.Len() {
return fmt.Errorf("%+v is too small for %+v", typ, v)
}
rv.Set(reflect.New(typ).Elem())
default:
return mustInto() // nothing, always returns err
}
for i, x := range v.V {
f := rv.Index(i)
el := reflect.New(f.Type()).Elem()
if err := Into(x, el); err != nil { // recurse
return err
}
f.Set(el)
}
return nil
case *MapValue:
if err := mustInto(reflect.Map); err != nil {
return err
}
rv.Set(reflect.MakeMapWithSize(typ, len(v.V)))
// convert both key and value, then set them in the map
for mk, mv := range v.V {
key := reflect.New(typ.Key()).Elem()
if err := Into(mk, key); err != nil { // recurse
return err
}
val := reflect.New(typ.Elem()).Elem()
if err := Into(mv, val); err != nil { // recurse
return err
}
rv.SetMapIndex(key, val)
}
return nil
case *StructValue:
if err := mustInto(reflect.Struct); err != nil {
return err
}
// Into sets the value of the given reflect.Value to the value of this obj
mapping, err := TypeStructTagToFieldName(typ)
if err != nil {
return err
}
for k := range v.T.Map {
mk := k
// map mcl field name -> go field name based on `lang:""` tag
if key, exists := mapping[k]; exists {
mk = key
}
field := rv.FieldByName(mk)
if err := Into(v.V[k], field); err != nil { // recurse
return err
}
}
return nil
case *FuncValue:
if err := mustInto(reflect.Func); err != nil {
return err
}
// wrap our function with the translation that is necessary
fn := func(args []reflect.Value) (results []reflect.Value) { // build
innerArgs := []Value{}
for _, x := range args {
v, err := ValueOf(x) // reflect.Value -> Value
if err != nil {
panic(fmt.Errorf("can't determine value of %+v", x))
}
innerArgs = append(innerArgs, v)
}
result, err := v.V(innerArgs) // call it
if err != nil {
// when calling our function with the Call method, then
// we get the error output and have a chance to decide
// what to do with it, but when calling it from within
// a normal golang function call, the error represents
// that something went horribly wrong, aka a panic...
panic(fmt.Errorf("function panic: %+v", err))
}
out := reflect.New(rv.Type().Out(0))
// convert the lang result back to a Go value
if err := Into(result, out); err != nil {
panic(fmt.Errorf("function return conversion panic: %+v", err))
}
return []reflect.Value{out} // only one result
}
rv.Set(reflect.MakeFunc(rv.Type(), fn))
return nil
case *VariantValue:
return Into(v.V, rv)
default:
return fmt.Errorf("cannot Into() %+v of type %s into %s", v, v.Type(), typ)
}
}
// ValueSlice is a linear list of values. It is used for sorting purposes.
type ValueSlice []Value
func (vs ValueSlice) Len() int { return len(vs) }
func (vs ValueSlice) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] }
func (vs ValueSlice) Less(i, j int) bool { return vs[i].Less(vs[j]) }
// base implements the missing methods that all types need.
type base struct{}
// Bool represents the value of this type as a bool if it is one. If this is not
// a bool, then this panics.
func (obj *base) Bool() bool {
panic("not a bool")
}
// Str represents the value of this type as a string if it is one. If this is
// not a string, then this panics.
func (obj *base) Str() string {
panic("not an str") // yes, i think this is the correct grammar
}
// Int represents the value of this type as an integer if it is one. If this is
// not an integer, then this panics.
func (obj *base) Int() int64 {
panic("not an int")
}
// Float represents the value of this type as a float if it is one. If this is
// not a float, then this panics.
func (obj *base) Float() float64 {
panic("not a float")
}
// List represents the value of this type as a list if it is one. If this is not
// a list, then this panics.
func (obj *base) List() []Value {
panic("not a list")
}
// Map represents the value of this type as a dictionary if it is one. If this
// is not a map, then this panics.
func (obj *base) Map() map[Value]Value {
panic("not a list")
}
// Struct represents the value of this type as a struct if it is one. If this is
// not a struct, then this panics.
func (obj *base) Struct() map[string]Value {
panic("not a struct")
}
// Func represents the value of this type as a function if it is one. If this is
// not a function, then this panics.
func (obj *base) Func() func([]Value) (Value, error) {
panic("not a func")
}
// Less compares to value and returns true if we're smaller. It is recommended
// that this base implementation of the method be replaced in the specific type.
// This *may* panic if the two types aren't the same.
// NOTE: this can be used as an example template to write your own function.
//func (obj *base) Less(v Value) bool {
// // TODO: cheap less, be smarter in each type eg: int's should cmp as int
// return obj.String() < v.String()
//}
// Cmp returns an error if this value isn't the same as the arg passed in. This
// implementation uses the base Less implementation and should be replaced. It
// is always nice to implement this properly so that we get better error output.
// NOTE: this can be used as an example template to write your own function.
//func (obj *base) Cmp(v Value) error {
// // if they're both true or both false, then they must be the same,
// // because we expect that if x < & && y < x then x == y
// if obj.Less(v) != v.Less(obj) {
// return fmt.Errorf("values differ according to less")
// }
// return nil
//}
// BoolValue represents a boolean value.
type BoolValue struct {
base
V bool
}
// NewBool creates a new boolean value.
func NewBool() *BoolValue { return &BoolValue{} }
// String returns a visual representation of this value.
func (obj *BoolValue) String() string {
return strconv.FormatBool(obj.V) // true or false
//if obj.V {
// return "true"
//}
//return "false"
}
// Type returns the type data structure that represents this type.
func (obj *BoolValue) Type() *Type { return NewType("bool") }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *BoolValue) Less(v Value) bool {
//return obj.String() < v.(*BoolValue).String()
if obj.V != v.(*BoolValue).V { // there must be one false
// f, t -> t ; t, f -> f
return !obj.V // TODO: should `false` sort less?
}
return false // they're the same
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *BoolValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
if obj.V != val.(*BoolValue).V {
return fmt.Errorf("values are different")
}
return nil
}
// Copy returns a copy of this value.
func (obj *BoolValue) Copy() Value {
return &BoolValue{V: obj.V}
}
// Value returns the raw value of this type.
func (obj *BoolValue) Value() interface{} {
return obj.V
}
// Bool represents the value of this type as a bool if it is one. If this is not
// a bool, then this panics.
func (obj *BoolValue) Bool() bool {
return obj.V
}
// StrValue represents a string value.
type StrValue struct {
base
V string
}
// NewStr creates a new string value.
func NewStr() *StrValue { return &StrValue{} }
// String returns a visual representation of this value.
func (obj *StrValue) String() string {
return strconv.Quote(obj.V) // wraps in quotes, turns tabs into \t etc...
//return fmt.Sprintf(`"%s"`, obj.V)
}
// Type returns the type data structure that represents this type.
func (obj *StrValue) Type() *Type { return NewType("str") }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *StrValue) Less(v Value) bool {
return obj.V < v.(*StrValue).V
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *StrValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
if obj.V != val.(*StrValue).V {
return fmt.Errorf("values are different")
}
return nil
}
// Copy returns a copy of this value.
func (obj *StrValue) Copy() Value {
return &StrValue{V: obj.V}
}
// Value returns the raw value of this type.
func (obj *StrValue) Value() interface{} {
return obj.V
}
// Str represents the value of this type as a string if it is one. If this is
// not a string, then this panics.
func (obj *StrValue) Str() string {
return obj.V
}
// IntValue represents an integer value.
type IntValue struct {
base
V int64
}
// NewInt creates a new int value.
func NewInt() *IntValue { return &IntValue{} }
// String returns a visual representation of this value.
func (obj *IntValue) String() string {
return strconv.FormatInt(obj.V, 10)
}
// Type returns the type data structure that represents this type.
func (obj *IntValue) Type() *Type { return NewType("int") }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *IntValue) Less(v Value) bool {
return obj.V < v.(*IntValue).V
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *IntValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
if obj.V != val.(*IntValue).V {
return fmt.Errorf("values are different")
}
return nil
}
// Copy returns a copy of this value.
func (obj *IntValue) Copy() Value {
return &IntValue{V: obj.V}
}
// Value returns the raw value of this type.
func (obj *IntValue) Value() interface{} {
return obj.V
}
// Int represents the value of this type as an integer if it is one. If this is
// not an integer, then this panics.
func (obj *IntValue) Int() int64 {
return obj.V
}
// FloatValue represents an integer value.
type FloatValue struct {
base
V float64
}
// NewFloat creates a new float value.
func NewFloat() *FloatValue { return &FloatValue{} }
// String returns a visual representation of this value.
func (obj *FloatValue) String() string {
// TODO: is this the right display mode?
// FIXME: floats don't print nicely: https://github.com/golang/go/issues/46118
return strconv.FormatFloat(obj.V, 'f', -1, 64) // -1 for exact precision
}
// Type returns the type data structure that represents this type.
func (obj *FloatValue) Type() *Type { return NewType("float") }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *FloatValue) Less(v Value) bool {
return obj.V < v.(*FloatValue).V
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *FloatValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
// FIXME: should we compare with an epsilon?
if obj.V != val.(*FloatValue).V {
return fmt.Errorf("values are different")
}
return nil
}
// Copy returns a copy of this value.
func (obj *FloatValue) Copy() Value {
return &FloatValue{V: obj.V}
}
// Value returns the raw value of this type.
func (obj *FloatValue) Value() interface{} {
return obj.V
}
// Float represents the value of this type as a float if it is one. If this is
// not a float, then this panics.
func (obj *FloatValue) Float() float64 {
return obj.V
}
// ListValue represents a list value.
type ListValue struct {
base
V []Value // all elements must have type T.Val
T *Type
}
// NewList creates a new list with the specified list type.
func NewList(t *Type) *ListValue {
if t.Kind != KindList {
return nil // sanity check
}
return &ListValue{
T: t,
}
}
// String returns a visual representation of this value.
func (obj *ListValue) String() string {
var s []string
for _, x := range obj.V {
s = append(s, x.String())
}
return fmt.Sprintf("[%s]", strings.Join(s, ", "))
}
// Type returns the type data structure that represents this type.
func (obj *ListValue) Type() *Type { return obj.T }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *ListValue) Less(v Value) bool {
V := v.(*ListValue).V
i, j := len(obj.V), len(V)
for x := 0; x < i && x < j; x++ { // keep to min count of both lists
if obj.V[x].Less(V[x]) {
return true
}
}
return i < j // TODO: i think this is correct :)
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *ListValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
cmp := val.(*ListValue)
if len(obj.V) != len(cmp.V) {
return fmt.Errorf("values have different lengths")
}
for i := range obj.V {
if err := obj.V[i].Cmp(cmp.V[i]); err != nil {
return errwrap.Wrapf(err, "index %d did not cmp", i)
}
}
return nil
}
// Copy returns a copy of this value.
func (obj *ListValue) Copy() Value {
v := []Value{}
for _, x := range obj.V {
v = append(v, x.Copy())
}
return &ListValue{
V: v,
T: obj.T.Copy(),
}
}
// Value returns the raw value of this type.
func (obj *ListValue) Value() interface{} {
typ := obj.T.Reflect()
// create an empty slice (of len=0) with room for cap=len(obj.V) elements
val := reflect.MakeSlice(typ, 0, len(obj.V))
for _, x := range obj.V {
val = reflect.Append(val, reflect.ValueOf(x.Value())) // recurse
}
return val.Interface()
}
// List represents the value of this type as a list if it is one. If this is not
// a list, then this panics.
func (obj *ListValue) List() []Value {
return obj.V
}
// Add adds an element to this list. It errors if the type does not match.
func (obj *ListValue) Add(v Value) error {
if obj.T.Val.Kind != KindVariant { // skip cmp if dest is a variant
if err := obj.T.Val.Cmp(v.Type()); err != nil {
return errwrap.Wrapf(err, "value does not match list element type")
}
}
obj.V = append(obj.V, v)
return nil
}
// Lookup looks up a value by index. On success it also returns the Value.
func (obj *ListValue) Lookup(index int) (value Value, exists bool) {
if index >= 0 && index < len(obj.V) {
return obj.V[index], true // found
}
return nil, false
}
// Contains searches for a value in the list. On success it returns the index.
func (obj *ListValue) Contains(v Value) (index int, exists bool) {
for i, x := range obj.V {
if v.Cmp(x) == nil {
return i, true
}
}
return -1, false
}
// MapValue represents a dictionary value.
type MapValue struct {
base
// the types of all keys and values are represented inside of T
V map[Value]Value
T *Type
}
// NewMap creates a new map with the specified map type.
func NewMap(t *Type) *MapValue {
if t.Kind != KindMap {
return nil // sanity check
}
return &MapValue{
V: make(map[Value]Value),
T: t,
}
}
// String returns a visual representation of this value.
func (obj *MapValue) String() string {
keys := []Value{}
for k := range obj.V {
keys = append(keys, k)
}
sort.Sort(ValueSlice(keys)) // deterministic print order
var s []string
for _, k := range keys {
s = append(s, fmt.Sprintf("%s: %s", k.String(), obj.V[k].String()))
}
return fmt.Sprintf("{%s}", strings.Join(s, ", "))
}
// Type returns the type data structure that represents this type.
func (obj *MapValue) Type() *Type { return obj.T }
// Less compares to value and returns true if we're smaller. This panics if the
// two types aren't the same.
func (obj *MapValue) Less(v Value) bool {
V := v.(*MapValue)
return obj.String() < V.String() // FIXME: implement a proper less func
}
// Cmp returns an error if this value isn't the same as the arg passed in.
func (obj *MapValue) Cmp(val Value) error {
if obj == nil || val == nil {
return fmt.Errorf("cannot cmp to nil")
}
if err := obj.Type().Cmp(val.Type()); err != nil {
return errwrap.Wrapf(err, "cannot cmp types")
}
cmp := val.(*MapValue)
if len(obj.V) != len(cmp.V) {
return fmt.Errorf("values have different lengths")
}
for k := range obj.V {
v, exists := cmp.V[k]
if !exists {
return fmt.Errorf("index %s does not exist", k)
}
if err := obj.V[k].Cmp(v); err != nil {
return errwrap.Wrapf(err, "index %s did not cmp", k)
}
}
return nil
}
// Copy returns a copy of this value.
func (obj *MapValue) Copy() Value {
m := map[Value]Value{}
for k, v := range obj.V {
m[k.Copy()] = v.Copy()
}
return &MapValue{
V: m,
T: obj.T.Copy(),
}
}
// Value returns the raw value of this type.
func (obj *MapValue) Value() interface{} {
typ := obj.T.Reflect()
val := reflect.MakeMap(typ)
for k, v := range obj.V {
val.SetMapIndex(reflect.ValueOf(k.Value()), reflect.ValueOf(v.Value())) // dual recurse
}
return val.Interface()
}
// Map represents the value of this type as a dictionary if it is one. If this
// is not a map, then this panics.
func (obj *MapValue) Map() map[Value]Value {
return obj.V
}
// Add adds an element to this map. It errors if the types do not match.
func (obj *MapValue) Add(k, v Value) error { // TODO: change method name?
//if obj.T.Key.Kind != KindVariant {
if err := obj.T.Key.Cmp(k.Type()); err != nil {
return errwrap.Wrapf(err, "key does not match map key type")
}
//}
if obj.T.Val.Kind != KindVariant { // skip cmp if dest is a variant
if err := obj.T.Val.Cmp(v.Type()); err != nil {
return errwrap.Wrapf(err, "val does not match map val type")
}
}