decode.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Copyright 2018 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. package json
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "regexp"
  10. "strconv"
  11. "unicode/utf8"
  12. "github.com/golang/protobuf/v2/internal/errors"
  13. )
  14. // Decoder is a token-based JSON decoder.
  15. type Decoder struct {
  16. lastType Type
  17. // startStack is a stack containing StartObject and StartArray types. The
  18. // top of stack represents the object or the array the current value is
  19. // directly located in.
  20. startStack []Type
  21. // orig is used in reporting line and column.
  22. orig []byte
  23. // in contains the unconsumed input.
  24. in []byte
  25. }
  26. // NewDecoder returns a Decoder to read the given []byte.
  27. func NewDecoder(b []byte) *Decoder {
  28. return &Decoder{orig: b, in: b}
  29. }
  30. // ReadNext returns the next JSON value. It will return an error if there is no
  31. // valid JSON value. For String types containing invalid UTF8 characters, a
  32. // non-fatal error is returned and caller can call ReadNext for the next value.
  33. func (d *Decoder) ReadNext() (Value, error) {
  34. var nerr errors.NonFatal
  35. value, n, err := d.parseNext()
  36. if !nerr.Merge(err) {
  37. return Value{}, err
  38. }
  39. switch value.typ {
  40. case EOF:
  41. if len(d.startStack) != 0 ||
  42. d.lastType&Null|Bool|Number|String|EndObject|EndArray == 0 {
  43. return Value{}, io.ErrUnexpectedEOF
  44. }
  45. case Null:
  46. if !d.isValueNext() {
  47. return Value{}, d.newSyntaxError("unexpected value null")
  48. }
  49. case Bool, Number:
  50. if !d.isValueNext() {
  51. return Value{}, d.newSyntaxError("unexpected value %v", value)
  52. }
  53. case String:
  54. if d.isValueNext() {
  55. break
  56. }
  57. // Check if this is for an object name.
  58. if d.lastType&(StartObject|comma) == 0 {
  59. return Value{}, d.newSyntaxError("unexpected value %q", value)
  60. }
  61. d.in = d.in[n:]
  62. d.consume(0)
  63. if c := d.in[0]; c != ':' {
  64. return Value{}, d.newSyntaxError(`unexpected character %v, missing ":" after object name`, string(c))
  65. }
  66. n = 1
  67. value.typ = Name
  68. case StartObject, StartArray:
  69. if !d.isValueNext() {
  70. return Value{}, d.newSyntaxError("unexpected character %v", value)
  71. }
  72. d.startStack = append(d.startStack, value.typ)
  73. case EndObject:
  74. if len(d.startStack) == 0 ||
  75. d.lastType == comma ||
  76. d.startStack[len(d.startStack)-1] != StartObject {
  77. return Value{}, d.newSyntaxError("unexpected character }")
  78. }
  79. d.startStack = d.startStack[:len(d.startStack)-1]
  80. case EndArray:
  81. if len(d.startStack) == 0 ||
  82. d.lastType == comma ||
  83. d.startStack[len(d.startStack)-1] != StartArray {
  84. return Value{}, d.newSyntaxError("unexpected character ]")
  85. }
  86. d.startStack = d.startStack[:len(d.startStack)-1]
  87. case comma:
  88. if len(d.startStack) == 0 ||
  89. d.lastType&(Null|Bool|Number|String|EndObject|EndArray) == 0 {
  90. return Value{}, d.newSyntaxError("unexpected character ,")
  91. }
  92. }
  93. // Update lastType only after validating value to be in the right
  94. // sequence.
  95. d.lastType = value.typ
  96. d.in = d.in[n:]
  97. if d.lastType == comma {
  98. return d.ReadNext()
  99. }
  100. return value, nerr.E
  101. }
  102. var (
  103. literalRegexp = regexp.MustCompile(`^(null|true|false)`)
  104. // Any sequence that looks like a non-delimiter (for error reporting).
  105. errRegexp = regexp.MustCompile(`^([-+._a-zA-Z0-9]{1,32}|.)`)
  106. )
  107. // parseNext parses for the next JSON value. It returns a Value object for
  108. // different types, except for Name. It also returns the size that was parsed.
  109. // It does not handle whether the next value is in a valid sequence or not, it
  110. // only ensures that the value is a valid one.
  111. func (d *Decoder) parseNext() (value Value, n int, err error) {
  112. // Trim leading spaces.
  113. d.consume(0)
  114. in := d.in
  115. if len(in) == 0 {
  116. return d.newValue(EOF, nil, nil), 0, nil
  117. }
  118. switch in[0] {
  119. case 'n', 't', 'f':
  120. n := matchWithDelim(literalRegexp, in)
  121. if n == 0 {
  122. return Value{}, 0, d.newSyntaxError("invalid value %s", errRegexp.Find(in))
  123. }
  124. switch in[0] {
  125. case 'n':
  126. return d.newValue(Null, in[:n], nil), n, nil
  127. case 't':
  128. return d.newValue(Bool, in[:n], true), n, nil
  129. case 'f':
  130. return d.newValue(Bool, in[:n], false), n, nil
  131. }
  132. case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  133. num, n := parseNumber(in)
  134. if num == nil {
  135. return Value{}, 0, d.newSyntaxError("invalid number %s", errRegexp.Find(in))
  136. }
  137. return d.newValue(Number, in[:n], num), n, nil
  138. case '"':
  139. var nerr errors.NonFatal
  140. s, n, err := d.parseString(in)
  141. if !nerr.Merge(err) {
  142. return Value{}, 0, err
  143. }
  144. return d.newValue(String, in[:n], s), n, nerr.E
  145. case '{':
  146. return d.newValue(StartObject, in[:1], nil), 1, nil
  147. case '}':
  148. return d.newValue(EndObject, in[:1], nil), 1, nil
  149. case '[':
  150. return d.newValue(StartArray, in[:1], nil), 1, nil
  151. case ']':
  152. return d.newValue(EndArray, in[:1], nil), 1, nil
  153. case ',':
  154. return d.newValue(comma, in[:1], nil), 1, nil
  155. }
  156. return Value{}, 0, d.newSyntaxError("invalid value %s", errRegexp.Find(in))
  157. }
  158. // position returns line and column number of parsed bytes.
  159. func (d *Decoder) position() (int, int) {
  160. // Calculate line and column of consumed input.
  161. b := d.orig[:len(d.orig)-len(d.in)]
  162. line := bytes.Count(b, []byte("\n")) + 1
  163. if i := bytes.LastIndexByte(b, '\n'); i >= 0 {
  164. b = b[i+1:]
  165. }
  166. column := utf8.RuneCount(b) + 1 // ignore multi-rune characters
  167. return line, column
  168. }
  169. // newSyntaxError returns an error with line and column information useful for
  170. // syntax errors.
  171. func (d *Decoder) newSyntaxError(f string, x ...interface{}) error {
  172. e := errors.New(f, x...)
  173. line, column := d.position()
  174. return errors.New("syntax error (line %d:%d): %v", line, column, e)
  175. }
  176. // matchWithDelim matches r with the input b and verifies that the match
  177. // terminates with a delimiter of some form (e.g., r"[^-+_.a-zA-Z0-9]").
  178. // As a special case, EOF is considered a delimiter.
  179. func matchWithDelim(r *regexp.Regexp, b []byte) int {
  180. n := len(r.Find(b))
  181. if n < len(b) {
  182. // Check that the next character is a delimiter.
  183. if isNotDelim(b[n]) {
  184. return 0
  185. }
  186. }
  187. return n
  188. }
  189. // isNotDelim returns true if given byte is a not delimiter character.
  190. func isNotDelim(c byte) bool {
  191. return (c == '-' || c == '+' || c == '.' || c == '_' ||
  192. ('a' <= c && c <= 'z') ||
  193. ('A' <= c && c <= 'Z') ||
  194. ('0' <= c && c <= '9'))
  195. }
  196. // consume consumes n bytes of input and any subsequent whitespace.
  197. func (d *Decoder) consume(n int) {
  198. d.in = d.in[n:]
  199. for len(d.in) > 0 {
  200. switch d.in[0] {
  201. case ' ', '\n', '\r', '\t':
  202. d.in = d.in[1:]
  203. default:
  204. return
  205. }
  206. }
  207. }
  208. // isValueNext returns true if next type should be a JSON value: Null,
  209. // Number, String or Bool.
  210. func (d *Decoder) isValueNext() bool {
  211. if len(d.startStack) == 0 {
  212. return d.lastType == 0
  213. }
  214. start := d.startStack[len(d.startStack)-1]
  215. switch start {
  216. case StartObject:
  217. return d.lastType&Name != 0
  218. case StartArray:
  219. return d.lastType&(StartArray|comma) != 0
  220. }
  221. panic(fmt.Sprintf(
  222. "unreachable logic in Decoder.isValueNext, lastType: %v, startStack: %v",
  223. d.lastType, start))
  224. }
  225. // newValue constructs a Value.
  226. func (d *Decoder) newValue(typ Type, input []byte, value interface{}) Value {
  227. line, column := d.position()
  228. return Value{
  229. input: input,
  230. line: line,
  231. column: column,
  232. typ: typ,
  233. value: value,
  234. }
  235. }
  236. // Value contains a JSON type and value parsed from calling Decoder.ReadNext.
  237. type Value struct {
  238. input []byte
  239. line int
  240. column int
  241. typ Type
  242. // value will be set to the following Go type based on the type field:
  243. // Bool => bool
  244. // Number => *numberParts
  245. // String => string
  246. // Name => string
  247. // It will be nil if none of the above.
  248. value interface{}
  249. }
  250. func (v Value) newError(f string, x ...interface{}) error {
  251. e := errors.New(f, x...)
  252. return errors.New("error (line %d:%d): %v", v.line, v.column, e)
  253. }
  254. // Type returns the JSON type.
  255. func (v Value) Type() Type {
  256. return v.typ
  257. }
  258. // Position returns the line and column of the value.
  259. func (v Value) Position() (int, int) {
  260. return v.line, v.column
  261. }
  262. // Bool returns the bool value if token is Bool, else it will return an error.
  263. func (v Value) Bool() (bool, error) {
  264. if v.typ != Bool {
  265. return false, v.newError("%s is not a bool", v.input)
  266. }
  267. return v.value.(bool), nil
  268. }
  269. // String returns the string value for a JSON string token or the read value in
  270. // string if token is not a string.
  271. func (v Value) String() string {
  272. if v.typ != String {
  273. return string(v.input)
  274. }
  275. return v.value.(string)
  276. }
  277. // Name returns the object name if token is Name, else it will return an error.
  278. func (v Value) Name() (string, error) {
  279. if v.typ != Name {
  280. return "", v.newError("%s is not an object name", v.input)
  281. }
  282. return v.value.(string), nil
  283. }
  284. // Float returns the floating-point number if token is Number, else it will
  285. // return an error.
  286. //
  287. // The floating-point precision is specified by the bitSize parameter: 32 for
  288. // float32 or 64 for float64. If bitSize=32, the result still has type float64,
  289. // but it will be convertible to float32 without changing its value. It will
  290. // return an error if the number exceeds the floating point limits for given
  291. // bitSize.
  292. func (v Value) Float(bitSize int) (float64, error) {
  293. if v.typ != Number {
  294. return 0, v.newError("%s is not a number", v.input)
  295. }
  296. f, err := strconv.ParseFloat(string(v.input), bitSize)
  297. if err != nil {
  298. return 0, v.newError("%v", err)
  299. }
  300. return f, nil
  301. }
  302. // Int returns the signed integer number if token is Number, else it will
  303. // return an error.
  304. //
  305. // The given bitSize specifies the integer type that the result must fit into.
  306. // It returns an error if the number is not an integer value or if the result
  307. // exceeds the limits for given bitSize.
  308. func (v Value) Int(bitSize int) (int64, error) {
  309. s, err := v.getIntStr()
  310. if err != nil {
  311. return 0, err
  312. }
  313. n, err := strconv.ParseInt(s, 10, bitSize)
  314. if err != nil {
  315. return 0, v.newError("%v", err)
  316. }
  317. return n, nil
  318. }
  319. // Uint returns the signed integer number if token is Number, else it will
  320. // return an error.
  321. //
  322. // The given bitSize specifies the unsigned integer type that the result must
  323. // fit into. It returns an error if the number is not an unsigned integer value
  324. // or if the result exceeds the limits for given bitSize.
  325. func (v Value) Uint(bitSize int) (uint64, error) {
  326. s, err := v.getIntStr()
  327. if err != nil {
  328. return 0, err
  329. }
  330. n, err := strconv.ParseUint(s, 10, bitSize)
  331. if err != nil {
  332. return 0, v.newError("%v", err)
  333. }
  334. return n, nil
  335. }
  336. func (v Value) getIntStr() (string, error) {
  337. if v.typ != Number {
  338. return "", v.newError("%s is not a number", v.input)
  339. }
  340. pnum := v.value.(*numberParts)
  341. num, ok := normalizeToIntString(pnum)
  342. if !ok {
  343. return "", v.newError("cannot convert %s to integer", v.input)
  344. }
  345. return num, nil
  346. }