Debian Codegraph @

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