Debian Codegraph @

src/encoding/json/decode.go

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