-
Notifications
You must be signed in to change notification settings - Fork 11
/
decode.go
1678 lines (1577 loc) · 40.6 KB
/
decode.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
// Copyright 2015 Jean Niklas L'orange. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package edn
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math/big"
"reflect"
"runtime"
"strconv"
"strings"
"unicode/utf8"
)
var (
errInternal = errors.New("Illegal internal parse state")
errNoneLeft = errors.New("No more tokens to read")
errUnexpected = errors.New("Unexpected token")
errIllegalRune = errors.New("Illegal rune form")
)
type UnknownTagError struct {
tag []byte
value []byte
inType reflect.Type
}
func (ute UnknownTagError) Error() string {
return fmt.Sprintf("Unable to decode %s%s into %s", string(ute.tag),
string(ute.value), ute.inType)
}
// Unmarshal parses the EDN-encoded data and stores the result in the value
// pointed to by v.
//
// Unmarshal uses the inverse of the encodings that Marshal uses, allocating
// maps, slices, and pointers as necessary, with the following additional rules:
//
// First, if the value to store the result into implements edn.Unmarshaler, it
// is called.
//
// If the value is tagged and the tag is known, the EDN value is translated into
// the input of the tag convert function. If no error happens during converting,
// the result of the conversion is then coerced into v if possible.
//
// To unmarshal EDN into a pointer, Unmarshal first handles the case of the EDN
// being the EDN literal nil. In that case, Unmarshal sets the pointer to nil.
// Otherwise, Unmarshal unmarshals the EDN into the value pointed at by the
// pointer. If the pointer is nil, Unmarshal allocates a new value for it to
// point to.
//
// To unmarshal EDN into a struct, Unmarshal matches incoming object
// keys to the keys used by Marshal (either the struct field name or its tag),
// preferring an exact match but also accepting a case-insensitive match.
//
// To unmarshal EDN into an interface value,
// Unmarshal stores one of these in the interface value:
//
// bool, for EDN booleans
// float64, for EDN floats
// int64, for EDN integers
// int32, for EDN characters
// string, for EDN strings
// []interface{}, for EDN vectors and lists
// map[interface{}]interface{}, for EDN maps
// map[interface{}]bool, for EDN sets
// nil for EDN nil
// edn.Tag for unknown EDN tagged elements
// T for known EDN tagged elements, where T is the result of the converter function
//
// To unmarshal an EDN vector/list into a slice, Unmarshal resets the slice to
// nil and then appends each element to the slice.
//
// To unmarshal an EDN map into a Go map, Unmarshal replaces the map
// with an empty map and then adds key-value pairs from the object to
// the map.
//
// If a EDN value is not appropriate for a given target type, or if a EDN number
// overflows the target type, Unmarshal skips that field and completes the
// unmarshalling as best it can. If no more serious errors are encountered,
// Unmarshal returns an UnmarshalTypeError describing the earliest such error.
//
// The EDN nil value unmarshals into an interface, map, pointer, or slice by
// setting that Go value to nil.
//
// When unmarshaling strings, invalid UTF-8 or invalid UTF-16 surrogate pairs
// are not treated as an error. Instead, they are replaced by the Unicode
// replacement character U+FFFD.
//
func Unmarshal(data []byte, v interface{}) error {
return newDecoder(bufio.NewReader(bytes.NewBuffer(data))).Decode(v)
}
// UnmarshalString works like Unmarshal, but accepts a string as input instead
// of a byte slice.
func UnmarshalString(data string, v interface{}) error {
return newDecoder(bufio.NewReader(bytes.NewBufferString(data))).Decode(v)
}
// NewDecoder returns a new decoder that reads from r.
//
// The decoder introduces its own buffering and may read data from r beyond the
// EDN values requested.
func NewDecoder(r io.Reader) *Decoder {
return newDecoder(bufio.NewReader(r))
}
// Buffered returns a reader of the data remaining in the Decoder's buffer. The
// reader is valid until the next call to Decode.
func (d *Decoder) Buffered() *bufio.Reader {
return d.rd
}
// AddTagFn adds a tag function to the decoder's TagMap. Note that TagMaps are
// mutable: If Decoder A and B share TagMap, then adding a tag function to one
// may modify both.
func (d *Decoder) AddTagFn(tagname string, fn interface{}) error {
return d.tagmap.AddTagFn(tagname, fn)
}
// MustAddTagFn adds a tag function to the decoder's TagMap like AddTagFn,
// except this function also panics if the tag could not be added.
func (d *Decoder) MustAddTagFn(tagname string, fn interface{}) {
d.tagmap.MustAddTagFn(tagname, fn)
}
// AddTagStruct adds a tag struct to the decoder's TagMap. Note that TagMaps are
// mutable: If Decoder A and B share TagMap, then adding a tag struct to one
// may modify both.
func (d *Decoder) AddTagStruct(tagname string, example interface{}) error {
return d.tagmap.AddTagStruct(tagname, example)
}
// UseTagMap sets the TagMap provided as the TagMap for this decoder.
func (d *Decoder) UseTagMap(tm *TagMap) {
d.tagmap = tm
}
// UseMathContext sets the given math context as default math context for this
// decoder.
func (d *Decoder) UseMathContext(mc MathContext) {
d.mc = &mc
}
func (d *Decoder) mathContext() *MathContext {
if d.mc != nil {
return d.mc
}
return &GlobalMathContext
}
// DisallowUnknownFields causes the Decoder to return an error when the
// destination is a struct and the input contains keys which do not match any
// non-ignored, exported fields in the destination.
func (d *Decoder) DisallowUnknownFields() {
d.disallowUnknownFields = true
}
// Unmarshaler is the interface implemented by objects that can unmarshal an EDN
// description of themselves. The input can be assumed to be a valid encoding of
// an EDN value. UnmarshalEDN must copy the EDN data if it wishes to retain the
// data after returning.
type Unmarshaler interface {
UnmarshalEDN([]byte) error
}
type parseState int
const (
parseToplevel = iota
parseList
parseVector
parseMap
parseSet
parseTagged
parseDiscard
)
// A Decoder reads and decodes EDN objects from an input stream.
type Decoder struct {
disallowUnknownFields bool
lex *lexer
savedError error
rd *bufio.Reader
tagmap *TagMap
mc *MathContext
// parser-specific
prevSlice []byte
prevTtype tokenType
undo bool
// if nextToken returned lexEndPrev, we must write the leftover value at
// next call to nextToken
hasLeftover bool
leftover rune
}
// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
type InvalidUnmarshalError struct {
Type reflect.Type
}
func (e *InvalidUnmarshalError) Error() string {
if e.Type == nil {
return "edn: Unmarshal(nil)"
}
if e.Type.Kind() != reflect.Ptr {
return "edb: Unmarshal(non-pointer " + e.Type.String() + ")"
}
return "edn: Unmarshal(nil " + e.Type.String() + ")"
}
// An UnmarshalTypeError describes a EDN value that was
// not appropriate for a value of a specific Go type.
type UnmarshalTypeError struct {
Value string // description of EDN value - "bool", "array", "number -5"
Type reflect.Type // type of Go value it could not be assigned to
}
func (e *UnmarshalTypeError) Error() string {
return "edn: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
}
// UnhashableError is an error which occurs when the decoder attempted to assign
// an unhashable key to a map or set. The position close to where value was
// found is provided to help debugging.
type UnhashableError struct {
Position int64
}
func (e *UnhashableError) Error() string {
return "edn: unhashable type at position " + strconv.FormatInt(e.Position, 10) + " in input"
}
type UnknownFieldError struct {
Field string // the field name
Type reflect.Type // type of Go struct with a missing field
}
func (e *UnknownFieldError) Error() string {
return "edn: cannot find a field '" + e.Field + "' in a struct " + e.Type.String() + " to unmarshal into"
}
// Decode reads the next EDN-encoded value from its input and stores it in the
// value pointed to by v.
//
// See the documentation for Unmarshal for details about the conversion of EDN
// into a Go value.
func (d *Decoder) Decode(val interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
// if unhashable, return ErrUnhashable. Else panic unless it's an error
// from the decoder itself.
if rerr, ok := r.(runtime.Error); ok {
if strings.Contains(rerr.Error(), "unhashable") {
err = &UnhashableError{Position: d.lex.position}
} else {
panic(r)
}
} else {
err = r.(error)
}
}
}()
err = d.more()
if err != nil {
return err
}
rv := reflect.ValueOf(val)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(val)}
}
d.value(rv)
return nil
}
func newDecoder(buf *bufio.Reader) *Decoder {
lex := lexer{}
lex.reset()
return &Decoder{
lex: &lex,
rd: buf,
hasLeftover: false,
leftover: '\uFFFD',
tagmap: new(TagMap),
}
}
func (d *Decoder) getTagFn(tagname string) *reflect.Value {
d.tagmap.RLock()
f, ok := d.tagmap.m[tagname]
d.tagmap.RUnlock()
if ok {
return &f
}
globalTags.RLock()
f, ok = globalTags.m[tagname]
globalTags.RUnlock()
if ok {
return &f
}
return nil
}
func (d *Decoder) error(err error) {
panic(err)
}
func (d *Decoder) doUndo(bs []byte, ttype tokenType) {
if d.undo {
d.error(errInternal) // this is LL(1), so this shouldn't happen
}
d.undo = true
d.prevSlice = bs
d.prevTtype = ttype
}
// array consumes an array from d.data[d.off-1:], decoding into the value v.
// the first byte of the array ('[') has been read already.
func (d *Decoder) array(v reflect.Value, endType tokenType) {
// Check for unmarshaler.
u, pv := d.indirect(v, false)
if u != nil {
switch endType {
case tokenVectorEnd:
d.doUndo([]byte{'['}, tokenVectorStart)
case tokenListEnd:
d.doUndo([]byte{'('}, tokenListStart)
case tokenSetEnd:
d.doUndo([]byte{'#', '{'}, tokenSetStart)
}
bs, err := d.nextValueBytes()
if err == nil {
err = u.UnmarshalEDN(bs)
}
if err != nil {
d.error(err)
}
return
}
v = pv
// Check type of target.
switch v.Kind() {
case reflect.Interface:
if v.NumMethod() == 0 {
// Decoding into nil interface? Switch to non-reflect code.
v.Set(reflect.ValueOf(d.arrayInterface(endType)))
return
}
// Otherwise it's invalid.
fallthrough
default:
d.error(&UnmarshalTypeError{"array", v.Type()})
return
case reflect.Array:
case reflect.Slice:
break
}
i := 0
for {
// Look ahead for ] - can only happen on first iteration.
bs, ttype, err := d.nextToken()
if err != nil {
d.error(err)
}
if ttype == endType {
break
}
d.doUndo(bs, ttype)
// Get element of array, growing if necessary.
if v.Kind() == reflect.Slice {
// Grow slice if necessary
if i >= v.Cap() {
newcap := v.Cap() + v.Cap()/2
if newcap < 4 {
newcap = 4
}
newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
reflect.Copy(newv, v)
v.Set(newv)
}
if i >= v.Len() {
v.SetLen(i + 1)
}
}
if i < v.Len() {
// Decode into element.
d.value(v.Index(i))
} else {
// Ran out of fixed array: skip.
d.value(reflect.Value{})
}
i++
}
if i < v.Len() {
if v.Kind() == reflect.Array {
// Array. Zero the rest.
z := reflect.Zero(v.Type().Elem())
for ; i < v.Len(); i++ {
v.Index(i).Set(z)
}
} else {
v.SetLen(i)
}
}
if i == 0 && v.Kind() == reflect.Slice {
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}
}
func (d *Decoder) arrayInterface(endType tokenType) interface{} {
var v = make([]interface{}, 0)
for {
// look out for endType
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
break
}
if tt == endType {
break
}
d.doUndo(bs, tt)
v = append(v, d.valueInterface())
}
return v
}
func (d *Decoder) value(v reflect.Value) {
if !v.IsValid() {
// read value and ignore it
d.valueInterface()
return
}
bs, ttype, err := d.nextToken()
// check error first
if err != nil {
d.error(err)
return
}
switch ttype {
default:
d.error(errUnexpected)
case tokenSymbol, tokenKeyword, tokenString, tokenInt, tokenFloat, tokenChar:
d.literal(bs, ttype, v)
case tokenTag:
d.tag(bs, v)
case tokenListStart:
d.array(v, tokenListEnd)
case tokenVectorStart:
d.array(v, tokenVectorEnd)
case tokenSetStart:
d.set(v)
case tokenMapStart:
d.ednmap(v)
}
}
func (d *Decoder) tag(tag []byte, v reflect.Value) {
// Check for unmarshaler.
u, pv := d.indirect(v, false)
if u != nil {
bs, err := d.nextValueBytes()
if err == nil {
err = u.UnmarshalEDN(append(append(tag, ' '), bs...))
}
if err != nil {
d.error(err)
}
return
}
v = pv
if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
v.Set(reflect.ValueOf(d.tagInterface(tag)))
return
}
fn := d.getTagFn(string(tag[1:]))
if fn == nil {
// So in theory we'd have to match against any interface that could be
// assignable to the Tag type, to ensure we would decode whenever possible.
// That is any interface that specifies any combination of the methods
// MarshalEDN, UnmarshalEDN and String. I'm not sure if that makes sense
// though, so I've punted this for now.
bs, err := d.nextValueBytes()
if err != nil {
d.error(err)
}
d.error(UnknownTagError{tag, bs, v.Type()})
} else {
tfn := fn.Type()
var result reflect.Value
// if not func, just match on struct shape
if tfn.Kind() != reflect.Func {
result = reflect.New(tfn).Elem()
d.value(result)
} else { // otherwise match on input value and call the function
inVal := reflect.New(tfn.In(0))
d.value(inVal)
res := fn.Call([]reflect.Value{inVal.Elem()})
if err, ok := res[1].Interface().(error); ok && err != nil {
d.error(err)
}
result = res[0]
}
// result is not necessarily direct, so we have to make it direct, but
// *only* if it's NOT null at every step. Which leads to the question: How
// do we unify these values? This is particularly hairy if these are double
// pointers or bigger.
// Currently we only attempt to solve this for results by checking if the
// result can be dereferenced into a value. The value will always be a
// non-pointer, so presumably we can assign it in this fashion as a
// temporary resolution.
if result.Type().AssignableTo(v.Type()) {
v.Set(result)
return
}
if result.Kind() == reflect.Ptr && !result.IsNil() &&
result.Elem().Type().AssignableTo(v.Type()) {
// is res a non-nil pointer to a value we can assign to? If yes, then
// let's just do that.
v.Set(result.Elem())
return
}
d.error(fmt.Errorf("Cannot assign %s to %s (tag issue?)", result.Type(), v.Type()))
}
}
func (d *Decoder) tagInterface(tag []byte) interface{} {
fn := d.getTagFn(string(tag[1:]))
if fn == nil {
var t Tag
t.Tagname = string(tag[1:])
t.Value = d.valueInterface()
return t
} else if fn.Type().Kind() != reflect.Func {
res := reflect.New(fn.Type()).Elem()
d.value(res)
return res.Interface()
} else {
tfn := fn.Type()
val := reflect.New(tfn.In(0))
d.value(val)
res := fn.Call([]reflect.Value{val.Elem()})
if err, ok := res[1].Interface().(error); ok && err != nil {
d.error(err)
}
return res[0].Interface()
}
}
func (d *Decoder) valueInterface() interface{} {
bs, ttype, err := d.nextToken()
// check error first
if err != nil {
d.error(err)
return nil /// won't get here
}
switch ttype {
default:
d.error(errUnexpected)
return nil
case tokenSymbol, tokenKeyword, tokenString, tokenInt, tokenFloat, tokenChar:
return d.literalInterface(bs, ttype)
case tokenTag:
return d.tagInterface(bs)
case tokenListStart:
return d.arrayInterface(tokenListEnd)
case tokenVectorStart:
return d.arrayInterface(tokenVectorEnd)
case tokenSetStart:
return d.setInterface()
case tokenMapStart:
return d.ednmapInterface()
}
return nil
}
func (d *Decoder) ednmap(v reflect.Value) {
// Check for unmarshaler.
u, pv := d.indirect(v, false)
if u != nil {
d.doUndo([]byte{'{'}, tokenMapStart)
bs, err := d.nextValueBytes()
if err == nil {
err = u.UnmarshalEDN(bs)
}
if err != nil {
d.error(err)
}
return
}
v = pv
if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
v.Set(reflect.ValueOf(d.ednmapInterface()))
return
}
var keyType reflect.Type
// Check type of target: Struct or map[T]U
switch v.Kind() {
case reflect.Map:
t := v.Type()
keyType = t.Key()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
case reflect.Struct:
default:
d.error(&UnmarshalTypeError{"map", v.Type()})
}
// separate these to ease reading (theoretically fewer checks too)
if v.Kind() == reflect.Struct {
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
skip := false
var key []byte
// The key can either be a symbol, a keyword or a string. We will skip
// anything that is not any of these values.
switch tt {
case tokenSymbol:
if bytes.Equal(bs, falseByte) || bytes.Equal(bs, trueByte) || bytes.Equal(bs, nilByte) {
skip = true
}
key = bs
case tokenKeyword:
key = bs[1:]
case tokenString:
k, ok := unquoteBytes(bs)
key = k
if !ok {
d.error(errInternal)
}
default:
skip = true
}
if skip { // will panic if something bad happens, so this is fine
d.valueInterface()
continue
}
var subv reflect.Value
var f *field
fields := cachedTypeFields(v.Type())
for i := range fields {
ff := &fields[i]
if bytes.Equal(ff.nameBytes, key) {
f = ff
break
}
if f == nil && ff.equalFold(ff.nameBytes, key) {
f = ff
}
}
if f != nil {
subv = v
for _, i := range f.index {
if subv.Kind() == reflect.Ptr {
if subv.IsNil() {
subv.Set(reflect.New(subv.Type().Elem()))
}
subv = subv.Elem()
}
subv = subv.Field(i)
}
} else if d.disallowUnknownFields {
d.error(&UnknownFieldError{string(key), v.Type()})
}
// If subv not set, value() will just skip.
d.value(subv)
}
// if not struct, then it is a map
} else if keyType.Kind() == reflect.Interface && keyType.NumMethod() == 0 {
// special case for unhashable key types
var mapElem reflect.Value
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
d.doUndo(bs, tt)
key := d.valueInterface()
elemType := v.Type().Elem()
if !mapElem.IsValid() {
mapElem = reflect.New(elemType).Elem()
} else {
mapElem.Set(reflect.Zero(elemType))
}
subv := mapElem
d.value(subv)
if key == nil {
v.SetMapIndex(reflect.New(keyType).Elem(), subv)
} else {
switch reflect.TypeOf(key).Kind() {
case reflect.Slice, reflect.Map: // bypass issues with unhashable types
v.SetMapIndex(reflect.ValueOf(&key), subv)
default:
v.SetMapIndex(reflect.ValueOf(key), subv)
}
}
}
} else { // default map case
var mapElem reflect.Value
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
d.doUndo(bs, tt)
// should we do the same as with mapElem?
key := reflect.New(keyType).Elem()
d.value(key)
elemType := v.Type().Elem()
if !mapElem.IsValid() {
mapElem = reflect.New(elemType).Elem()
} else {
mapElem.Set(reflect.Zero(elemType))
}
subv := mapElem
d.value(subv)
v.SetMapIndex(key, subv)
}
}
}
func (d *Decoder) ednmapInterface() interface{} {
theMap := make(map[interface{}]interface{}, 0)
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenMapEnd {
break
}
d.doUndo(bs, tt)
key := d.valueInterface()
value := d.valueInterface()
// special case on nil here. nil is hashable, so use it as key.
if key == nil {
theMap[key] = value
} else {
switch reflect.TypeOf(key).Kind() {
case reflect.Slice, reflect.Map: // bypass issues with unhashable types
theMap[&key] = value
default:
theMap[key] = value
}
}
}
return theMap
}
func (d *Decoder) set(v reflect.Value) {
// Check for unmarshaler.
u, pv := d.indirect(v, false)
if u != nil {
d.doUndo([]byte{'#', '{'}, tokenSetStart)
bs, err := d.nextValueBytes()
if err == nil {
err = u.UnmarshalEDN(bs)
}
if err != nil {
d.error(err)
}
return
}
v = pv
var setValue reflect.Value
var keyType reflect.Type
// Check type of target.
// TODO: accept option structs? -- i.e. structs where all fields are bools
// TODO: Also accept slices
switch v.Kind() {
case reflect.Map:
// map must have bool or struct{} value type
t := v.Type()
keyType = t.Key()
valKind := t.Elem().Kind()
switch valKind {
case reflect.Bool:
setValue = reflect.ValueOf(true)
case reflect.Struct:
// check if struct, and if so, ensure it has 0 fields
if t.Elem().NumField() != 0 {
d.error(&UnmarshalTypeError{"set", v.Type()})
}
setValue = reflect.Zero(t.Elem())
default:
d.error(&UnmarshalTypeError{"set", v.Type()})
}
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
case reflect.Slice, reflect.Array:
// Some extent of rechecking going on when we pass it to array, but it
// should be a constant factor only.
d.array(v, tokenSetEnd)
return
case reflect.Interface:
if v.NumMethod() == 0 {
// break out and use setInterface
v.Set(reflect.ValueOf(d.setInterface()))
return
} else {
d.error(&UnmarshalTypeError{"set", v.Type()})
}
default:
d.error(&UnmarshalTypeError{"set", v.Type()})
}
// special case here, to avoid panics when we have slices and maps as keys.
// Split out from code below to improve perf
if keyType.Kind() == reflect.Interface && keyType.NumMethod() == 0 {
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
d.doUndo(bs, tt)
key := d.valueInterface()
// special case on nil here: Need to create a zero type of the specific
// keyType. As this is an interface, this will itself be nil.
if key == nil {
v.SetMapIndex(reflect.New(keyType).Elem(), setValue)
} else {
switch reflect.TypeOf(key).Kind() {
case reflect.Slice, reflect.Map: // bypass issues with unhashable types
v.SetMapIndex(reflect.ValueOf(&key), setValue)
default:
v.SetMapIndex(reflect.ValueOf(key), setValue)
}
}
}
} else {
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
d.doUndo(bs, tt)
key := reflect.New(keyType).Elem()
d.value(key)
v.SetMapIndex(key, setValue)
}
}
}
func (d *Decoder) setInterface() interface{} {
theSet := make(map[interface{}]bool, 0)
for {
bs, tt, err := d.nextToken()
if err != nil {
d.error(err)
}
if tt == tokenSetEnd {
break
}
d.doUndo(bs, tt)
key := d.valueInterface()
if key == nil {
theSet[key] = true
} else {
switch reflect.TypeOf(key).Kind() {
case reflect.Slice, reflect.Map: // bypass issues with unhashable types
theSet[&key] = true
default:
theSet[key] = true
}
}
}
return theSet
}
var nilByte = []byte(`nil`)
var trueByte = []byte(`true`)
var falseByte = []byte(`false`)
var symbolType = reflect.TypeOf(Symbol(""))
var keywordType = reflect.TypeOf(Keyword(""))
var byteSliceType = reflect.TypeOf([]byte(nil))
var bigFloatType = reflect.TypeOf((*big.Float)(nil)).Elem()
var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
func (d *Decoder) literal(bs []byte, ttype tokenType, v reflect.Value) {
wantptr := ttype == tokenSymbol && bytes.Equal(nilByte, bs)
u, pv := d.indirect(v, wantptr)
if u != nil {
err := u.UnmarshalEDN(bs)
if err != nil {
d.error(err)
}
return
}
v = pv
switch ttype {
case tokenSymbol:
if wantptr { // nil
switch v.Kind() {
case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
v.Set(reflect.Zero(v.Type()))
default:
d.error(&UnmarshalTypeError{"nil", v.Type()})
}
} else if bytes.Equal(trueByte, bs) || bytes.Equal(falseByte, bs) { // true|false
value := bs[0] == 't'
switch v.Kind() {
default:
d.error(&UnmarshalTypeError{"bool", v.Type()})
case reflect.Bool:
v.SetBool(value)
case reflect.Interface:
if v.NumMethod() == 0 {
v.Set(reflect.ValueOf(value))
} else {
d.error(&UnmarshalTypeError{"bool", v.Type()})
}
}
} else if v.Kind() == reflect.String && v.Type() == symbolType { // "actual" symbols
v.SetString(string(bs))
} else if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
v.Set(reflect.ValueOf(Symbol(string(bs))))
} else {
d.error(&UnmarshalTypeError{"symbol", v.Type()})
}
case tokenKeyword:
if v.Kind() == reflect.String && v.Type() == keywordType { // "actual" keywords
v.SetString(string(bs[1:]))
} else if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
v.Set(reflect.ValueOf(Keyword(string(bs[1:]))))
} else {
d.error(&UnmarshalTypeError{"keyword", v.Type()})
}
case tokenInt:
var s string
isBig := false
if bs[len(bs)-1] == 'N' { // can end with N, which we promptly ignore
// TODO: If the user expects a float and receives what is perceived as an
// int (ends with N), what is the sensible thing to do?
s = string(bs[:len(bs)-1])
isBig = true
} else {
s = string(bs)
}
switch v.Kind() {
default:
switch v.Type() {