decode.go 40 KB

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