Debian Codegraph @

internal/golang/encoding/json/decode.go

raw symbols SCIP
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Represents JSON data structure using native Go types: booleans, floats,
6 // strings, arrays, and maps.
7
8 package json
9
10 import (
11 "encoding"
12 "encoding/base64"
13 "fmt"
14 "reflect"
15 "strconv"
16 "strings"
17 "unicode"
18 "unicode/utf16"
19 "unicode/utf8"
20 )
21
22 // Unmarshal parses the JSON-encoded data and stores the result
23 // in the value pointed to by v. If v is nil or not a pointer,
24 // Unmarshal returns an [InvalidUnmarshalError].
25 //
26 // Unmarshal uses the inverse of the encodings that
27 // [Marshal] uses, allocating maps, slices, and pointers as necessary,
28 // with the following additional rules:
29 //
30 // To unmarshal JSON into a pointer, Unmarshal first handles the case of
31 // the JSON being the JSON literal null. In that case, Unmarshal sets
32 // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into
33 // the value pointed at by the pointer. If the pointer is nil, Unmarshal
34 // allocates a new value for it to point to.
35 //
36 // To unmarshal JSON into a value implementing [Unmarshaler],
37 // Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including
38 // when the input is a JSON null.
39 // Otherwise, if the value implements [encoding.TextUnmarshaler]
40 // and the input is a JSON quoted string, Unmarshal calls
41 // [encoding.TextUnmarshaler.UnmarshalText] with the unquoted form of the string.
42 //
43 // To unmarshal JSON into a struct, Unmarshal matches incoming object
44 // keys to the keys used by [Marshal] (either the struct field name or its tag),
45 // preferring an exact match but also accepting a case-insensitive match. By
46 // default, object keys which don't have a corresponding struct field are
47 // ignored (see [Decoder.DisallowUnknownFields] for an alternative).
48 //
49 // To unmarshal JSON into an interface value,
50 // Unmarshal stores one of these in the interface value:
51 //
52 // - bool, for JSON booleans
53 // - float64, for JSON numbers
54 // - string, for JSON strings
55 // - []interface{}, for JSON arrays
56 // - map[string]interface{}, for JSON objects
57 // - nil for JSON null
58 //
59 // To unmarshal a JSON array into a slice, Unmarshal resets the slice length
60 // to zero and then appends each element to the slice.
61 // As a special case, to unmarshal an empty JSON array into a slice,
62 // Unmarshal replaces the slice with a new empty slice.
63 //
64 // To unmarshal a JSON array into a Go array, Unmarshal decodes
65 // JSON array elements into corresponding Go array elements.
66 // If the Go array is smaller than the JSON array,
67 // the additional JSON array elements are discarded.
68 // If the JSON array is smaller than the Go array,
69 // the additional Go array elements are set to zero values.
70 //
71 // To unmarshal a JSON object into a map, Unmarshal first establishes a map to
72 // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
73 // reuses the existing map, keeping existing entries. Unmarshal then stores
74 // key-value pairs from the JSON object into the map. The map's key type must
75 // either be any string type, an integer, or implement [encoding.TextUnmarshaler].
76 //
77 // If the JSON-encoded data contain a syntax error, Unmarshal returns a [SyntaxError].
78 //
79 // If a JSON value is not appropriate for a given target type,
80 // or if a JSON number overflows the target type, Unmarshal
81 // skips that field and completes the unmarshaling as best it can.
82 // If no more serious errors are encountered, Unmarshal returns
83 // an [UnmarshalTypeError] describing the earliest such error. In any
84 // case, it's not guaranteed that all the remaining fields following
85 // the problematic one will be unmarshaled into the target object.
86 //
87 // The JSON null value unmarshals into an interface, map, pointer, or slice
88 // by setting that Go value to nil. Because null is often used in JSON to mean
89 // “not present,” unmarshaling a JSON null into any other Go type has no effect
90 // on the value and produces no error.
91 //
92 // When unmarshaling quoted strings, invalid UTF-8 or
93 // invalid UTF-16 surrogate pairs are not treated as an error.
94 // Instead, they are replaced by the Unicode replacement
95 // character U+FFFD.
96 func Unmarshal(data []byte, v any, opts ...UnmarshalOpt) error {
97 // Check for well-formedness.
98 // Avoids filling out half a data structure
99 // before discovering a JSON syntax error.
100 var d decodeState
101
102 for _, opt := range opts {
103 opt(&d)
104 }
105
106 err := checkValid(data, &d.scan)
107 if err != nil {
108 return err
109 }
110
111 d.init(data)
112 return d.unmarshal(v)
113 }
114
115 // Unmarshaler is the interface implemented by types
116 // that can unmarshal a JSON description of themselves.
117 // The input can be assumed to be a valid encoding of
118 // a JSON value. UnmarshalJSON must copy the JSON data
119 // if it wishes to retain the data after returning.
120 //
121 // By convention, to approximate the behavior of [Unmarshal] itself,
122 // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
123 type Unmarshaler interface {
124 UnmarshalJSON([]byte) error
125 }
126
127 /*
128 // An UnmarshalTypeError describes a JSON value that was
129 // not appropriate for a value of a specific Go type.
130 type UnmarshalTypeError struct {
131 Value string // description of JSON value - "bool", "array", "number -5"
132 Type reflect.Type // type of Go value it could not be assigned to
133 Offset int64 // error occurred after reading Offset bytes
134 Struct string // name of the struct type containing the field
135 Field string // the full path from root node to the field
136 }
137
138 func (e *UnmarshalTypeError) Error() string {
139 if e.Struct != "" || e.Field != "" {
140 return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String()
141 }
142 return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
143 }
144
145 // An UnmarshalFieldError describes a JSON object key that
146 // led to an unexported (and therefore unwritable) struct field.
147 //
148 // Deprecated: No longer used; kept for compatibility.
149 type UnmarshalFieldError struct {
150 Key string
151 Type reflect.Type
152 Field reflect.StructField
153 }
154
155 func (e *UnmarshalFieldError) Error() string {
156 return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
157 }
158
159 // An InvalidUnmarshalError describes an invalid argument passed to [Unmarshal].
160 // (The argument to [Unmarshal] must be a non-nil pointer.)
161 type InvalidUnmarshalError struct {
162 Type reflect.Type
163 }
164
165 func (e *InvalidUnmarshalError) Error() string {
166 if e.Type == nil {
167 return "json: Unmarshal(nil)"
168 }
169
170 if e.Type.Kind() != reflect.Pointer {
171 return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
172 }
173 return "json: Unmarshal(nil " + e.Type.String() + ")"
174 }
175 */
176
177 func (d *decodeState) unmarshal(v any) error {
178 rv := reflect.ValueOf(v)
179 if rv.Kind() != reflect.Pointer || rv.IsNil() {
180 return &InvalidUnmarshalError{reflect.TypeOf(v)}
181 }
182
183 d.scan.reset()
184 d.scanWhile(scanSkipSpace)
185 // We decode rv not rv.Elem because the Unmarshaler interface
186 // test must be applied at the top level of the value.
187 err := d.value(rv)
188 if err != nil {
189 return d.addErrorContext(err)
190 }
191 if d.savedError != nil {
192 return d.savedError
193 }
194 if len(d.savedStrictErrors) > 0 {
195 return &UnmarshalStrictError{Errors: d.savedStrictErrors}
196 }
197 return nil
198 }
199
200 /*
201 // A Number represents a JSON number literal.
202 type Number string
203
204 // String returns the literal text of the number.
205 func (n Number) String() string { return string(n) }
206
207 // Float64 returns the number as a float64.
208 func (n Number) Float64() (float64, error) {
209 return strconv.ParseFloat(string(n), 64)
210 }
211
212 // Int64 returns the number as an int64.
213 func (n Number) Int64() (int64, error) {
214 return strconv.ParseInt(string(n), 10, 64)
215 }
216 */
217
218 // An errorContext provides context for type errors during decoding.
219 type errorContext struct {
220 Struct reflect.Type
221 FieldStack []string
222 }
223
224 // decodeState represents the state while decoding a JSON value.
225 type decodeState struct {
226 data []byte
227 off int // next read offset in data
228 opcode int // last read result
229 scan scanner
230 errorContext *errorContext
231 savedError error
232 useNumber bool
233 disallowUnknownFields bool
234
235 savedStrictErrors []error
236 seenStrictErrors map[strictError]struct{}
237 strictFieldStack []string
238
239 caseSensitive bool
240
241 preserveInts bool
242
243 disallowDuplicateFields bool
244 }
245
246 // readIndex returns the position of the last byte read.
247 func (d *decodeState) readIndex() int {
248 return d.off - 1
249 }
250
251 // phasePanicMsg is used as a panic message when we end up with something that
252 // shouldn't happen. It can indicate a bug in the JSON decoder, or that
253 // something is editing the data slice while the decoder executes.
254 const phasePanicMsg = "JSON decoder out of sync - data changing underfoot?"
255
256 func (d *decodeState) init(data []byte) *decodeState {
257 d.data = data
258 d.off = 0
259 d.savedError = nil
260 if d.errorContext != nil {
261 d.errorContext.Struct = nil
262 // Reuse the allocated space for the FieldStack slice.
263 d.errorContext.FieldStack = d.errorContext.FieldStack[:0]
264 }
265 // Reuse the allocated space for the strict FieldStack slice.
266 d.strictFieldStack = d.strictFieldStack[:0]
267 return d
268 }
269
270 // saveError saves the first err it is called with,
271 // for reporting at the end of the unmarshal.
272 func (d *decodeState) saveError(err error) {
273 if d.savedError == nil {
274 d.savedError = d.addErrorContext(err)
275 }
276 }
277
278 // addErrorContext returns a new error enhanced with information from d.errorContext
279 func (d *decodeState) addErrorContext(err error) error {
280 if d.errorContext != nil && (d.errorContext.Struct != nil || len(d.errorContext.FieldStack) > 0) {
281 switch err := err.(type) {
282 case *UnmarshalTypeError:
283 err.Struct = d.errorContext.Struct.Name()
284 err.Field = strings.Join(d.errorContext.FieldStack, ".")
285 }
286 }
287 return err
288 }
289
290 // skip scans to the end of what was started.
291 func (d *decodeState) skip() {
292 s, data, i := &d.scan, d.data, d.off
293 depth := len(s.parseState)
294 for {
295 op := s.step(s, data[i])
296 i++
297 if len(s.parseState) < depth {
298 d.off = i
299 d.opcode = op
300 return
301 }
302 }
303 }
304
305 // scanNext processes the byte at d.data[d.off].
306 func (d *decodeState) scanNext() {
307 if d.off < len(d.data) {
308 d.opcode = d.scan.step(&d.scan, d.data[d.off])
309 d.off++
310 } else {
311 d.opcode = d.scan.eof()
312 d.off = len(d.data) + 1 // mark processed EOF with len+1
313 }
314 }
315
316 // scanWhile processes bytes in d.data[d.off:] until it
317 // receives a scan code not equal to op.
318 func (d *decodeState) scanWhile(op int) {
319 s, data, i := &d.scan, d.data, d.off
320 for i < len(data) {
321 newOp := s.step(s, data[i])
322 i++
323 if newOp != op {
324 d.opcode = newOp
325 d.off = i
326 return
327 }
328 }
329
330 d.off = len(data) + 1 // mark processed EOF with len+1
331 d.opcode = d.scan.eof()
332 }
333
334 // rescanLiteral is similar to scanWhile(scanContinue), but it specialises the
335 // common case where we're decoding a literal. The decoder scans the input
336 // twice, once for syntax errors and to check the length of the value, and the
337 // second to perform the decoding.
338 //
339 // Only in the second step do we use decodeState to tokenize literals, so we
340 // know there aren't any syntax errors. We can take advantage of that knowledge,
341 // and scan a literal's bytes much more quickly.
342 func (d *decodeState) rescanLiteral() {
343 data, i := d.data, d.off
344 Switch:
345 switch data[i-1] {
346 case '"': // string
347 for ; i < len(data); i++ {
348 switch data[i] {
349 case '\\':
350 i++ // escaped char
351 case '"':
352 i++ // tokenize the closing quote too
353 break Switch
354 }
355 }
356 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': // number
357 for ; i < len(data); i++ {
358 switch data[i] {
359 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
360 '.', 'e', 'E', '+', '-':
361 default:
362 break Switch
363 }
364 }
365 case 't': // true
366 i += len("rue")
367 case 'f': // false
368 i += len("alse")
369 case 'n': // null
370 i += len("ull")
371 }
372 if i < len(data) {
373 d.opcode = stateEndValue(&d.scan, data[i])
374 } else {
375 d.opcode = scanEnd
376 }
377 d.off = i + 1
378 }
379
380 // value consumes a JSON value from d.data[d.off-1:], decoding into v, and
381 // reads the following byte ahead. If v is invalid, the value is discarded.
382 // The first byte of the value has been read already.
383 func (d *decodeState) value(v reflect.Value) error {
384 switch d.opcode {
385 default:
386 panic(phasePanicMsg)
387
388 case scanBeginArray:
389 if v.IsValid() {
390 if err := d.array(v); err != nil {
391 return err
392 }
393 } else {
394 d.skip()
395 }
396 d.scanNext()
397
398 case scanBeginObject:
399 if v.IsValid() {
400 if err := d.object(v); err != nil {
401 return err
402 }
403 } else {
404 d.skip()
405 }
406 d.scanNext()
407
408 case scanBeginLiteral:
409 // All bytes inside literal return scanContinue op code.
410 start := d.readIndex()
411 d.rescanLiteral()
412
413 if v.IsValid() {
414 if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil {
415 return err
416 }
417 }
418 }
419 return nil
420 }
421
422 type unquotedValue struct{}
423
424 // valueQuoted is like value but decodes a
425 // quoted string literal or literal null into an interface value.
426 // If it finds anything other than a quoted string literal or null,
427 // valueQuoted returns unquotedValue{}.
428 func (d *decodeState) valueQuoted() any {
429 switch d.opcode {
430 default:
431 panic(phasePanicMsg)
432
433 case scanBeginArray, scanBeginObject:
434 d.skip()
435 d.scanNext()
436
437 case scanBeginLiteral:
438 v := d.literalInterface()
439 switch v.(type) {
440 case nil, string:
441 return v
442 }
443 }
444 return unquotedValue{}
445 }
446
447 // indirect walks down v allocating pointers as needed,
448 // until it gets to a non-pointer.
449 // If it encounters an Unmarshaler, indirect stops and returns that.
450 // If decodingNull is true, indirect stops at the first settable pointer so it
451 // can be set to nil.
452 func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
453 // Issue #24153 indicates that it is generally not a guaranteed property
454 // that you may round-trip a reflect.Value by calling Value.Addr().Elem()
455 // and expect the value to still be settable for values derived from
456 // unexported embedded struct fields.
457 //
458 // The logic below effectively does this when it first addresses the value
459 // (to satisfy possible pointer methods) and continues to dereference
460 // subsequent pointers as necessary.
461 //
462 // After the first round-trip, we set v back to the original value to
463 // preserve the original RW flags contained in reflect.Value.
464 v0 := v
465 haveAddr := false
466
467 // If v is a named type and is addressable,
468 // start with its address, so that if the type has pointer methods,
469 // we find them.
470 if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() {
471 haveAddr = true
472 v = v.Addr()
473 }
474 for {
475 // Load value from interface, but only if the result will be
476 // usefully addressable.
477 if v.Kind() == reflect.Interface && !v.IsNil() {
478 e := v.Elem()
479 if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) {
480 haveAddr = false
481 v = e
482 continue
483 }
484 }
485
486 if v.Kind() != reflect.Pointer {
487 break
488 }
489
490 if decodingNull && v.CanSet() {
491 break
492 }
493
494 // Prevent infinite loop if v is an interface pointing to its own address:
495 // var v interface{}
496 // v = &v
497 if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
498 v = v.Elem()
499 break
500 }
501 if v.IsNil() {
502 v.Set(reflect.New(v.Type().Elem()))
503 }
504 if v.Type().NumMethod() > 0 && v.CanInterface() {
505 if u, ok := v.Interface().(Unmarshaler); ok {
506 return u, nil, reflect.Value{}
507 }
508 if !decodingNull {
509 if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
510 return nil, u, reflect.Value{}
511 }
512 }
513 }
514
515 if haveAddr {
516 v = v0 // restore original value after round-trip Value.Addr().Elem()
517 haveAddr = false
518 } else {
519 v = v.Elem()
520 }
521 }
522 return nil, nil, v
523 }
524
525 // array consumes an array from d.data[d.off-1:], decoding into v.
526 // The first byte of the array ('[') has been read already.
527 func (d *decodeState) array(v reflect.Value) error {
528 // Check for unmarshaler.
529 u, ut, pv := indirect(v, false)
530 if u != nil {
531 start := d.readIndex()
532 d.skip()
533 return u.UnmarshalJSON(d.data[start:d.off])
534 }
535 if ut != nil {
536 d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
537 d.skip()
538 return nil
539 }
540 v = pv
541
542 // Check type of target.
543 switch v.Kind() {
544 case reflect.Interface:
545 if v.NumMethod() == 0 {
546 // Decoding into nil interface? Switch to non-reflect code.
547 ai := d.arrayInterface()
548 v.Set(reflect.ValueOf(ai))
549 return nil
550 }
551 // Otherwise it's invalid.
552 fallthrough
553 default:
554 d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
555 d.skip()
556 return nil
557 case reflect.Array, reflect.Slice:
558 break
559 }
560
561 origStrictFieldStackLen := len(d.strictFieldStack)
562 defer func() {
563 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
564 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
565 }()
566
567 i := 0
568 for {
569 // Look ahead for ] - can only happen on first iteration.
570 d.scanWhile(scanSkipSpace)
571 if d.opcode == scanEndArray {
572 break
573 }
574
575 // Expand slice length, growing the slice if necessary.
576 if v.Kind() == reflect.Slice {
577 if i >= v.Cap() {
578 v.Grow(1)
579 }
580 if i >= v.Len() {
581 v.SetLen(i + 1)
582 }
583 }
584
585 d.appendStrictFieldStackIndex(i)
586 if i < v.Len() {
587 // Decode into element.
588 if err := d.value(v.Index(i)); err != nil {
589 return err
590 }
591 } else {
592 // Ran out of fixed array: skip.
593 if err := d.value(reflect.Value{}); err != nil {
594 return err
595 }
596 }
597 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
598 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
599 i++
600
601 // Next token must be , or ].
602 if d.opcode == scanSkipSpace {
603 d.scanWhile(scanSkipSpace)
604 }
605 if d.opcode == scanEndArray {
606 break
607 }
608 if d.opcode != scanArrayValue {
609 panic(phasePanicMsg)
610 }
611 }
612
613 if i < v.Len() {
614 if v.Kind() == reflect.Array {
615 for ; i < v.Len(); i++ {
616 v.Index(i).SetZero() // zero remainder of array
617 }
618 } else {
619 v.SetLen(i) // truncate the slice
620 }
621 }
622 if i == 0 && v.Kind() == reflect.Slice {
623 v.Set(reflect.MakeSlice(v.Type(), 0, 0))
624 }
625 return nil
626 }
627
628 var nullLiteral = []byte("null")
629 var textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
630
631 // object consumes an object from d.data[d.off-1:], decoding into v.
632 // The first byte ('{') of the object has been read already.
633 func (d *decodeState) object(v reflect.Value) error {
634 // Check for unmarshaler.
635 u, ut, pv := indirect(v, false)
636 if u != nil {
637 start := d.readIndex()
638 d.skip()
639 return u.UnmarshalJSON(d.data[start:d.off])
640 }
641 if ut != nil {
642 d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
643 d.skip()
644 return nil
645 }
646 v = pv
647 t := v.Type()
648
649 // Decoding into nil interface? Switch to non-reflect code.
650 if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
651 oi := d.objectInterface()
652 v.Set(reflect.ValueOf(oi))
653 return nil
654 }
655
656 var fields structFields
657 var checkDuplicateField func(fieldNameIndex int, fieldName string)
658
659 // Check type of target:
660 // struct or
661 // map[T1]T2 where T1 is string, an integer type,
662 // or an encoding.TextUnmarshaler
663 switch v.Kind() {
664 case reflect.Map:
665 // Map key must either have string kind, have an integer kind,
666 // or be an encoding.TextUnmarshaler.
667 switch t.Key().Kind() {
668 case reflect.String,
669 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
670 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
671 default:
672 if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) {
673 d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
674 d.skip()
675 return nil
676 }
677 }
678 if v.IsNil() {
679 v.Set(reflect.MakeMap(t))
680 }
681
682 if d.disallowDuplicateFields {
683 var seenKeys map[string]struct{}
684 checkDuplicateField = func(fieldNameIndex int, fieldName string) {
685 if seenKeys == nil {
686 seenKeys = map[string]struct{}{}
687 }
688 if _, seen := seenKeys[fieldName]; seen {
689 d.saveStrictError(d.newFieldError(duplicateStrictErrType, fieldName))
690 } else {
691 seenKeys[fieldName] = struct{}{}
692 }
693 }
694 }
695
696 case reflect.Struct:
697 fields = cachedTypeFields(t)
698
699 if d.disallowDuplicateFields {
700 if len(fields.list) <= 64 {
701 // bitset by field index for structs with <= 64 fields
702 var seenKeys uint64
703 checkDuplicateField = func(fieldNameIndex int, fieldName string) {
704 if seenKeys&(1<<fieldNameIndex) != 0 {
705 d.saveStrictError(d.newFieldError(duplicateStrictErrType, fieldName))
706 } else {
707 seenKeys = seenKeys | (1 << fieldNameIndex)
708 }
709 }
710 } else {
711 // list of seen field indices for structs with greater than 64 fields
712 var seenIndexes []bool
713 checkDuplicateField = func(fieldNameIndex int, fieldName string) {
714 if seenIndexes == nil {
715 seenIndexes = make([]bool, len(fields.list))
716 }
717 if seenIndexes[fieldNameIndex] {
718 d.saveStrictError(d.newFieldError(duplicateStrictErrType, fieldName))
719 } else {
720 seenIndexes[fieldNameIndex] = true
721 }
722 }
723 }
724 }
725
726 // ok
727 default:
728 d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
729 d.skip()
730 return nil
731 }
732
733 var mapElem reflect.Value
734 var origErrorContext errorContext
735 if d.errorContext != nil {
736 origErrorContext = *d.errorContext
737 }
738 origStrictFieldStackLen := len(d.strictFieldStack)
739
740 for {
741 // Read opening " of string key or closing }.
742 d.scanWhile(scanSkipSpace)
743 if d.opcode == scanEndObject {
744 // closing } - can only happen on first iteration.
745 break
746 }
747 if d.opcode != scanBeginLiteral {
748 panic(phasePanicMsg)
749 }
750
751 // Read key.
752 start := d.readIndex()
753 d.rescanLiteral()
754 item := d.data[start:d.readIndex()]
755 key, ok := unquoteBytes(item)
756 if !ok {
757 panic(phasePanicMsg)
758 }
759
760 // Figure out field corresponding to key.
761 var subv reflect.Value
762 destring := false // whether the value is wrapped in a string to be decoded first
763
764 if v.Kind() == reflect.Map {
765 elemType := t.Elem()
766 if !mapElem.IsValid() {
767 mapElem = reflect.New(elemType).Elem()
768 } else {
769 mapElem.SetZero()
770 }
771 subv = mapElem
772 if checkDuplicateField != nil {
773 checkDuplicateField(0, string(key))
774 }
775 d.appendStrictFieldStackKey(string(key))
776 } else {
777 f := fields.byExactName[string(key)]
778 if f == nil && !d.caseSensitive {
779 f = fields.byFoldedName[string(foldName(key))]
780 }
781 if f != nil {
782 if checkDuplicateField != nil {
783 checkDuplicateField(f.listIndex, f.name)
784 }
785 subv = v
786 destring = f.quoted
787 for _, i := range f.index {
788 if subv.Kind() == reflect.Pointer {
789 if subv.IsNil() {
790 // If a struct embeds a pointer to an unexported type,
791 // it is not possible to set a newly allocated value
792 // since the field is unexported.
793 //
794 // See https://golang.org/issue/21357
795 if !subv.CanSet() {
796 d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem()))
797 // Invalidate subv to ensure d.value(subv) skips over
798 // the JSON value without assigning it to subv.
799 subv = reflect.Value{}
800 destring = false
801 break
802 }
803 subv.Set(reflect.New(subv.Type().Elem()))
804 }
805 subv = subv.Elem()
806 }
807 subv = subv.Field(i)
808 }
809 if d.errorContext == nil {
810 d.errorContext = new(errorContext)
811 }
812 d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name)
813 d.errorContext.Struct = t
814 d.appendStrictFieldStackKey(f.name)
815 } else if d.disallowUnknownFields {
816 d.saveStrictError(d.newFieldError(unknownStrictErrType, string(key)))
817 }
818 }
819
820 // Read : before value.
821 if d.opcode == scanSkipSpace {
822 d.scanWhile(scanSkipSpace)
823 }
824 if d.opcode != scanObjectKey {
825 panic(phasePanicMsg)
826 }
827 d.scanWhile(scanSkipSpace)
828
829 if destring {
830 switch qv := d.valueQuoted().(type) {
831 case nil:
832 if err := d.literalStore(nullLiteral, subv, false); err != nil {
833 return err
834 }
835 case string:
836 if err := d.literalStore([]byte(qv), subv, true); err != nil {
837 return err
838 }
839 default:
840 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
841 }
842 } else {
843 if err := d.value(subv); err != nil {
844 return err
845 }
846 }
847
848 // Write value back to map;
849 // if using struct, subv points into struct already.
850 if v.Kind() == reflect.Map {
851 kt := t.Key()
852 var kv reflect.Value
853 if reflect.PointerTo(kt).Implements(textUnmarshalerType) {
854 kv = reflect.New(kt)
855 if err := d.literalStore(item, kv, true); err != nil {
856 return err
857 }
858 kv = kv.Elem()
859 } else {
860 switch kt.Kind() {
861 case reflect.String:
862 kv = reflect.New(kt).Elem()
863 kv.SetString(string(key))
864 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
865 s := string(key)
866 n, err := strconv.ParseInt(s, 10, 64)
867 if err != nil || kt.OverflowInt(n) {
868 d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
869 break
870 }
871 kv = reflect.New(kt).Elem()
872 kv.SetInt(n)
873 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
874 s := string(key)
875 n, err := strconv.ParseUint(s, 10, 64)
876 if err != nil || kt.OverflowUint(n) {
877 d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
878 break
879 }
880 kv = reflect.New(kt).Elem()
881 kv.SetUint(n)
882 default:
883 panic("json: Unexpected key type") // should never occur
884 }
885 }
886 if kv.IsValid() {
887 v.SetMapIndex(kv, subv)
888 }
889 }
890
891 // Next token must be , or }.
892 if d.opcode == scanSkipSpace {
893 d.scanWhile(scanSkipSpace)
894 }
895 if d.errorContext != nil {
896 // Reset errorContext to its original state.
897 // Keep the same underlying array for FieldStack, to reuse the
898 // space and avoid unnecessary allocs.
899 d.errorContext.FieldStack = d.errorContext.FieldStack[:len(origErrorContext.FieldStack)]
900 d.errorContext.Struct = origErrorContext.Struct
901 }
902 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
903 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
904 if d.opcode == scanEndObject {
905 break
906 }
907 if d.opcode != scanObjectValue {
908 panic(phasePanicMsg)
909 }
910 }
911 return nil
912 }
913
914 // convertNumber converts the number literal s to a float64 or a Number
915 // depending on the setting of d.useNumber.
916 func (d *decodeState) convertNumber(s string) (any, error) {
917 if d.useNumber {
918 return Number(s), nil
919 }
920
921 // if the string contains no floating point, return it as an int64 if it decodes successfully and does not overflow.
922 // otherwise, fall back to float64 behavior.
923 if d.preserveInts && !strings.Contains(s, ".") {
924 if i, err := strconv.ParseInt(s, 10, 64); err == nil {
925 return i, nil
926 }
927 }
928
929 f, err := strconv.ParseFloat(s, 64)
930 if err != nil {
931 return nil, &UnmarshalTypeError{Value: "number " + s, Type: reflect.TypeFor[float64](), Offset: int64(d.off)}
932 }
933 return f, nil
934 }
935
936 var numberType = reflect.TypeFor[Number]()
937
938 // literalStore decodes a literal stored in item into v.
939 //
940 // fromQuoted indicates whether this literal came from unwrapping a
941 // string from the ",string" struct tag option. this is used only to
942 // produce more helpful error messages.
943 func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error {
944 // Check for unmarshaler.
945 if len(item) == 0 {
946 // Empty string given.
947 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
948 return nil
949 }
950 isNull := item[0] == 'n' // null
951 u, ut, pv := indirect(v, isNull)
952 if u != nil {
953 return u.UnmarshalJSON(item)
954 }
955 if ut != nil {
956 if item[0] != '"' {
957 if fromQuoted {
958 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
959 return nil
960 }
961 val := "number"
962 switch item[0] {
963 case 'n':
964 val = "null"
965 case 't', 'f':
966 val = "bool"
967 }
968 d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())})
969 return nil
970 }
971 s, ok := unquoteBytes(item)
972 if !ok {
973 if fromQuoted {
974 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
975 }
976 panic(phasePanicMsg)
977 }
978 return ut.UnmarshalText(s)
979 }
980
981 v = pv
982
983 switch c := item[0]; c {
984 case 'n': // null
985 // The main parser checks that only true and false can reach here,
986 // but if this was a quoted string input, it could be anything.
987 if fromQuoted && string(item) != "null" {
988 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
989 break
990 }
991 switch v.Kind() {
992 case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
993 v.SetZero()
994 // otherwise, ignore null for primitives/string
995 }
996 case 't', 'f': // true, false
997 value := item[0] == 't'
998 // The main parser checks that only true and false can reach here,
999 // but if this was a quoted string input, it could be anything.
1000 if fromQuoted && string(item) != "true" && string(item) != "false" {
1001 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1002 break
1003 }
1004 switch v.Kind() {
1005 default:
1006 if fromQuoted {
1007 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1008 } else {
1009 d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
1010 }
1011 case reflect.Bool:
1012 v.SetBool(value)
1013 case reflect.Interface:
1014 if v.NumMethod() == 0 {
1015 v.Set(reflect.ValueOf(value))
1016 } else {
1017 d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
1018 }
1019 }
1020
1021 case '"': // string
1022 s, ok := unquoteBytes(item)
1023 if !ok {
1024 if fromQuoted {
1025 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
1026 }
1027 panic(phasePanicMsg)
1028 }
1029 switch v.Kind() {
1030 default:
1031 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
1032 case reflect.Slice:
1033 if v.Type().Elem().Kind() != reflect.Uint8 {
1034 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
1035 break
1036 }
1037 b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
1038 n, err := base64.StdEncoding.Decode(b, s)
1039 if err != nil {
1040 d.saveError(err)
1041 break
1042 }
1043 v.SetBytes(b[:n])
1044 case reflect.String:
1045 t := string(s)
1046 if v.Type() == numberType && !isValidNumber(t) {
1047 return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)
1048 }
1049 v.SetString(t)
1050 case reflect.Interface:
1051 if v.NumMethod() == 0 {
1052 v.Set(reflect.ValueOf(string(s)))
1053 } else {
1054 d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
1055 }
1056 }
1057
1058 default: // number
1059 if c != '-' && (c < '0' || c > '9') {
1060 if fromQuoted {
1061 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
1062 }
1063 panic(phasePanicMsg)
1064 }
1065 switch v.Kind() {
1066 default:
1067 if v.Kind() == reflect.String && v.Type() == numberType {
1068 // s must be a valid number, because it's
1069 // already been tokenized.
1070 v.SetString(string(item))
1071 break
1072 }
1073 if fromQuoted {
1074 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
1075 }
1076 d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
1077 case reflect.Interface:
1078 n, err := d.convertNumber(string(item))
1079 if err != nil {
1080 d.saveError(err)
1081 break
1082 }
1083 if v.NumMethod() != 0 {
1084 d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
1085 break
1086 }
1087 v.Set(reflect.ValueOf(n))
1088
1089 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1090 n, err := strconv.ParseInt(string(item), 10, 64)
1091 if err != nil || v.OverflowInt(n) {
1092 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1093 break
1094 }
1095 v.SetInt(n)
1096
1097 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1098 n, err := strconv.ParseUint(string(item), 10, 64)
1099 if err != nil || v.OverflowUint(n) {
1100 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1101 break
1102 }
1103 v.SetUint(n)
1104
1105 case reflect.Float32, reflect.Float64:
1106 n, err := strconv.ParseFloat(string(item), v.Type().Bits())
1107 if err != nil || v.OverflowFloat(n) {
1108 d.saveError(&UnmarshalTypeError{Value: "number " + string(item), Type: v.Type(), Offset: int64(d.readIndex())})
1109 break
1110 }
1111 v.SetFloat(n)
1112 }
1113 }
1114 return nil
1115 }
1116
1117 // The xxxInterface routines build up a value to be stored
1118 // in an empty interface. They are not strictly necessary,
1119 // but they avoid the weight of reflection in this common case.
1120
1121 // valueInterface is like value but returns interface{}
1122 func (d *decodeState) valueInterface() (val any) {
1123 switch d.opcode {
1124 default:
1125 panic(phasePanicMsg)
1126 case scanBeginArray:
1127 val = d.arrayInterface()
1128 d.scanNext()
1129 case scanBeginObject:
1130 val = d.objectInterface()
1131 d.scanNext()
1132 case scanBeginLiteral:
1133 val = d.literalInterface()
1134 }
1135 return
1136 }
1137
1138 // arrayInterface is like array but returns []interface{}.
1139 func (d *decodeState) arrayInterface() []any {
1140 origStrictFieldStackLen := len(d.strictFieldStack)
1141 defer func() {
1142 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
1143 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
1144 }()
1145
1146 var v = make([]any, 0)
1147 for {
1148 // Look ahead for ] - can only happen on first iteration.
1149 d.scanWhile(scanSkipSpace)
1150 if d.opcode == scanEndArray {
1151 break
1152 }
1153
1154 d.appendStrictFieldStackIndex(len(v))
1155 v = append(v, d.valueInterface())
1156 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
1157 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
1158
1159 // Next token must be , or ].
1160 if d.opcode == scanSkipSpace {
1161 d.scanWhile(scanSkipSpace)
1162 }
1163 if d.opcode == scanEndArray {
1164 break
1165 }
1166 if d.opcode != scanArrayValue {
1167 panic(phasePanicMsg)
1168 }
1169 }
1170 return v
1171 }
1172
1173 // objectInterface is like object but returns map[string]interface{}.
1174 func (d *decodeState) objectInterface() map[string]any {
1175 origStrictFieldStackLen := len(d.strictFieldStack)
1176 defer func() {
1177 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
1178 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
1179 }()
1180
1181 m := make(map[string]any)
1182 for {
1183 // Read opening " of string key or closing }.
1184 d.scanWhile(scanSkipSpace)
1185 if d.opcode == scanEndObject {
1186 // closing } - can only happen on first iteration.
1187 break
1188 }
1189 if d.opcode != scanBeginLiteral {
1190 panic(phasePanicMsg)
1191 }
1192
1193 // Read string key.
1194 start := d.readIndex()
1195 d.rescanLiteral()
1196 item := d.data[start:d.readIndex()]
1197 key, ok := unquote(item)
1198 if !ok {
1199 panic(phasePanicMsg)
1200 }
1201
1202 // Read : before value.
1203 if d.opcode == scanSkipSpace {
1204 d.scanWhile(scanSkipSpace)
1205 }
1206 if d.opcode != scanObjectKey {
1207 panic(phasePanicMsg)
1208 }
1209 d.scanWhile(scanSkipSpace)
1210
1211 if d.disallowDuplicateFields {
1212 if _, exists := m[key]; exists {
1213 d.saveStrictError(d.newFieldError(duplicateStrictErrType, key))
1214 }
1215 }
1216
1217 // Read value.
1218 d.appendStrictFieldStackKey(key)
1219 m[key] = d.valueInterface()
1220 // Reset to original length and reuse the allocated space for the strict FieldStack slice.
1221 d.strictFieldStack = d.strictFieldStack[:origStrictFieldStackLen]
1222
1223 // Next token must be , or }.
1224 if d.opcode == scanSkipSpace {
1225 d.scanWhile(scanSkipSpace)
1226 }
1227 if d.opcode == scanEndObject {
1228 break
1229 }
1230 if d.opcode != scanObjectValue {
1231 panic(phasePanicMsg)
1232 }
1233 }
1234 return m
1235 }
1236
1237 // literalInterface consumes and returns a literal from d.data[d.off-1:] and
1238 // it reads the following byte ahead. The first byte of the literal has been
1239 // read already (that's how the caller knows it's a literal).
1240 func (d *decodeState) literalInterface() any {
1241 // All bytes inside literal return scanContinue op code.
1242 start := d.readIndex()
1243 d.rescanLiteral()
1244
1245 item := d.data[start:d.readIndex()]
1246
1247 switch c := item[0]; c {
1248 case 'n': // null
1249 return nil
1250
1251 case 't', 'f': // true, false
1252 return c == 't'
1253
1254 case '"': // string
1255 s, ok := unquote(item)
1256 if !ok {
1257 panic(phasePanicMsg)
1258 }
1259 return s
1260
1261 default: // number
1262 if c != '-' && (c < '0' || c > '9') {
1263 panic(phasePanicMsg)
1264 }
1265 n, err := d.convertNumber(string(item))
1266 if err != nil {
1267 d.saveError(err)
1268 }
1269 return n
1270 }
1271 }
1272
1273 // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
1274 // or it returns -1.
1275 func getu4(s []byte) rune {
1276 if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
1277 return -1
1278 }
1279 var r rune
1280 for _, c := range s[2:6] {
1281 switch {
1282 case '0' <= c && c <= '9':
1283 c = c - '0'
1284 case 'a' <= c && c <= 'f':
1285 c = c - 'a' + 10
1286 case 'A' <= c && c <= 'F':
1287 c = c - 'A' + 10
1288 default:
1289 return -1
1290 }
1291 r = r*16 + rune(c)
1292 }
1293 return r
1294 }
1295
1296 // unquote converts a quoted JSON string literal s into an actual string t.
1297 // The rules are different than for Go, so cannot use strconv.Unquote.
1298 func unquote(s []byte) (t string, ok bool) {
1299 s, ok = unquoteBytes(s)
1300 t = string(s)
1301 return
1302 }
1303
1304 func unquoteBytes(s []byte) (t []byte, ok bool) {
1305 if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
1306 return
1307 }
1308 s = s[1 : len(s)-1]
1309
1310 // Check for unusual characters. If there are none,
1311 // then no unquoting is needed, so return a slice of the
1312 // original bytes.
1313 r := 0
1314 for r < len(s) {
1315 c := s[r]
1316 if c == '\\' || c == '"' || c < ' ' {
1317 break
1318 }
1319 if c < utf8.RuneSelf {
1320 r++
1321 continue
1322 }
1323 rr, size := utf8.DecodeRune(s[r:])
1324 if rr == utf8.RuneError && size == 1 {
1325 break
1326 }
1327 r += size
1328 }
1329 if r == len(s) {
1330 return s, true
1331 }
1332
1333 b := make([]byte, len(s)+2*utf8.UTFMax)
1334 w := copy(b, s[0:r])
1335 for r < len(s) {
1336 // Out of room? Can only happen if s is full of
1337 // malformed UTF-8 and we're replacing each
1338 // byte with RuneError.
1339 if w >= len(b)-2*utf8.UTFMax {
1340 nb := make([]byte, (len(b)+utf8.UTFMax)*2)
1341 copy(nb, b[0:w])
1342 b = nb
1343 }
1344 switch c := s[r]; {
1345 case c == '\\':
1346 r++
1347 if r >= len(s) {
1348 return
1349 }
1350 switch s[r] {
1351 default:
1352 return
1353 case '"', '\\', '/', '\'':
1354 b[w] = s[r]
1355 r++
1356 w++
1357 case 'b':
1358 b[w] = '\b'
1359 r++
1360 w++
1361 case 'f':
1362 b[w] = '\f'
1363 r++
1364 w++
1365 case 'n':
1366 b[w] = '\n'
1367 r++
1368 w++
1369 case 'r':
1370 b[w] = '\r'
1371 r++
1372 w++
1373 case 't':
1374 b[w] = '\t'
1375 r++
1376 w++
1377 case 'u':
1378 r--
1379 rr := getu4(s[r:])
1380 if rr < 0 {
1381 return
1382 }
1383 r += 6
1384 if utf16.IsSurrogate(rr) {
1385 rr1 := getu4(s[r:])
1386 if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
1387 // A valid pair; consume.
1388 r += 6
1389 w += utf8.EncodeRune(b[w:], dec)
1390 break
1391 }
1392 // Invalid surrogate; fall back to replacement rune.
1393 rr = unicode.ReplacementChar
1394 }
1395 w += utf8.EncodeRune(b[w:], rr)
1396 }
1397
1398 // Quote, control characters are invalid.
1399 case c == '"', c < ' ':
1400 return
1401
1402 // ASCII
1403 case c < utf8.RuneSelf:
1404 b[w] = c
1405 r++
1406 w++
1407
1408 // Coerce to well-formed UTF-8.
1409 default:
1410 rr, size := utf8.DecodeRune(s[r:])
1411 r += size
1412 w += utf8.EncodeRune(b[w:], rr)
1413 }
1414 }
1415 return b[0:w], true
1416 }