Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go
2880 views
1
package toml
2
3
import (
4
"encoding"
5
"errors"
6
"fmt"
7
"io"
8
"math"
9
"reflect"
10
"strconv"
11
"strings"
12
"sync/atomic"
13
"time"
14
15
"github.com/pelletier/go-toml/v2/internal/danger"
16
"github.com/pelletier/go-toml/v2/internal/tracker"
17
"github.com/pelletier/go-toml/v2/unstable"
18
)
19
20
// Unmarshal deserializes a TOML document into a Go value.
21
//
22
// It is a shortcut for Decoder.Decode() with the default options.
23
func Unmarshal(data []byte, v interface{}) error {
24
d := decoder{}
25
d.p.Reset(data)
26
return d.FromParser(v)
27
}
28
29
// Decoder reads and decode a TOML document from an input stream.
30
type Decoder struct {
31
// input
32
r io.Reader
33
34
// global settings
35
strict bool
36
37
// toggles unmarshaler interface
38
unmarshalerInterface bool
39
}
40
41
// NewDecoder creates a new Decoder that will read from r.
42
func NewDecoder(r io.Reader) *Decoder {
43
return &Decoder{r: r}
44
}
45
46
// DisallowUnknownFields causes the Decoder to return an error when the
47
// destination is a struct and the input contains a key that does not match a
48
// non-ignored field.
49
//
50
// In that case, the Decoder returns a StrictMissingError that can be used to
51
// retrieve the individual errors as well as generate a human readable
52
// description of the missing fields.
53
func (d *Decoder) DisallowUnknownFields() *Decoder {
54
d.strict = true
55
return d
56
}
57
58
// EnableUnmarshalerInterface allows to enable unmarshaler interface.
59
//
60
// With this feature enabled, types implementing the unstable/Unmarshaler
61
// interface can be decoded from any structure of the document. It allows types
62
// that don't have a straightforward TOML representation to provide their own
63
// decoding logic.
64
//
65
// Currently, types can only decode from a single value. Tables and array tables
66
// are not supported.
67
//
68
// *Unstable:* This method does not follow the compatibility guarantees of
69
// semver. It can be changed or removed without a new major version being
70
// issued.
71
func (d *Decoder) EnableUnmarshalerInterface() *Decoder {
72
d.unmarshalerInterface = true
73
return d
74
}
75
76
// Decode the whole content of r into v.
77
//
78
// By default, values in the document that don't exist in the target Go value
79
// are ignored. See Decoder.DisallowUnknownFields() to change this behavior.
80
//
81
// When a TOML local date, time, or date-time is decoded into a time.Time, its
82
// value is represented in time.Local timezone. Otherwise the appropriate Local*
83
// structure is used. For time values, precision up to the nanosecond is
84
// supported by truncating extra digits.
85
//
86
// Empty tables decoded in an interface{} create an empty initialized
87
// map[string]interface{}.
88
//
89
// Types implementing the encoding.TextUnmarshaler interface are decoded from a
90
// TOML string.
91
//
92
// When decoding a number, go-toml will return an error if the number is out of
93
// bounds for the target type (which includes negative numbers when decoding
94
// into an unsigned int).
95
//
96
// If an error occurs while decoding the content of the document, this function
97
// returns a toml.DecodeError, providing context about the issue. When using
98
// strict mode and a field is missing, a `toml.StrictMissingError` is
99
// returned. In any other case, this function returns a standard Go error.
100
//
101
// # Type mapping
102
//
103
// List of supported TOML types and their associated accepted Go types:
104
//
105
// String -> string
106
// Integer -> uint*, int*, depending on size
107
// Float -> float*, depending on size
108
// Boolean -> bool
109
// Offset Date-Time -> time.Time
110
// Local Date-time -> LocalDateTime, time.Time
111
// Local Date -> LocalDate, time.Time
112
// Local Time -> LocalTime, time.Time
113
// Array -> slice and array, depending on elements types
114
// Table -> map and struct
115
// Inline Table -> same as Table
116
// Array of Tables -> same as Array and Table
117
func (d *Decoder) Decode(v interface{}) error {
118
b, err := io.ReadAll(d.r)
119
if err != nil {
120
return fmt.Errorf("toml: %w", err)
121
}
122
123
dec := decoder{
124
strict: strict{
125
Enabled: d.strict,
126
},
127
unmarshalerInterface: d.unmarshalerInterface,
128
}
129
dec.p.Reset(b)
130
131
return dec.FromParser(v)
132
}
133
134
type decoder struct {
135
// Which parser instance in use for this decoding session.
136
p unstable.Parser
137
138
// Flag indicating that the current expression is stashed.
139
// If set to true, calling nextExpr will not actually pull a new expression
140
// but turn off the flag instead.
141
stashedExpr bool
142
143
// Skip expressions until a table is found. This is set to true when a
144
// table could not be created (missing field in map), so all KV expressions
145
// need to be skipped.
146
skipUntilTable bool
147
148
// Flag indicating that the current array/slice table should be cleared because
149
// it is the first encounter of an array table.
150
clearArrayTable bool
151
152
// Tracks position in Go arrays.
153
// This is used when decoding [[array tables]] into Go arrays. Given array
154
// tables are separate TOML expression, we need to keep track of where we
155
// are at in the Go array, as we can't just introspect its size.
156
arrayIndexes map[reflect.Value]int
157
158
// Tracks keys that have been seen, with which type.
159
seen tracker.SeenTracker
160
161
// Strict mode
162
strict strict
163
164
// Flag that enables/disables unmarshaler interface.
165
unmarshalerInterface bool
166
167
// Current context for the error.
168
errorContext *errorContext
169
}
170
171
type errorContext struct {
172
Struct reflect.Type
173
Field []int
174
}
175
176
func (d *decoder) typeMismatchError(toml string, target reflect.Type) error {
177
return fmt.Errorf("toml: %s", d.typeMismatchString(toml, target))
178
}
179
180
func (d *decoder) typeMismatchString(toml string, target reflect.Type) string {
181
if d.errorContext != nil && d.errorContext.Struct != nil {
182
ctx := d.errorContext
183
f := ctx.Struct.FieldByIndex(ctx.Field)
184
return fmt.Sprintf("cannot decode TOML %s into struct field %s.%s of type %s", toml, ctx.Struct, f.Name, f.Type)
185
}
186
return fmt.Sprintf("cannot decode TOML %s into a Go value of type %s", toml, target)
187
}
188
189
func (d *decoder) expr() *unstable.Node {
190
return d.p.Expression()
191
}
192
193
func (d *decoder) nextExpr() bool {
194
if d.stashedExpr {
195
d.stashedExpr = false
196
return true
197
}
198
return d.p.NextExpression()
199
}
200
201
func (d *decoder) stashExpr() {
202
d.stashedExpr = true
203
}
204
205
func (d *decoder) arrayIndex(shouldAppend bool, v reflect.Value) int {
206
if d.arrayIndexes == nil {
207
d.arrayIndexes = make(map[reflect.Value]int, 1)
208
}
209
210
idx, ok := d.arrayIndexes[v]
211
212
if !ok {
213
d.arrayIndexes[v] = 0
214
} else if shouldAppend {
215
idx++
216
d.arrayIndexes[v] = idx
217
}
218
219
return idx
220
}
221
222
func (d *decoder) FromParser(v interface{}) error {
223
r := reflect.ValueOf(v)
224
if r.Kind() != reflect.Ptr {
225
return fmt.Errorf("toml: decoding can only be performed into a pointer, not %s", r.Kind())
226
}
227
228
if r.IsNil() {
229
return fmt.Errorf("toml: decoding pointer target cannot be nil")
230
}
231
232
r = r.Elem()
233
if r.Kind() == reflect.Interface && r.IsNil() {
234
newMap := map[string]interface{}{}
235
r.Set(reflect.ValueOf(newMap))
236
}
237
238
err := d.fromParser(r)
239
if err == nil {
240
return d.strict.Error(d.p.Data())
241
}
242
243
var e *unstable.ParserError
244
if errors.As(err, &e) {
245
return wrapDecodeError(d.p.Data(), e)
246
}
247
248
return err
249
}
250
251
func (d *decoder) fromParser(root reflect.Value) error {
252
for d.nextExpr() {
253
err := d.handleRootExpression(d.expr(), root)
254
if err != nil {
255
return err
256
}
257
}
258
259
return d.p.Error()
260
}
261
262
/*
263
Rules for the unmarshal code:
264
265
- The stack is used to keep track of which values need to be set where.
266
- handle* functions <=> switch on a given unstable.Kind.
267
- unmarshalX* functions need to unmarshal a node of kind X.
268
- An "object" is either a struct or a map.
269
*/
270
271
func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) error {
272
var x reflect.Value
273
var err error
274
var first bool // used for to clear array tables on first use
275
276
if !(d.skipUntilTable && expr.Kind == unstable.KeyValue) {
277
first, err = d.seen.CheckExpression(expr)
278
if err != nil {
279
return err
280
}
281
}
282
283
switch expr.Kind {
284
case unstable.KeyValue:
285
if d.skipUntilTable {
286
return nil
287
}
288
x, err = d.handleKeyValue(expr, v)
289
case unstable.Table:
290
d.skipUntilTable = false
291
d.strict.EnterTable(expr)
292
x, err = d.handleTable(expr.Key(), v)
293
case unstable.ArrayTable:
294
d.skipUntilTable = false
295
d.strict.EnterArrayTable(expr)
296
d.clearArrayTable = first
297
x, err = d.handleArrayTable(expr.Key(), v)
298
default:
299
panic(fmt.Errorf("parser should not permit expression of kind %s at document root", expr.Kind))
300
}
301
302
if d.skipUntilTable {
303
if expr.Kind == unstable.Table || expr.Kind == unstable.ArrayTable {
304
d.strict.MissingTable(expr)
305
}
306
} else if err == nil && x.IsValid() {
307
v.Set(x)
308
}
309
310
return err
311
}
312
313
func (d *decoder) handleArrayTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
314
if key.Next() {
315
return d.handleArrayTablePart(key, v)
316
}
317
return d.handleKeyValues(v)
318
}
319
320
func (d *decoder) handleArrayTableCollectionLast(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
321
switch v.Kind() {
322
case reflect.Interface:
323
elem := v.Elem()
324
if !elem.IsValid() {
325
elem = reflect.New(sliceInterfaceType).Elem()
326
elem.Set(reflect.MakeSlice(sliceInterfaceType, 0, 16))
327
} else if elem.Kind() == reflect.Slice {
328
if elem.Type() != sliceInterfaceType {
329
elem = reflect.New(sliceInterfaceType).Elem()
330
elem.Set(reflect.MakeSlice(sliceInterfaceType, 0, 16))
331
} else if !elem.CanSet() {
332
nelem := reflect.New(sliceInterfaceType).Elem()
333
nelem.Set(reflect.MakeSlice(sliceInterfaceType, elem.Len(), elem.Cap()))
334
reflect.Copy(nelem, elem)
335
elem = nelem
336
}
337
if d.clearArrayTable && elem.Len() > 0 {
338
elem.SetLen(0)
339
d.clearArrayTable = false
340
}
341
}
342
return d.handleArrayTableCollectionLast(key, elem)
343
case reflect.Ptr:
344
elem := v.Elem()
345
if !elem.IsValid() {
346
ptr := reflect.New(v.Type().Elem())
347
v.Set(ptr)
348
elem = ptr.Elem()
349
}
350
351
elem, err := d.handleArrayTableCollectionLast(key, elem)
352
if err != nil {
353
return reflect.Value{}, err
354
}
355
v.Elem().Set(elem)
356
357
return v, nil
358
case reflect.Slice:
359
if d.clearArrayTable && v.Len() > 0 {
360
v.SetLen(0)
361
d.clearArrayTable = false
362
}
363
elemType := v.Type().Elem()
364
var elem reflect.Value
365
if elemType.Kind() == reflect.Interface {
366
elem = makeMapStringInterface()
367
} else {
368
elem = reflect.New(elemType).Elem()
369
}
370
elem2, err := d.handleArrayTable(key, elem)
371
if err != nil {
372
return reflect.Value{}, err
373
}
374
if elem2.IsValid() {
375
elem = elem2
376
}
377
return reflect.Append(v, elem), nil
378
case reflect.Array:
379
idx := d.arrayIndex(true, v)
380
if idx >= v.Len() {
381
return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx)
382
}
383
elem := v.Index(idx)
384
_, err := d.handleArrayTable(key, elem)
385
return v, err
386
default:
387
return reflect.Value{}, d.typeMismatchError("array table", v.Type())
388
}
389
}
390
391
// When parsing an array table expression, each part of the key needs to be
392
// evaluated like a normal key, but if it returns a collection, it also needs to
393
// point to the last element of the collection. Unless it is the last part of
394
// the key, then it needs to create a new element at the end.
395
func (d *decoder) handleArrayTableCollection(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
396
if key.IsLast() {
397
return d.handleArrayTableCollectionLast(key, v)
398
}
399
400
switch v.Kind() {
401
case reflect.Ptr:
402
elem := v.Elem()
403
if !elem.IsValid() {
404
ptr := reflect.New(v.Type().Elem())
405
v.Set(ptr)
406
elem = ptr.Elem()
407
}
408
409
elem, err := d.handleArrayTableCollection(key, elem)
410
if err != nil {
411
return reflect.Value{}, err
412
}
413
if elem.IsValid() {
414
v.Elem().Set(elem)
415
}
416
417
return v, nil
418
case reflect.Slice:
419
elem := v.Index(v.Len() - 1)
420
x, err := d.handleArrayTable(key, elem)
421
if err != nil || d.skipUntilTable {
422
return reflect.Value{}, err
423
}
424
if x.IsValid() {
425
elem.Set(x)
426
}
427
428
return v, err
429
case reflect.Array:
430
idx := d.arrayIndex(false, v)
431
if idx >= v.Len() {
432
return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx)
433
}
434
elem := v.Index(idx)
435
_, err := d.handleArrayTable(key, elem)
436
return v, err
437
}
438
439
return d.handleArrayTable(key, v)
440
}
441
442
func (d *decoder) handleKeyPart(key unstable.Iterator, v reflect.Value, nextFn handlerFn, makeFn valueMakerFn) (reflect.Value, error) {
443
var rv reflect.Value
444
445
// First, dispatch over v to make sure it is a valid object.
446
// There is no guarantee over what it could be.
447
switch v.Kind() {
448
case reflect.Ptr:
449
elem := v.Elem()
450
if !elem.IsValid() {
451
v.Set(reflect.New(v.Type().Elem()))
452
}
453
elem = v.Elem()
454
return d.handleKeyPart(key, elem, nextFn, makeFn)
455
case reflect.Map:
456
vt := v.Type()
457
458
// Create the key for the map element. Convert to key type.
459
mk, err := d.keyFromData(vt.Key(), key.Node().Data)
460
if err != nil {
461
return reflect.Value{}, err
462
}
463
464
// If the map does not exist, create it.
465
if v.IsNil() {
466
vt := v.Type()
467
v = reflect.MakeMap(vt)
468
rv = v
469
}
470
471
mv := v.MapIndex(mk)
472
set := false
473
if !mv.IsValid() {
474
// If there is no value in the map, create a new one according to
475
// the map type. If the element type is interface, create either a
476
// map[string]interface{} or a []interface{} depending on whether
477
// this is the last part of the array table key.
478
479
t := vt.Elem()
480
if t.Kind() == reflect.Interface {
481
mv = makeFn()
482
} else {
483
mv = reflect.New(t).Elem()
484
}
485
set = true
486
} else if mv.Kind() == reflect.Interface {
487
mv = mv.Elem()
488
if !mv.IsValid() {
489
mv = makeFn()
490
}
491
set = true
492
} else if !mv.CanAddr() {
493
vt := v.Type()
494
t := vt.Elem()
495
oldmv := mv
496
mv = reflect.New(t).Elem()
497
mv.Set(oldmv)
498
set = true
499
}
500
501
x, err := nextFn(key, mv)
502
if err != nil {
503
return reflect.Value{}, err
504
}
505
506
if x.IsValid() {
507
mv = x
508
set = true
509
}
510
511
if set {
512
v.SetMapIndex(mk, mv)
513
}
514
case reflect.Struct:
515
path, found := structFieldPath(v, string(key.Node().Data))
516
if !found {
517
d.skipUntilTable = true
518
return reflect.Value{}, nil
519
}
520
521
if d.errorContext == nil {
522
d.errorContext = new(errorContext)
523
}
524
t := v.Type()
525
d.errorContext.Struct = t
526
d.errorContext.Field = path
527
528
f := fieldByIndex(v, path)
529
x, err := nextFn(key, f)
530
if err != nil || d.skipUntilTable {
531
return reflect.Value{}, err
532
}
533
if x.IsValid() {
534
f.Set(x)
535
}
536
d.errorContext.Field = nil
537
d.errorContext.Struct = nil
538
case reflect.Interface:
539
if v.Elem().IsValid() {
540
v = v.Elem()
541
} else {
542
v = makeMapStringInterface()
543
}
544
545
x, err := d.handleKeyPart(key, v, nextFn, makeFn)
546
if err != nil {
547
return reflect.Value{}, err
548
}
549
if x.IsValid() {
550
v = x
551
}
552
rv = v
553
default:
554
panic(fmt.Errorf("unhandled part: %s", v.Kind()))
555
}
556
557
return rv, nil
558
}
559
560
// HandleArrayTablePart navigates the Go structure v using the key v. It is
561
// only used for the prefix (non-last) parts of an array-table. When
562
// encountering a collection, it should go to the last element.
563
func (d *decoder) handleArrayTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
564
var makeFn valueMakerFn
565
if key.IsLast() {
566
makeFn = makeSliceInterface
567
} else {
568
makeFn = makeMapStringInterface
569
}
570
return d.handleKeyPart(key, v, d.handleArrayTableCollection, makeFn)
571
}
572
573
// HandleTable returns a reference when it has checked the next expression but
574
// cannot handle it.
575
func (d *decoder) handleTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
576
if v.Kind() == reflect.Slice {
577
if v.Len() == 0 {
578
return reflect.Value{}, unstable.NewParserError(key.Node().Data, "cannot store a table in a slice")
579
}
580
elem := v.Index(v.Len() - 1)
581
x, err := d.handleTable(key, elem)
582
if err != nil {
583
return reflect.Value{}, err
584
}
585
if x.IsValid() {
586
elem.Set(x)
587
}
588
return reflect.Value{}, nil
589
}
590
if key.Next() {
591
// Still scoping the key
592
return d.handleTablePart(key, v)
593
}
594
// Done scoping the key.
595
// Now handle all the key-value expressions in this table.
596
return d.handleKeyValues(v)
597
}
598
599
// Handle root expressions until the end of the document or the next
600
// non-key-value.
601
func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) {
602
var rv reflect.Value
603
for d.nextExpr() {
604
expr := d.expr()
605
if expr.Kind != unstable.KeyValue {
606
// Stash the expression so that fromParser can just loop and use
607
// the right handler.
608
// We could just recurse ourselves here, but at least this gives a
609
// chance to pop the stack a bit.
610
d.stashExpr()
611
break
612
}
613
614
_, err := d.seen.CheckExpression(expr)
615
if err != nil {
616
return reflect.Value{}, err
617
}
618
619
x, err := d.handleKeyValue(expr, v)
620
if err != nil {
621
return reflect.Value{}, err
622
}
623
if x.IsValid() {
624
v = x
625
rv = x
626
}
627
}
628
return rv, nil
629
}
630
631
type (
632
handlerFn func(key unstable.Iterator, v reflect.Value) (reflect.Value, error)
633
valueMakerFn func() reflect.Value
634
)
635
636
func makeMapStringInterface() reflect.Value {
637
return reflect.MakeMap(mapStringInterfaceType)
638
}
639
640
func makeSliceInterface() reflect.Value {
641
return reflect.MakeSlice(sliceInterfaceType, 0, 16)
642
}
643
644
func (d *decoder) handleTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
645
return d.handleKeyPart(key, v, d.handleTable, makeMapStringInterface)
646
}
647
648
func (d *decoder) tryTextUnmarshaler(node *unstable.Node, v reflect.Value) (bool, error) {
649
// Special case for time, because we allow to unmarshal to it from
650
// different kind of AST nodes.
651
if v.Type() == timeType {
652
return false, nil
653
}
654
655
if v.CanAddr() && v.Addr().Type().Implements(textUnmarshalerType) {
656
err := v.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText(node.Data)
657
if err != nil {
658
return false, unstable.NewParserError(d.p.Raw(node.Raw), "%w", err)
659
}
660
661
return true, nil
662
}
663
664
return false, nil
665
}
666
667
func (d *decoder) handleValue(value *unstable.Node, v reflect.Value) error {
668
for v.Kind() == reflect.Ptr {
669
v = initAndDereferencePointer(v)
670
}
671
672
if d.unmarshalerInterface {
673
if v.CanAddr() && v.Addr().CanInterface() {
674
if outi, ok := v.Addr().Interface().(unstable.Unmarshaler); ok {
675
return outi.UnmarshalTOML(value)
676
}
677
}
678
}
679
680
ok, err := d.tryTextUnmarshaler(value, v)
681
if ok || err != nil {
682
return err
683
}
684
685
switch value.Kind {
686
case unstable.String:
687
return d.unmarshalString(value, v)
688
case unstable.Integer:
689
return d.unmarshalInteger(value, v)
690
case unstable.Float:
691
return d.unmarshalFloat(value, v)
692
case unstable.Bool:
693
return d.unmarshalBool(value, v)
694
case unstable.DateTime:
695
return d.unmarshalDateTime(value, v)
696
case unstable.LocalDate:
697
return d.unmarshalLocalDate(value, v)
698
case unstable.LocalTime:
699
return d.unmarshalLocalTime(value, v)
700
case unstable.LocalDateTime:
701
return d.unmarshalLocalDateTime(value, v)
702
case unstable.InlineTable:
703
return d.unmarshalInlineTable(value, v)
704
case unstable.Array:
705
return d.unmarshalArray(value, v)
706
default:
707
panic(fmt.Errorf("handleValue not implemented for %s", value.Kind))
708
}
709
}
710
711
func (d *decoder) unmarshalArray(array *unstable.Node, v reflect.Value) error {
712
switch v.Kind() {
713
case reflect.Slice:
714
if v.IsNil() {
715
v.Set(reflect.MakeSlice(v.Type(), 0, 16))
716
} else {
717
v.SetLen(0)
718
}
719
case reflect.Array:
720
// arrays are always initialized
721
case reflect.Interface:
722
elem := v.Elem()
723
if !elem.IsValid() {
724
elem = reflect.New(sliceInterfaceType).Elem()
725
elem.Set(reflect.MakeSlice(sliceInterfaceType, 0, 16))
726
} else if elem.Kind() == reflect.Slice {
727
if elem.Type() != sliceInterfaceType {
728
elem = reflect.New(sliceInterfaceType).Elem()
729
elem.Set(reflect.MakeSlice(sliceInterfaceType, 0, 16))
730
} else if !elem.CanSet() {
731
nelem := reflect.New(sliceInterfaceType).Elem()
732
nelem.Set(reflect.MakeSlice(sliceInterfaceType, elem.Len(), elem.Cap()))
733
reflect.Copy(nelem, elem)
734
elem = nelem
735
}
736
}
737
err := d.unmarshalArray(array, elem)
738
if err != nil {
739
return err
740
}
741
v.Set(elem)
742
return nil
743
default:
744
// TODO: use newDecodeError, but first the parser needs to fill
745
// array.Data.
746
return d.typeMismatchError("array", v.Type())
747
}
748
749
elemType := v.Type().Elem()
750
751
it := array.Children()
752
idx := 0
753
for it.Next() {
754
n := it.Node()
755
756
// TODO: optimize
757
if v.Kind() == reflect.Slice {
758
elem := reflect.New(elemType).Elem()
759
760
err := d.handleValue(n, elem)
761
if err != nil {
762
return err
763
}
764
765
v.Set(reflect.Append(v, elem))
766
} else { // array
767
if idx >= v.Len() {
768
return nil
769
}
770
elem := v.Index(idx)
771
err := d.handleValue(n, elem)
772
if err != nil {
773
return err
774
}
775
idx++
776
}
777
}
778
779
return nil
780
}
781
782
func (d *decoder) unmarshalInlineTable(itable *unstable.Node, v reflect.Value) error {
783
// Make sure v is an initialized object.
784
switch v.Kind() {
785
case reflect.Map:
786
if v.IsNil() {
787
v.Set(reflect.MakeMap(v.Type()))
788
}
789
case reflect.Struct:
790
// structs are always initialized.
791
case reflect.Interface:
792
elem := v.Elem()
793
if !elem.IsValid() {
794
elem = makeMapStringInterface()
795
v.Set(elem)
796
}
797
return d.unmarshalInlineTable(itable, elem)
798
default:
799
return unstable.NewParserError(d.p.Raw(itable.Raw), "cannot store inline table in Go type %s", v.Kind())
800
}
801
802
it := itable.Children()
803
for it.Next() {
804
n := it.Node()
805
806
x, err := d.handleKeyValue(n, v)
807
if err != nil {
808
return err
809
}
810
if x.IsValid() {
811
v = x
812
}
813
}
814
815
return nil
816
}
817
818
func (d *decoder) unmarshalDateTime(value *unstable.Node, v reflect.Value) error {
819
dt, err := parseDateTime(value.Data)
820
if err != nil {
821
return err
822
}
823
824
v.Set(reflect.ValueOf(dt))
825
return nil
826
}
827
828
func (d *decoder) unmarshalLocalDate(value *unstable.Node, v reflect.Value) error {
829
ld, err := parseLocalDate(value.Data)
830
if err != nil {
831
return err
832
}
833
834
if v.Type() == timeType {
835
cast := ld.AsTime(time.Local)
836
v.Set(reflect.ValueOf(cast))
837
return nil
838
}
839
840
v.Set(reflect.ValueOf(ld))
841
842
return nil
843
}
844
845
func (d *decoder) unmarshalLocalTime(value *unstable.Node, v reflect.Value) error {
846
lt, rest, err := parseLocalTime(value.Data)
847
if err != nil {
848
return err
849
}
850
851
if len(rest) > 0 {
852
return unstable.NewParserError(rest, "extra characters at the end of a local time")
853
}
854
855
v.Set(reflect.ValueOf(lt))
856
return nil
857
}
858
859
func (d *decoder) unmarshalLocalDateTime(value *unstable.Node, v reflect.Value) error {
860
ldt, rest, err := parseLocalDateTime(value.Data)
861
if err != nil {
862
return err
863
}
864
865
if len(rest) > 0 {
866
return unstable.NewParserError(rest, "extra characters at the end of a local date time")
867
}
868
869
if v.Type() == timeType {
870
cast := ldt.AsTime(time.Local)
871
872
v.Set(reflect.ValueOf(cast))
873
return nil
874
}
875
876
v.Set(reflect.ValueOf(ldt))
877
878
return nil
879
}
880
881
func (d *decoder) unmarshalBool(value *unstable.Node, v reflect.Value) error {
882
b := value.Data[0] == 't'
883
884
switch v.Kind() {
885
case reflect.Bool:
886
v.SetBool(b)
887
case reflect.Interface:
888
v.Set(reflect.ValueOf(b))
889
default:
890
return unstable.NewParserError(value.Data, "cannot assign boolean to a %t", b)
891
}
892
893
return nil
894
}
895
896
func (d *decoder) unmarshalFloat(value *unstable.Node, v reflect.Value) error {
897
f, err := parseFloat(value.Data)
898
if err != nil {
899
return err
900
}
901
902
switch v.Kind() {
903
case reflect.Float64:
904
v.SetFloat(f)
905
case reflect.Float32:
906
if f > math.MaxFloat32 {
907
return unstable.NewParserError(value.Data, "number %f does not fit in a float32", f)
908
}
909
v.SetFloat(f)
910
case reflect.Interface:
911
v.Set(reflect.ValueOf(f))
912
default:
913
return unstable.NewParserError(value.Data, "float cannot be assigned to %s", v.Kind())
914
}
915
916
return nil
917
}
918
919
const (
920
maxInt = int64(^uint(0) >> 1)
921
minInt = -maxInt - 1
922
)
923
924
// Maximum value of uint for decoding. Currently the decoder parses the integer
925
// into an int64. As a result, on architectures where uint is 64 bits, the
926
// effective maximum uint we can decode is the maximum of int64. On
927
// architectures where uint is 32 bits, the maximum value we can decode is
928
// lower: the maximum of uint32. I didn't find a way to figure out this value at
929
// compile time, so it is computed during initialization.
930
var maxUint int64 = math.MaxInt64
931
932
func init() {
933
m := uint64(^uint(0))
934
if m < uint64(maxUint) {
935
maxUint = int64(m)
936
}
937
}
938
939
func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error {
940
kind := v.Kind()
941
if kind == reflect.Float32 || kind == reflect.Float64 {
942
return d.unmarshalFloat(value, v)
943
}
944
945
i, err := parseInteger(value.Data)
946
if err != nil {
947
return err
948
}
949
950
var r reflect.Value
951
952
switch kind {
953
case reflect.Int64:
954
v.SetInt(i)
955
return nil
956
case reflect.Int32:
957
if i < math.MinInt32 || i > math.MaxInt32 {
958
return fmt.Errorf("toml: number %d does not fit in an int32", i)
959
}
960
961
r = reflect.ValueOf(int32(i))
962
case reflect.Int16:
963
if i < math.MinInt16 || i > math.MaxInt16 {
964
return fmt.Errorf("toml: number %d does not fit in an int16", i)
965
}
966
967
r = reflect.ValueOf(int16(i))
968
case reflect.Int8:
969
if i < math.MinInt8 || i > math.MaxInt8 {
970
return fmt.Errorf("toml: number %d does not fit in an int8", i)
971
}
972
973
r = reflect.ValueOf(int8(i))
974
case reflect.Int:
975
if i < minInt || i > maxInt {
976
return fmt.Errorf("toml: number %d does not fit in an int", i)
977
}
978
979
r = reflect.ValueOf(int(i))
980
case reflect.Uint64:
981
if i < 0 {
982
return fmt.Errorf("toml: negative number %d does not fit in an uint64", i)
983
}
984
985
r = reflect.ValueOf(uint64(i))
986
case reflect.Uint32:
987
if i < 0 || i > math.MaxUint32 {
988
return fmt.Errorf("toml: negative number %d does not fit in an uint32", i)
989
}
990
991
r = reflect.ValueOf(uint32(i))
992
case reflect.Uint16:
993
if i < 0 || i > math.MaxUint16 {
994
return fmt.Errorf("toml: negative number %d does not fit in an uint16", i)
995
}
996
997
r = reflect.ValueOf(uint16(i))
998
case reflect.Uint8:
999
if i < 0 || i > math.MaxUint8 {
1000
return fmt.Errorf("toml: negative number %d does not fit in an uint8", i)
1001
}
1002
1003
r = reflect.ValueOf(uint8(i))
1004
case reflect.Uint:
1005
if i < 0 || i > maxUint {
1006
return fmt.Errorf("toml: negative number %d does not fit in an uint", i)
1007
}
1008
1009
r = reflect.ValueOf(uint(i))
1010
case reflect.Interface:
1011
r = reflect.ValueOf(i)
1012
default:
1013
return unstable.NewParserError(d.p.Raw(value.Raw), d.typeMismatchString("integer", v.Type()))
1014
}
1015
1016
if !r.Type().AssignableTo(v.Type()) {
1017
r = r.Convert(v.Type())
1018
}
1019
1020
v.Set(r)
1021
1022
return nil
1023
}
1024
1025
func (d *decoder) unmarshalString(value *unstable.Node, v reflect.Value) error {
1026
switch v.Kind() {
1027
case reflect.String:
1028
v.SetString(string(value.Data))
1029
case reflect.Interface:
1030
v.Set(reflect.ValueOf(string(value.Data)))
1031
default:
1032
return unstable.NewParserError(d.p.Raw(value.Raw), d.typeMismatchString("string", v.Type()))
1033
}
1034
1035
return nil
1036
}
1037
1038
func (d *decoder) handleKeyValue(expr *unstable.Node, v reflect.Value) (reflect.Value, error) {
1039
d.strict.EnterKeyValue(expr)
1040
1041
v, err := d.handleKeyValueInner(expr.Key(), expr.Value(), v)
1042
if d.skipUntilTable {
1043
d.strict.MissingField(expr)
1044
d.skipUntilTable = false
1045
}
1046
1047
d.strict.ExitKeyValue(expr)
1048
1049
return v, err
1050
}
1051
1052
func (d *decoder) handleKeyValueInner(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) {
1053
if key.Next() {
1054
// Still scoping the key
1055
return d.handleKeyValuePart(key, value, v)
1056
}
1057
// Done scoping the key.
1058
// v is whatever Go value we need to fill.
1059
return reflect.Value{}, d.handleValue(value, v)
1060
}
1061
1062
func (d *decoder) keyFromData(keyType reflect.Type, data []byte) (reflect.Value, error) {
1063
switch {
1064
case stringType.AssignableTo(keyType):
1065
return reflect.ValueOf(string(data)), nil
1066
1067
case stringType.ConvertibleTo(keyType):
1068
return reflect.ValueOf(string(data)).Convert(keyType), nil
1069
1070
case keyType.Implements(textUnmarshalerType):
1071
mk := reflect.New(keyType.Elem())
1072
if err := mk.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
1073
return reflect.Value{}, fmt.Errorf("toml: error unmarshalling key type %s from text: %w", stringType, err)
1074
}
1075
return mk, nil
1076
1077
case reflect.PointerTo(keyType).Implements(textUnmarshalerType):
1078
mk := reflect.New(keyType)
1079
if err := mk.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
1080
return reflect.Value{}, fmt.Errorf("toml: error unmarshalling key type %s from text: %w", stringType, err)
1081
}
1082
return mk.Elem(), nil
1083
1084
case keyType.Kind() == reflect.Int || keyType.Kind() == reflect.Int8 || keyType.Kind() == reflect.Int16 || keyType.Kind() == reflect.Int32 || keyType.Kind() == reflect.Int64:
1085
key, err := strconv.ParseInt(string(data), 10, 64)
1086
if err != nil {
1087
return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from integer: %w", stringType, err)
1088
}
1089
return reflect.ValueOf(key).Convert(keyType), nil
1090
case keyType.Kind() == reflect.Uint || keyType.Kind() == reflect.Uint8 || keyType.Kind() == reflect.Uint16 || keyType.Kind() == reflect.Uint32 || keyType.Kind() == reflect.Uint64:
1091
key, err := strconv.ParseUint(string(data), 10, 64)
1092
if err != nil {
1093
return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from unsigned integer: %w", stringType, err)
1094
}
1095
return reflect.ValueOf(key).Convert(keyType), nil
1096
1097
case keyType.Kind() == reflect.Float32:
1098
key, err := strconv.ParseFloat(string(data), 32)
1099
if err != nil {
1100
return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from float: %w", stringType, err)
1101
}
1102
return reflect.ValueOf(float32(key)), nil
1103
1104
case keyType.Kind() == reflect.Float64:
1105
key, err := strconv.ParseFloat(string(data), 64)
1106
if err != nil {
1107
return reflect.Value{}, fmt.Errorf("toml: error parsing key of type %s from float: %w", stringType, err)
1108
}
1109
return reflect.ValueOf(float64(key)), nil
1110
}
1111
return reflect.Value{}, fmt.Errorf("toml: cannot convert map key of type %s to expected type %s", stringType, keyType)
1112
}
1113
1114
func (d *decoder) handleKeyValuePart(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) {
1115
// contains the replacement for v
1116
var rv reflect.Value
1117
1118
// First, dispatch over v to make sure it is a valid object.
1119
// There is no guarantee over what it could be.
1120
switch v.Kind() {
1121
case reflect.Map:
1122
vt := v.Type()
1123
1124
mk, err := d.keyFromData(vt.Key(), key.Node().Data)
1125
if err != nil {
1126
return reflect.Value{}, err
1127
}
1128
1129
// If the map does not exist, create it.
1130
if v.IsNil() {
1131
v = reflect.MakeMap(vt)
1132
rv = v
1133
}
1134
1135
mv := v.MapIndex(mk)
1136
set := false
1137
if !mv.IsValid() || key.IsLast() {
1138
set = true
1139
mv = reflect.New(v.Type().Elem()).Elem()
1140
}
1141
1142
nv, err := d.handleKeyValueInner(key, value, mv)
1143
if err != nil {
1144
return reflect.Value{}, err
1145
}
1146
if nv.IsValid() {
1147
mv = nv
1148
set = true
1149
}
1150
1151
if set {
1152
v.SetMapIndex(mk, mv)
1153
}
1154
case reflect.Struct:
1155
path, found := structFieldPath(v, string(key.Node().Data))
1156
if !found {
1157
d.skipUntilTable = true
1158
break
1159
}
1160
1161
if d.errorContext == nil {
1162
d.errorContext = new(errorContext)
1163
}
1164
t := v.Type()
1165
d.errorContext.Struct = t
1166
d.errorContext.Field = path
1167
1168
f := fieldByIndex(v, path)
1169
1170
if !f.CanAddr() {
1171
// If the field is not addressable, need to take a slower path and
1172
// make a copy of the struct itself to a new location.
1173
nvp := reflect.New(v.Type())
1174
nvp.Elem().Set(v)
1175
v = nvp.Elem()
1176
_, err := d.handleKeyValuePart(key, value, v)
1177
if err != nil {
1178
return reflect.Value{}, err
1179
}
1180
return nvp.Elem(), nil
1181
}
1182
x, err := d.handleKeyValueInner(key, value, f)
1183
if err != nil {
1184
return reflect.Value{}, err
1185
}
1186
1187
if x.IsValid() {
1188
f.Set(x)
1189
}
1190
d.errorContext.Struct = nil
1191
d.errorContext.Field = nil
1192
case reflect.Interface:
1193
v = v.Elem()
1194
1195
// Following encoding/json: decoding an object into an
1196
// interface{}, it needs to always hold a
1197
// map[string]interface{}. This is for the types to be
1198
// consistent whether a previous value was set or not.
1199
if !v.IsValid() || v.Type() != mapStringInterfaceType {
1200
v = makeMapStringInterface()
1201
}
1202
1203
x, err := d.handleKeyValuePart(key, value, v)
1204
if err != nil {
1205
return reflect.Value{}, err
1206
}
1207
if x.IsValid() {
1208
v = x
1209
}
1210
rv = v
1211
case reflect.Ptr:
1212
elem := v.Elem()
1213
if !elem.IsValid() {
1214
ptr := reflect.New(v.Type().Elem())
1215
v.Set(ptr)
1216
rv = v
1217
elem = ptr.Elem()
1218
}
1219
1220
elem2, err := d.handleKeyValuePart(key, value, elem)
1221
if err != nil {
1222
return reflect.Value{}, err
1223
}
1224
if elem2.IsValid() {
1225
elem = elem2
1226
}
1227
v.Elem().Set(elem)
1228
default:
1229
return reflect.Value{}, fmt.Errorf("unhandled kv part: %s", v.Kind())
1230
}
1231
1232
return rv, nil
1233
}
1234
1235
func initAndDereferencePointer(v reflect.Value) reflect.Value {
1236
var elem reflect.Value
1237
if v.IsNil() {
1238
ptr := reflect.New(v.Type().Elem())
1239
v.Set(ptr)
1240
}
1241
elem = v.Elem()
1242
return elem
1243
}
1244
1245
// Same as reflect.Value.FieldByIndex, but creates pointers if needed.
1246
func fieldByIndex(v reflect.Value, path []int) reflect.Value {
1247
for _, x := range path {
1248
v = v.Field(x)
1249
1250
if v.Kind() == reflect.Ptr {
1251
if v.IsNil() {
1252
v.Set(reflect.New(v.Type().Elem()))
1253
}
1254
v = v.Elem()
1255
}
1256
}
1257
return v
1258
}
1259
1260
type fieldPathsMap = map[string][]int
1261
1262
var globalFieldPathsCache atomic.Value // map[danger.TypeID]fieldPathsMap
1263
1264
func structFieldPath(v reflect.Value, name string) ([]int, bool) {
1265
t := v.Type()
1266
1267
cache, _ := globalFieldPathsCache.Load().(map[danger.TypeID]fieldPathsMap)
1268
fieldPaths, ok := cache[danger.MakeTypeID(t)]
1269
1270
if !ok {
1271
fieldPaths = map[string][]int{}
1272
1273
forEachField(t, nil, func(name string, path []int) {
1274
fieldPaths[name] = path
1275
// extra copy for the case-insensitive match
1276
fieldPaths[strings.ToLower(name)] = path
1277
})
1278
1279
newCache := make(map[danger.TypeID]fieldPathsMap, len(cache)+1)
1280
newCache[danger.MakeTypeID(t)] = fieldPaths
1281
for k, v := range cache {
1282
newCache[k] = v
1283
}
1284
globalFieldPathsCache.Store(newCache)
1285
}
1286
1287
path, ok := fieldPaths[name]
1288
if !ok {
1289
path, ok = fieldPaths[strings.ToLower(name)]
1290
}
1291
return path, ok
1292
}
1293
1294
func forEachField(t reflect.Type, path []int, do func(name string, path []int)) {
1295
n := t.NumField()
1296
for i := 0; i < n; i++ {
1297
f := t.Field(i)
1298
1299
if !f.Anonymous && f.PkgPath != "" {
1300
// only consider exported fields.
1301
continue
1302
}
1303
1304
fieldPath := append(path, i)
1305
fieldPath = fieldPath[:len(fieldPath):len(fieldPath)]
1306
1307
name := f.Tag.Get("toml")
1308
if name == "-" {
1309
continue
1310
}
1311
1312
if i := strings.IndexByte(name, ','); i >= 0 {
1313
name = name[:i]
1314
}
1315
1316
if f.Anonymous && name == "" {
1317
t2 := f.Type
1318
if t2.Kind() == reflect.Ptr {
1319
t2 = t2.Elem()
1320
}
1321
1322
if t2.Kind() == reflect.Struct {
1323
forEachField(t2, fieldPath, do)
1324
}
1325
continue
1326
}
1327
1328
if name == "" {
1329
name = f.Name
1330
}
1331
1332
do(name, fieldPath)
1333
}
1334
}
1335
1336