OSDN Git Service

31b15a400dfc3623bd363615853b68dcd928e38d
[pf3gnuchains/gcc-fork.git] / libgo / go / json / decode.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Represents JSON data structure using native Go types: booleans, floats,
6 // strings, arrays, and maps.
7
8 package json
9
10 import (
11         "encoding/base64"
12         "os"
13         "reflect"
14         "runtime"
15         "strconv"
16         "strings"
17         "unicode"
18         "utf16"
19         "utf8"
20 )
21
22 // Unmarshal parses the JSON-encoded data and stores the result
23 // in the value pointed to by v.
24 //
25 // Unmarshal uses the inverse of the encodings that
26 // Marshal uses, allocating maps, slices, and pointers as necessary,
27 // with the following additional rules:
28 //
29 // To unmarshal JSON into a pointer, Unmarshal first handles the case of
30 // the JSON being the JSON literal null.  In that case, Unmarshal sets
31 // the pointer to nil.  Otherwise, Unmarshal unmarshals the JSON into
32 // the value pointed at by the pointer.  If the pointer is nil, Unmarshal
33 // allocates a new value for it to point to.
34 //
35 // To unmarshal JSON into an interface value, Unmarshal unmarshals
36 // the JSON into the concrete value contained in the interface value.
37 // If the interface value is nil, that is, has no concrete value stored in it,
38 // Unmarshal stores one of these in the interface value:
39 //
40 //      bool, for JSON booleans
41 //      float64, for JSON numbers
42 //      string, for JSON strings
43 //      []interface{}, for JSON arrays
44 //      map[string]interface{}, for JSON objects
45 //      nil for JSON null
46 //
47 // If a JSON value is not appropriate for a given target type,
48 // or if a JSON number overflows the target type, Unmarshal
49 // skips that field and completes the unmarshalling as best it can.
50 // If no more serious errors are encountered, Unmarshal returns
51 // an UnmarshalTypeError describing the earliest such error.
52 //
53 func Unmarshal(data []byte, v interface{}) os.Error {
54         d := new(decodeState).init(data)
55
56         // Quick check for well-formedness.
57         // Avoids filling out half a data structure
58         // before discovering a JSON syntax error.
59         err := checkValid(data, &d.scan)
60         if err != nil {
61                 return err
62         }
63
64         return d.unmarshal(v)
65 }
66
67 // Unmarshaler is the interface implemented by objects
68 // that can unmarshal a JSON description of themselves.
69 // The input can be assumed to be a valid JSON object
70 // encoding.  UnmarshalJSON must copy the JSON data
71 // if it wishes to retain the data after returning.
72 type Unmarshaler interface {
73         UnmarshalJSON([]byte) os.Error
74 }
75
76 // An UnmarshalTypeError describes a JSON value that was
77 // not appropriate for a value of a specific Go type.
78 type UnmarshalTypeError struct {
79         Value string       // description of JSON value - "bool", "array", "number -5"
80         Type  reflect.Type // type of Go value it could not be assigned to
81 }
82
83 func (e *UnmarshalTypeError) String() string {
84         return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
85 }
86
87 // An UnmarshalFieldError describes a JSON object key that
88 // led to an unexported (and therefore unwritable) struct field.
89 type UnmarshalFieldError struct {
90         Key   string
91         Type  reflect.Type
92         Field reflect.StructField
93 }
94
95 func (e *UnmarshalFieldError) String() string {
96         return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
97 }
98
99 // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
100 // (The argument to Unmarshal must be a non-nil pointer.)
101 type InvalidUnmarshalError struct {
102         Type reflect.Type
103 }
104
105 func (e *InvalidUnmarshalError) String() string {
106         if e.Type == nil {
107                 return "json: Unmarshal(nil)"
108         }
109
110         if e.Type.Kind() != reflect.Ptr {
111                 return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
112         }
113         return "json: Unmarshal(nil " + e.Type.String() + ")"
114 }
115
116 func (d *decodeState) unmarshal(v interface{}) (err os.Error) {
117         defer func() {
118                 if r := recover(); r != nil {
119                         if _, ok := r.(runtime.Error); ok {
120                                 panic(r)
121                         }
122                         err = r.(os.Error)
123                 }
124         }()
125
126         rv := reflect.ValueOf(v)
127         pv := rv
128         if pv.Kind() != reflect.Ptr || pv.IsNil() {
129                 return &InvalidUnmarshalError{reflect.TypeOf(v)}
130         }
131
132         d.scan.reset()
133         // We decode rv not pv.Elem because the Unmarshaler interface
134         // test must be applied at the top level of the value.
135         d.value(rv)
136         return d.savedError
137 }
138
139 // decodeState represents the state while decoding a JSON value.
140 type decodeState struct {
141         data       []byte
142         off        int // read offset in data
143         scan       scanner
144         nextscan   scanner // for calls to nextValue
145         savedError os.Error
146         tempstr    string // scratch space to avoid some allocations
147 }
148
149 // errPhase is used for errors that should not happen unless
150 // there is a bug in the JSON decoder or something is editing
151 // the data slice while the decoder executes.
152 var errPhase = os.NewError("JSON decoder out of sync - data changing underfoot?")
153
154 func (d *decodeState) init(data []byte) *decodeState {
155         d.data = data
156         d.off = 0
157         d.savedError = nil
158         return d
159 }
160
161 // error aborts the decoding by panicking with err.
162 func (d *decodeState) error(err os.Error) {
163         panic(err)
164 }
165
166 // saveError saves the first err it is called with,
167 // for reporting at the end of the unmarshal.
168 func (d *decodeState) saveError(err os.Error) {
169         if d.savedError == nil {
170                 d.savedError = err
171         }
172 }
173
174 // next cuts off and returns the next full JSON value in d.data[d.off:].
175 // The next value is known to be an object or array, not a literal.
176 func (d *decodeState) next() []byte {
177         c := d.data[d.off]
178         item, rest, err := nextValue(d.data[d.off:], &d.nextscan)
179         if err != nil {
180                 d.error(err)
181         }
182         d.off = len(d.data) - len(rest)
183
184         // Our scanner has seen the opening brace/bracket
185         // and thinks we're still in the middle of the object.
186         // invent a closing brace/bracket to get it out.
187         if c == '{' {
188                 d.scan.step(&d.scan, '}')
189         } else {
190                 d.scan.step(&d.scan, ']')
191         }
192
193         return item
194 }
195
196 // scanWhile processes bytes in d.data[d.off:] until it
197 // receives a scan code not equal to op.
198 // It updates d.off and returns the new scan code.
199 func (d *decodeState) scanWhile(op int) int {
200         var newOp int
201         for {
202                 if d.off >= len(d.data) {
203                         newOp = d.scan.eof()
204                         d.off = len(d.data) + 1 // mark processed EOF with len+1
205                 } else {
206                         c := int(d.data[d.off])
207                         d.off++
208                         newOp = d.scan.step(&d.scan, c)
209                 }
210                 if newOp != op {
211                         break
212                 }
213         }
214         return newOp
215 }
216
217 // value decodes a JSON value from d.data[d.off:] into the value.
218 // it updates d.off to point past the decoded value.
219 func (d *decodeState) value(v reflect.Value) {
220         if !v.IsValid() {
221                 _, rest, err := nextValue(d.data[d.off:], &d.nextscan)
222                 if err != nil {
223                         d.error(err)
224                 }
225                 d.off = len(d.data) - len(rest)
226
227                 // d.scan thinks we're still at the beginning of the item.
228                 // Feed in an empty string - the shortest, simplest value -
229                 // so that it knows we got to the end of the value.
230                 if d.scan.step == stateRedo {
231                         panic("redo")
232                 }
233                 d.scan.step(&d.scan, '"')
234                 d.scan.step(&d.scan, '"')
235                 return
236         }
237
238         switch op := d.scanWhile(scanSkipSpace); op {
239         default:
240                 d.error(errPhase)
241
242         case scanBeginArray:
243                 d.array(v)
244
245         case scanBeginObject:
246                 d.object(v)
247
248         case scanBeginLiteral:
249                 d.literal(v)
250         }
251 }
252
253 // indirect walks down v allocating pointers as needed,
254 // until it gets to a non-pointer.
255 // if it encounters an Unmarshaler, indirect stops and returns that.
256 // if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
257 func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, reflect.Value) {
258         // If v is a named type and is addressable,
259         // start with its address, so that if the type has pointer methods,
260         // we find them.
261         if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
262                 v = v.Addr()
263         }
264         for {
265                 var isUnmarshaler bool
266                 if v.Type().NumMethod() > 0 {
267                         // Remember that this is an unmarshaler,
268                         // but wait to return it until after allocating
269                         // the pointer (if necessary).
270                         _, isUnmarshaler = v.Interface().(Unmarshaler)
271                 }
272
273                 if iv := v; iv.Kind() == reflect.Interface && !iv.IsNil() {
274                         v = iv.Elem()
275                         continue
276                 }
277
278                 pv := v
279                 if pv.Kind() != reflect.Ptr {
280                         break
281                 }
282
283                 if pv.Elem().Kind() != reflect.Ptr && decodingNull && pv.CanSet() {
284                         return nil, pv
285                 }
286                 if pv.IsNil() {
287                         pv.Set(reflect.New(pv.Type().Elem()))
288                 }
289                 if isUnmarshaler {
290                         // Using v.Interface().(Unmarshaler)
291                         // here means that we have to use a pointer
292                         // as the struct field.  We cannot use a value inside
293                         // a pointer to a struct, because in that case
294                         // v.Interface() is the value (x.f) not the pointer (&x.f).
295                         // This is an unfortunate consequence of reflect.
296                         // An alternative would be to look up the
297                         // UnmarshalJSON method and return a FuncValue.
298                         return v.Interface().(Unmarshaler), reflect.Value{}
299                 }
300                 v = pv.Elem()
301         }
302         return nil, v
303 }
304
305 // array consumes an array from d.data[d.off-1:], decoding into the value v.
306 // the first byte of the array ('[') has been read already.
307 func (d *decodeState) array(v reflect.Value) {
308         // Check for unmarshaler.
309         unmarshaler, pv := d.indirect(v, false)
310         if unmarshaler != nil {
311                 d.off--
312                 err := unmarshaler.UnmarshalJSON(d.next())
313                 if err != nil {
314                         d.error(err)
315                 }
316                 return
317         }
318         v = pv
319
320         // Decoding into nil interface?  Switch to non-reflect code.
321         iv := v
322         ok := iv.Kind() == reflect.Interface
323         if ok {
324                 iv.Set(reflect.ValueOf(d.arrayInterface()))
325                 return
326         }
327
328         // Check type of target.
329         av := v
330         if av.Kind() != reflect.Array && av.Kind() != reflect.Slice {
331                 d.saveError(&UnmarshalTypeError{"array", v.Type()})
332                 d.off--
333                 d.next()
334                 return
335         }
336
337         sv := v
338
339         i := 0
340         for {
341                 // Look ahead for ] - can only happen on first iteration.
342                 op := d.scanWhile(scanSkipSpace)
343                 if op == scanEndArray {
344                         break
345                 }
346
347                 // Back up so d.value can have the byte we just read.
348                 d.off--
349                 d.scan.undo(op)
350
351                 // Get element of array, growing if necessary.
352                 if i >= av.Cap() && sv.IsValid() {
353                         newcap := sv.Cap() + sv.Cap()/2
354                         if newcap < 4 {
355                                 newcap = 4
356                         }
357                         newv := reflect.MakeSlice(sv.Type(), sv.Len(), newcap)
358                         reflect.Copy(newv, sv)
359                         sv.Set(newv)
360                 }
361                 if i >= av.Len() && sv.IsValid() {
362                         // Must be slice; gave up on array during i >= av.Cap().
363                         sv.SetLen(i + 1)
364                 }
365
366                 // Decode into element.
367                 if i < av.Len() {
368                         d.value(av.Index(i))
369                 } else {
370                         // Ran out of fixed array: skip.
371                         d.value(reflect.Value{})
372                 }
373                 i++
374
375                 // Next token must be , or ].
376                 op = d.scanWhile(scanSkipSpace)
377                 if op == scanEndArray {
378                         break
379                 }
380                 if op != scanArrayValue {
381                         d.error(errPhase)
382                 }
383         }
384         if i < av.Len() {
385                 if !sv.IsValid() {
386                         // Array.  Zero the rest.
387                         z := reflect.Zero(av.Type().Elem())
388                         for ; i < av.Len(); i++ {
389                                 av.Index(i).Set(z)
390                         }
391                 } else {
392                         sv.SetLen(i)
393                 }
394         }
395 }
396
397 // object consumes an object from d.data[d.off-1:], decoding into the value v.
398 // the first byte of the object ('{') has been read already.
399 func (d *decodeState) object(v reflect.Value) {
400         // Check for unmarshaler.
401         unmarshaler, pv := d.indirect(v, false)
402         if unmarshaler != nil {
403                 d.off--
404                 err := unmarshaler.UnmarshalJSON(d.next())
405                 if err != nil {
406                         d.error(err)
407                 }
408                 return
409         }
410         v = pv
411
412         // Decoding into nil interface?  Switch to non-reflect code.
413         iv := v
414         if iv.Kind() == reflect.Interface {
415                 iv.Set(reflect.ValueOf(d.objectInterface()))
416                 return
417         }
418
419         // Check type of target: struct or map[string]T
420         var (
421                 mv reflect.Value
422                 sv reflect.Value
423         )
424         switch v.Kind() {
425         case reflect.Map:
426                 // map must have string type
427                 t := v.Type()
428                 if t.Key() != reflect.TypeOf("") {
429                         d.saveError(&UnmarshalTypeError{"object", v.Type()})
430                         break
431                 }
432                 mv = v
433                 if mv.IsNil() {
434                         mv.Set(reflect.MakeMap(t))
435                 }
436         case reflect.Struct:
437                 sv = v
438         default:
439                 d.saveError(&UnmarshalTypeError{"object", v.Type()})
440         }
441
442         if !mv.IsValid() && !sv.IsValid() {
443                 d.off--
444                 d.next() // skip over { } in input
445                 return
446         }
447
448         var mapElem reflect.Value
449
450         for {
451                 // Read opening " of string key or closing }.
452                 op := d.scanWhile(scanSkipSpace)
453                 if op == scanEndObject {
454                         // closing } - can only happen on first iteration.
455                         break
456                 }
457                 if op != scanBeginLiteral {
458                         d.error(errPhase)
459                 }
460
461                 // Read string key.
462                 start := d.off - 1
463                 op = d.scanWhile(scanContinue)
464                 item := d.data[start : d.off-1]
465                 key, ok := unquote(item)
466                 if !ok {
467                         d.error(errPhase)
468                 }
469
470                 // Figure out field corresponding to key.
471                 var subv reflect.Value
472                 destring := false // whether the value is wrapped in a string to be decoded first
473
474                 if mv.IsValid() {
475                         elemType := mv.Type().Elem()
476                         if !mapElem.IsValid() {
477                                 mapElem = reflect.New(elemType).Elem()
478                         } else {
479                                 mapElem.Set(reflect.Zero(elemType))
480                         }
481                         subv = mapElem
482                 } else {
483                         var f reflect.StructField
484                         var ok bool
485                         st := sv.Type()
486                         for i := 0; i < sv.NumField(); i++ {
487                                 sf := st.Field(i)
488                                 tag := sf.Tag.Get("json")
489                                 if tag == "-" {
490                                         // Pretend this field doesn't exist.
491                                         continue
492                                 }
493                                 // First, tag match
494                                 tagName, _ := parseTag(tag)
495                                 if tagName == key {
496                                         f = sf
497                                         ok = true
498                                         break // no better match possible
499                                 }
500                                 // Second, exact field name match
501                                 if sf.Name == key {
502                                         f = sf
503                                         ok = true
504                                 }
505                                 // Third, case-insensitive field name match,
506                                 // but only if a better match hasn't already been seen
507                                 if !ok && strings.EqualFold(sf.Name, key) {
508                                         f = sf
509                                         ok = true
510                                 }
511                         }
512
513                         // Extract value; name must be exported.
514                         if ok {
515                                 if f.PkgPath != "" {
516                                         d.saveError(&UnmarshalFieldError{key, st, f})
517                                 } else {
518                                         subv = sv.FieldByIndex(f.Index)
519                                 }
520                                 _, opts := parseTag(f.Tag.Get("json"))
521                                 destring = opts.Contains("string")
522                         }
523                 }
524
525                 // Read : before value.
526                 if op == scanSkipSpace {
527                         op = d.scanWhile(scanSkipSpace)
528                 }
529                 if op != scanObjectKey {
530                         d.error(errPhase)
531                 }
532
533                 // Read value.
534                 if destring {
535                         d.value(reflect.ValueOf(&d.tempstr))
536                         d.literalStore([]byte(d.tempstr), subv)
537                 } else {
538                         d.value(subv)
539                 }
540                 // Write value back to map;
541                 // if using struct, subv points into struct already.
542                 if mv.IsValid() {
543                         mv.SetMapIndex(reflect.ValueOf(key), subv)
544                 }
545
546                 // Next token must be , or }.
547                 op = d.scanWhile(scanSkipSpace)
548                 if op == scanEndObject {
549                         break
550                 }
551                 if op != scanObjectValue {
552                         d.error(errPhase)
553                 }
554         }
555 }
556
557 // literal consumes a literal from d.data[d.off-1:], decoding into the value v.
558 // The first byte of the literal has been read already
559 // (that's how the caller knows it's a literal).
560 func (d *decodeState) literal(v reflect.Value) {
561         // All bytes inside literal return scanContinue op code.
562         start := d.off - 1
563         op := d.scanWhile(scanContinue)
564
565         // Scan read one byte too far; back up.
566         d.off--
567         d.scan.undo(op)
568
569         d.literalStore(d.data[start:d.off], v)
570 }
571
572 // literalStore decodes a literal stored in item into v.
573 func (d *decodeState) literalStore(item []byte, v reflect.Value) {
574         // Check for unmarshaler.
575         wantptr := item[0] == 'n' // null
576         unmarshaler, pv := d.indirect(v, wantptr)
577         if unmarshaler != nil {
578                 err := unmarshaler.UnmarshalJSON(item)
579                 if err != nil {
580                         d.error(err)
581                 }
582                 return
583         }
584         v = pv
585
586         switch c := item[0]; c {
587         case 'n': // null
588                 switch v.Kind() {
589                 default:
590                         d.saveError(&UnmarshalTypeError{"null", v.Type()})
591                 case reflect.Interface, reflect.Ptr, reflect.Map:
592                         v.Set(reflect.Zero(v.Type()))
593                 }
594
595         case 't', 'f': // true, false
596                 value := c == 't'
597                 switch v.Kind() {
598                 default:
599                         d.saveError(&UnmarshalTypeError{"bool", v.Type()})
600                 case reflect.Bool:
601                         v.SetBool(value)
602                 case reflect.Interface:
603                         v.Set(reflect.ValueOf(value))
604                 }
605
606         case '"': // string
607                 s, ok := unquoteBytes(item)
608                 if !ok {
609                         d.error(errPhase)
610                 }
611                 switch v.Kind() {
612                 default:
613                         d.saveError(&UnmarshalTypeError{"string", v.Type()})
614                 case reflect.Slice:
615                         if v.Type() != byteSliceType {
616                                 d.saveError(&UnmarshalTypeError{"string", v.Type()})
617                                 break
618                         }
619                         b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
620                         n, err := base64.StdEncoding.Decode(b, s)
621                         if err != nil {
622                                 d.saveError(err)
623                                 break
624                         }
625                         v.Set(reflect.ValueOf(b[0:n]))
626                 case reflect.String:
627                         v.SetString(string(s))
628                 case reflect.Interface:
629                         v.Set(reflect.ValueOf(string(s)))
630                 }
631
632         default: // number
633                 if c != '-' && (c < '0' || c > '9') {
634                         d.error(errPhase)
635                 }
636                 s := string(item)
637                 switch v.Kind() {
638                 default:
639                         d.error(&UnmarshalTypeError{"number", v.Type()})
640                 case reflect.Interface:
641                         n, err := strconv.Atof64(s)
642                         if err != nil {
643                                 d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
644                                 break
645                         }
646                         v.Set(reflect.ValueOf(n))
647
648                 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
649                         n, err := strconv.Atoi64(s)
650                         if err != nil || v.OverflowInt(n) {
651                                 d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
652                                 break
653                         }
654                         v.SetInt(n)
655
656                 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
657                         n, err := strconv.Atoui64(s)
658                         if err != nil || v.OverflowUint(n) {
659                                 d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
660                                 break
661                         }
662                         v.SetUint(n)
663
664                 case reflect.Float32, reflect.Float64:
665                         n, err := strconv.AtofN(s, v.Type().Bits())
666                         if err != nil || v.OverflowFloat(n) {
667                                 d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
668                                 break
669                         }
670                         v.SetFloat(n)
671                 }
672         }
673 }
674
675 // The xxxInterface routines build up a value to be stored
676 // in an empty interface.  They are not strictly necessary,
677 // but they avoid the weight of reflection in this common case.
678
679 // valueInterface is like value but returns interface{}
680 func (d *decodeState) valueInterface() interface{} {
681         switch d.scanWhile(scanSkipSpace) {
682         default:
683                 d.error(errPhase)
684         case scanBeginArray:
685                 return d.arrayInterface()
686         case scanBeginObject:
687                 return d.objectInterface()
688         case scanBeginLiteral:
689                 return d.literalInterface()
690         }
691         panic("unreachable")
692 }
693
694 // arrayInterface is like array but returns []interface{}.
695 func (d *decodeState) arrayInterface() []interface{} {
696         var v []interface{}
697         for {
698                 // Look ahead for ] - can only happen on first iteration.
699                 op := d.scanWhile(scanSkipSpace)
700                 if op == scanEndArray {
701                         break
702                 }
703
704                 // Back up so d.value can have the byte we just read.
705                 d.off--
706                 d.scan.undo(op)
707
708                 v = append(v, d.valueInterface())
709
710                 // Next token must be , or ].
711                 op = d.scanWhile(scanSkipSpace)
712                 if op == scanEndArray {
713                         break
714                 }
715                 if op != scanArrayValue {
716                         d.error(errPhase)
717                 }
718         }
719         return v
720 }
721
722 // objectInterface is like object but returns map[string]interface{}.
723 func (d *decodeState) objectInterface() map[string]interface{} {
724         m := make(map[string]interface{})
725         for {
726                 // Read opening " of string key or closing }.
727                 op := d.scanWhile(scanSkipSpace)
728                 if op == scanEndObject {
729                         // closing } - can only happen on first iteration.
730                         break
731                 }
732                 if op != scanBeginLiteral {
733                         d.error(errPhase)
734                 }
735
736                 // Read string key.
737                 start := d.off - 1
738                 op = d.scanWhile(scanContinue)
739                 item := d.data[start : d.off-1]
740                 key, ok := unquote(item)
741                 if !ok {
742                         d.error(errPhase)
743                 }
744
745                 // Read : before value.
746                 if op == scanSkipSpace {
747                         op = d.scanWhile(scanSkipSpace)
748                 }
749                 if op != scanObjectKey {
750                         d.error(errPhase)
751                 }
752
753                 // Read value.
754                 m[key] = d.valueInterface()
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         return m
766 }
767
768 // literalInterface is like literal but returns an interface value.
769 func (d *decodeState) literalInterface() interface{} {
770         // All bytes inside literal return scanContinue op code.
771         start := d.off - 1
772         op := d.scanWhile(scanContinue)
773
774         // Scan read one byte too far; back up.
775         d.off--
776         d.scan.undo(op)
777         item := d.data[start:d.off]
778
779         switch c := item[0]; c {
780         case 'n': // null
781                 return nil
782
783         case 't', 'f': // true, false
784                 return c == 't'
785
786         case '"': // string
787                 s, ok := unquote(item)
788                 if !ok {
789                         d.error(errPhase)
790                 }
791                 return s
792
793         default: // number
794                 if c != '-' && (c < '0' || c > '9') {
795                         d.error(errPhase)
796                 }
797                 n, err := strconv.Atof64(string(item))
798                 if err != nil {
799                         d.saveError(&UnmarshalTypeError{"number " + string(item), reflect.TypeOf(0.0)})
800                 }
801                 return n
802         }
803         panic("unreachable")
804 }
805
806 // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
807 // or it returns -1.
808 func getu4(s []byte) int {
809         if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
810                 return -1
811         }
812         rune, err := strconv.Btoui64(string(s[2:6]), 16)
813         if err != nil {
814                 return -1
815         }
816         return int(rune)
817 }
818
819 // unquote converts a quoted JSON string literal s into an actual string t.
820 // The rules are different than for Go, so cannot use strconv.Unquote.
821 func unquote(s []byte) (t string, ok bool) {
822         s, ok = unquoteBytes(s)
823         t = string(s)
824         return
825 }
826
827 func unquoteBytes(s []byte) (t []byte, ok bool) {
828         if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
829                 return
830         }
831         s = s[1 : len(s)-1]
832
833         // Check for unusual characters. If there are none,
834         // then no unquoting is needed, so return a slice of the
835         // original bytes.
836         r := 0
837         for r < len(s) {
838                 c := s[r]
839                 if c == '\\' || c == '"' || c < ' ' {
840                         break
841                 }
842                 if c < utf8.RuneSelf {
843                         r++
844                         continue
845                 }
846                 rune, size := utf8.DecodeRune(s[r:])
847                 if rune == utf8.RuneError && size == 1 {
848                         break
849                 }
850                 r += size
851         }
852         if r == len(s) {
853                 return s, true
854         }
855
856         b := make([]byte, len(s)+2*utf8.UTFMax)
857         w := copy(b, s[0:r])
858         for r < len(s) {
859                 // Out of room?  Can only happen if s is full of
860                 // malformed UTF-8 and we're replacing each
861                 // byte with RuneError.
862                 if w >= len(b)-2*utf8.UTFMax {
863                         nb := make([]byte, (len(b)+utf8.UTFMax)*2)
864                         copy(nb, b[0:w])
865                         b = nb
866                 }
867                 switch c := s[r]; {
868                 case c == '\\':
869                         r++
870                         if r >= len(s) {
871                                 return
872                         }
873                         switch s[r] {
874                         default:
875                                 return
876                         case '"', '\\', '/', '\'':
877                                 b[w] = s[r]
878                                 r++
879                                 w++
880                         case 'b':
881                                 b[w] = '\b'
882                                 r++
883                                 w++
884                         case 'f':
885                                 b[w] = '\f'
886                                 r++
887                                 w++
888                         case 'n':
889                                 b[w] = '\n'
890                                 r++
891                                 w++
892                         case 'r':
893                                 b[w] = '\r'
894                                 r++
895                                 w++
896                         case 't':
897                                 b[w] = '\t'
898                                 r++
899                                 w++
900                         case 'u':
901                                 r--
902                                 rune := getu4(s[r:])
903                                 if rune < 0 {
904                                         return
905                                 }
906                                 r += 6
907                                 if utf16.IsSurrogate(rune) {
908                                         rune1 := getu4(s[r:])
909                                         if dec := utf16.DecodeRune(rune, rune1); dec != unicode.ReplacementChar {
910                                                 // A valid pair; consume.
911                                                 r += 6
912                                                 w += utf8.EncodeRune(b[w:], dec)
913                                                 break
914                                         }
915                                         // Invalid surrogate; fall back to replacement rune.
916                                         rune = unicode.ReplacementChar
917                                 }
918                                 w += utf8.EncodeRune(b[w:], rune)
919                         }
920
921                 // Quote, control characters are invalid.
922                 case c == '"', c < ' ':
923                         return
924
925                 // ASCII
926                 case c < utf8.RuneSelf:
927                         b[w] = c
928                         r++
929                         w++
930
931                 // Coerce to well-formed UTF-8.
932                 default:
933                         rune, size := utf8.DecodeRune(s[r:])
934                         r += size
935                         w += utf8.EncodeRune(b[w:], rune)
936                 }
937         }
938         return b[0:w], true
939 }