Debian Codegraph @

decode.go

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