Debian Codegraph @

internal/decoder/stream_token_v2.go

raw
1 //go:build go1.27 && goexperiment.jsonv2
2
3 package decoder
4
5 import (
6 "bytes"
7 "encoding/json"
8 "io"
9 "strconv"
10 "unicode/utf8"
11 "unsafe"
12
13 "github.com/goccy/go-json/internal/errors"
14 )
15
16 // The tokens of a stream as encoding/json of Go 1.27 reads them, by encoding/json/jsontext: a token or a value is
17 // read after the comma or the colon which the grammar has before it, which is checked against the kind of the
18 // token, and a read which fails leaves the stream where it was. A value may be read where a key is waited for,
19 // as the key.
20
21 // streamPeek is what More peeked at: encoding/json of Go 1.27 reports by InputOffset the start of the next token
22 // after More, until a value or a token is read.
23 type streamPeek struct {
24 // peeked is whether More was called after the last value or token which was read.
25 peeked bool
26 // offset is the total offset of the next token which More peeked at, or of the end of the value or the token
27 // before it if the input has none.
28 offset int64
29 }
30
31 // reset forgets what More peeked at, after a value or a token is read.
32 func (p *streamPeek) reset() {
33 p.peeked = false
34 }
35
36 // countsScanned is whether the offset of a syntax error of a value of Decode is counted from the bytes which the
37 // reads of the values read: encoding/json of Go 1.27 reports the offset in the whole input.
38 const countsScanned = false
39
40 // invalidCharacter returns the syntax error of the character at the total offset, which the grammar doesn't
41 // have where it is: encoding/json of Go 1.27 reports the rune there. The bytes of the rune are read if the buffer
42 // ends in it, and the ones from at are kept for it.
43 func (s *Stream) invalidCharacter(at int64, where string) error {
44 cursor := s.TotalOffset()
45 s.cursor = min(cursor, at) - s.offset
46 for s.length-(at-s.offset) < utf8.UTFMax && !utf8.FullRune(s.buf[at-s.offset:s.length]) && s.read() {
47 }
48 s.cursor = cursor - s.offset
49 err := invalidCharacterError(s.buf[:s.length+1], at-s.offset, where)
50 return s.totalOffsetError(err)
51 }
52
53 // tokenEnded is after Token read the end of the input: every read returns io.EOF.
54 const tokenEnded = tokenFailed + 1
55
56 // needDelim returns the comma or the colon which the grammar has before a token of the kind which starts with c,
57 // or 0 for none.
58 func (s *Stream) needDelim(c byte) byte {
59 switch s.tokenState {
60 case tokenObjectColon:
61 return ':'
62 case tokenArrayComma, tokenObjectComma:
63 if c != '}' && c != ']' {
64 return ','
65 }
66 }
67 return 0
68 }
69
70 // readDelim reads, from start, the white spaces and the comma or the colon before the next token, which it checks
71 // against the token, and moves the state after it. It returns the byte which starts the token.
72 func (s *Stream) readDelim(start int64) (byte, error) {
73 if !s.peek() {
74 return 0, s.tokenEnd(start)
75 }
76 var delim byte
77 at := s.TotalOffset()
78 if c := s.buf[s.cursor]; c == ',' || c == ':' {
79 delim = c
80 s.cursor++
81 if !s.skipWhiteSpace() {
82 // the next token is not known: a string, which follows any comma or colon, is taken for it
83 if s.needDelim('"') != delim {
84 return 0, s.delimError('"', at)
85 }
86 return 0, s.tokenEnd(start)
87 }
88 }
89 c := s.buf[s.cursor]
90 if s.needDelim(c) != delim {
91 // the byte after the white spaces: the comma or the colon, or else the token
92 return 0, s.delimError(c, at)
93 }
94 switch {
95 case delim == ',' && s.tokenState == tokenArrayComma:
96 s.tokenState = tokenArrayValue
97 case delim == ',':
98 s.tokenState = tokenObjectKey
99 case delim == ':':
100 s.tokenState = tokenObjectValue
101 }
102 return c, nil
103 }
104
105 // delimError returns the error of the byte c at the total offset at, which is not the comma or the colon which the
106 // grammar has before a token which starts with next.
107 func (s *Stream) delimError(next byte, at int64) error {
108 where := "looking for beginning of value"
109 switch s.needDelim(next) {
110 case ':':
111 where = "after object key"
112 case ',':
113 if s.tokenState == tokenObjectComma {
114 where = "after object key:value pair"
115 } else {
116 where = "after array element"
117 }
118 }
119 return s.invalidCharacter(at, where)
120 }
121
122 // tokenEnd returns the error of the end of the input before a token: io.EOF if what is left is white spaces,
123 // commas and colons, which a value may follow, as encoding/json reports it.
124 func (s *Stream) tokenEnd(start int64) error {
125 if err := s.endError(); err != io.EOF {
126 return err
127 }
128 for i := start - s.offset; i < s.length; i++ {
129 switch s.buf[i] {
130 case ' ', '\t', '\n', '\r', ',', ':':
131 default:
132 return io.ErrUnexpectedEOF
133 }
134 }
135 return io.EOF
136 }
137
138 // restore moves the stream back to the total offset start, where a read which failed started, which InputOffset
139 // reports, and returns err.
140 func (s *Stream) restore(start int64, err error) error {
141 s.moveBack(start)
142 return err
143 }
144
145 // moveBack moves the stream back to the total offset start, where a read which failed started, which InputOffset
146 // reports.
147 func (s *Stream) moveBack(start int64) {
148 if start >= s.offset {
149 s.cursor = start - s.offset
150 }
151 s.errOffset = start
152 }
153
154 // prepareInTokens moves the cursor to the value which Decode reads between the tokens: after the comma or the
155 // colon which the grammar has before it. A read which fails is kept, as encoding/json keeps it. It is not
156 // inlined, so that Decode keeps the size it had.
157 //
158 //go:noinline
159 func (s *Stream) prepareInTokens() error {
160 if s.tokenState == tokenFailed || s.tokenState == tokenEnded {
161 return s.err
162 }
163 start := s.TotalOffset()
164 c, err := s.readDelim(start)
165 if err == nil {
166 err = s.valueStartError(c)
167 }
168 if err != nil {
169 if err == io.EOF {
170 // the end of the input in an object or an array
171 err = io.ErrUnexpectedEOF
172 }
173 s.moveBack(start)
174 s.err, s.tokenState = err, tokenFailed
175 return err
176 }
177 return nil
178 }
179
180 // valueStartError returns the error of a value which starts with c where it can't be read: the end of an object or
181 // an array, or a value which is not a string where a key is waited for.
182 func (s *Stream) valueStartError(c byte) error {
183 at := s.TotalOffset()
184 switch {
185 case c == '}' || c == ']':
186 // a bracket where the value starts
187 if err := s.valueStartMismatch(at - s.offset); err != nil {
188 return err
189 }
190 return s.invalidCharacter(at, "looking for beginning of value")
191 case kindOf(c) == noValue:
192 // a byte which starts no token
193 return s.invalidCharacter(at, "looking for beginning of value")
194 case c != '"' && (s.tokenState == tokenObjectStart || s.tokenState == tokenObjectKey):
195 return s.memberNameError(at)
196 }
197 return nil
198 }
199
200 // valueStartMismatch returns the error of the bracket at the position at in the buffer, where a value is waited for
201 // in the value which is read or where it starts, if it is the end of the other kind of the object or the array
202 // which Token opened last, which has a member or an element already: jsontext reports it as a mismatch of that
203 // one, whatever the value is in. It returns nil for any other one, which is not the start of a value.
204 func (s *Stream) valueStartMismatch(at int64) error {
205 switch c := s.buf[at]; {
206 case c == ']' && (s.tokenState == tokenObjectKey || s.tokenState == tokenObjectColon ||
207 s.tokenState == tokenObjectValue || s.tokenState == tokenObjectComma):
208 return s.invalidCharacter(s.offset+at, "after object key:value pair")
209 case c == '}' && (s.tokenState == tokenArrayValue || s.tokenState == tokenArrayComma):
210 return s.invalidCharacter(s.offset+at, "after array element")
211 }
212 return nil
213 }
214
215 // memberNameError returns the error of the value at the cursor, at the total offset at, where the name of a member
216 // of an object is waited for: the value is read first, as jsontext reads a value or a token, and its syntax error,
217 // or the end of the input in it, is the error; else the name is not a string.
218 func (s *Stream) memberNameError(at int64) error {
219 if _, err := s.scanValue(); err != nil {
220 return err
221 }
222 if err := s.valueSyntaxError(); err != nil {
223 return err
224 }
225 return errors.ErrSyntax("object member name must be a string", at+1)
226 }
227
228 // mismatchError returns the error of the end of an object or an array c at the total offset at, which doesn't end
229 // the one which is open.
230 func (s *Stream) mismatchError(at int64) error {
231 where := "looking for beginning of value"
232 switch s.tokenState {
233 case tokenArrayComma:
234 where = "after array element"
235 case tokenObjectComma, tokenObjectValue:
236 // a bracket where a value of an object is waited for too, as jsontext reports it
237 where = "after object key:value pair"
238 }
239 return s.invalidCharacter(at, where)
240 }
241
242 // Token returns the next token of the stream: a delimiter, a string, a number, a bool or nil. The commas and the
243 // colons are consumed where the grammar has them.
244 func (s *Stream) Token() (any, error) {
245 // a read which fails leaves the stream where it was, in its state, with the bytes from where it was
246 state := s.tokenState
247 s.keeps, s.keepFrom = true, s.TotalOffset()
248 v, err := s.token()
249 s.keeps = false
250 if _, ok := err.(*errors.UnmarshalTypeError); err == nil || ok {
251 // a token is read: InputOffset reports its end again
252 s.more.reset()
253 } else if s.tokenState != tokenFailed && s.tokenState != tokenEnded {
254 s.tokenState = state
255 }
256 return v, err
257 }
258
259 // token reads the next token for Token.
260 func (s *Stream) token() (any, error) {
261 if s.tokenState == tokenFailed || s.tokenState == tokenEnded {
262 return nil, s.err
263 }
264 start := s.TotalOffset()
265 c, err := s.readDelim(start)
266 if err != nil {
267 if err == io.EOF {
268 // InputOffset reports a comma or a colon before the end, with the white spaces before it, and not the
269 // white spaces at the end
270 s.moveBack(start)
271 if rest := trimLeftSpaces(s.buf[s.cursor:s.length]); len(rest) > 0 && (rest[0] == ',' || rest[0] == ':') {
272 s.errOffset = s.TotalOffset() + int64(len(s.buf[s.cursor:s.length])-len(rest)) + 1
273 }
274 s.tokenState, s.err = tokenEnded, err
275 return nil, err
276 }
277 return nil, s.restore(start, err)
278 }
279 at := s.TotalOffset()
280 switch c {
281 case '[', '{':
282 if s.tokenState == tokenObjectStart || s.tokenState == tokenObjectKey {
283 return nil, s.restore(start, errors.ErrSyntax("object member name must be a string", at+1))
284 }
285 s.cursor++
286 s.tokenStack = append(s.tokenStack, s.tokenState)
287 if c == '[' {
288 s.tokenState = tokenArrayStart
289 } else {
290 s.tokenState = tokenObjectStart
291 }
292 return json.Delim(c), nil
293 case ']', '}':
294 open := tokenArrayStart
295 if c == '}' {
296 open = tokenObjectStart
297 }
298 if len(s.tokenStack) == 0 || !s.inOpen(open) {
299 return nil, s.restore(start, s.mismatchError(at))
300 }
301 if s.tokenState == tokenObjectValue {
302 return nil, s.restore(start, errors.ErrSyntax("missing value after object key", at+1))
303 }
304 s.cursor++
305 s.tokenState = s.tokenStack[len(s.tokenStack)-1]
306 s.tokenStack = s.tokenStack[:len(s.tokenStack)-1]
307 s.tokenValueEnd()
308 return json.Delim(c), nil
309 case '"':
310 if s.tokenState == tokenObjectStart || s.tokenState == tokenObjectKey {
311 key, err := s.tokenString()
312 if err != nil {
313 return nil, s.restore(start, err)
314 }
315 s.tokenState = tokenObjectColon
316 return key, nil
317 }
318 default:
319 if kindOf(c) != noValue && (s.tokenState == tokenObjectStart || s.tokenState == tokenObjectKey) {
320 return nil, s.restore(start, s.memberNameError(at))
321 }
322 }
323 v, err := s.tokenValue(c)
324 if err != nil {
325 if _, ok := err.(*errors.UnmarshalTypeError); ok {
326 // the value is read: the stream goes on after it
327 s.tokenValueEnd()
328 return nil, err
329 }
330 return nil, s.restore(start, err)
331 }
332 s.tokenValueEnd()
333 return v, nil
334 }
335
336 // inOpen reports whether the innermost object or array which is open is of the kind of the state open.
337 func (s *Stream) inOpen(open tokenState) bool {
338 switch s.tokenState {
339 case tokenArrayStart, tokenArrayValue, tokenArrayComma:
340 return open == tokenArrayStart
341 }
342 return open == tokenObjectStart
343 }
344
345 // tokenError returns the syntax error of the byte c at the cursor, which the grammar doesn't have in the state.
346 func (s *Stream) tokenError(c byte) error {
347 return s.invalidCharacter(s.TotalOffset(), "looking for beginning of value")
348 }
349
350 // InputOffset returns the offset of the stream which Decoder.InputOffset reports: the end of the last token or
351 // value read, or where a read which failed started.
352 func (s *Stream) InputOffset() int64 {
353 offset := s.TotalOffset()
354 if s.tokenState == tokenFailed || s.tokenState == tokenEnded {
355 offset = s.errOffset
356 }
357 if s.more.peeked {
358 // after More, the start of the next token which it peeked at, after the white spaces before it
359 return s.more.offset
360 }
361 return offset
362 }
363
364 // More reports whether the current array or object has another element: at the end of the input in one, it
365 // reports true, and the error of the end is returned by the next read, as encoding/json of Go 1.27 does.
366 func (s *Stream) More() bool {
367 if s.tokenState == tokenFailed || s.tokenState == tokenEnded {
368 return s.err != io.EOF
369 }
370 // the next token is peeked at, with the comma or the colon before it, as Token reads it: the cursor is kept,
371 // so that the bytes from it stay in the buffer while more input is read
372 start := s.TotalOffset()
373 s.more.peeked, s.more.offset = true, start
374 pos, ok := s.peekFrom(s.cursor)
375 if !ok {
376 return s.moreAtEnd(start)
377 }
378 s.more.offset = s.offset + pos
379 at, c := s.offset+pos, s.buf[pos]
380 var delim byte
381 if c == ',' || c == ':' {
382 delim = c
383 if pos, ok = s.peekFrom(pos + 1); !ok {
384 // the next token is not known: a string, which follows any comma or colon, is taken for it
385 if s.needDelim('"') != delim {
386 return s.moreError(s.delimError('"', at))
387 }
388 return s.moreAtEnd(start)
389 }
390 c = s.buf[pos]
391 }
392 if s.needDelim(c) != delim {
393 return s.moreError(s.delimError(c, at))
394 }
395 return c != ']' && c != '}'
396 }
397
398 // peekFrom returns the position of the first byte from pos which is not a white space, reading more input as
399 // needed without moving the cursor, or false at the end of the input.
400 func (s *Stream) peekFrom(pos int64) (int64, bool) {
401 // the position is kept relative to the cursor, because a read may move the data ( grow )
402 rel := pos - s.cursor
403 for {
404 for pos = s.cursor + rel; pos < s.length; pos++ {
405 if !isWhiteSpace[s.buf[pos]] {
406 return pos, true
407 }
408 }
409 rel = s.length - s.cursor
410 if !s.read() {
411 return 0, false
412 }
413 }
414 }
415
416 // moreAtEnd returns what More reports at the end of the input, which it peeked at from the total offset start: the
417 // end of a stream of values, or the unexpected end of an object or an array, which is kept as the error.
418 func (s *Stream) moreAtEnd(start int64) bool {
419 if len(s.tokenStack) == 0 {
420 return false
421 }
422 // the error is at the end of the input, after the white spaces, which InputOffset doesn't report
423 s.err, s.errOffset, s.tokenState = errors.ErrSyntax("unexpected end of JSON input", s.offset+s.length), start, tokenFailed
424 return true
425 }
426
427 // moreError keeps err, the error of the token which More peeked at, which encoding/json of Go 1.27 reads, and
428 // returns true.
429 func (s *Stream) moreError(err error) bool {
430 s.err, s.errOffset, s.tokenState = err, s.TotalOffset(), tokenFailed
431 return true
432 }
433
434 func trimLeftSpaces(b []byte) []byte {
435 for len(b) > 0 && (b[0] == ' ' || b[0] == '\t' || b[0] == '\n' || b[0] == '\r') {
436 b = b[1:]
437 }
438 return b
439 }
440
441 // tokenValue returns the value at the cursor, which starts with c, as the token of a string, a number, a bool or
442 // null.
443 func (s *Stream) tokenValue(c byte) (any, error) {
444 switch c {
445 case '"':
446 return s.tokenString()
447 case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
448 end, err := s.scanValue()
449 if err != nil {
450 return nil, err
451 }
452 // the number ends where the grammar ends it, as 01 is 0 and 1, and is a number by the grammar
453 end = streamNumberEnd(s.buf, s.cursor, end)
454 literal := s.buf[s.cursor:end]
455 if !isValidNumber(literal) {
456 return nil, s.valueSyntaxError()
457 }
458 s.cursor = end
459 if (s.Option.Flags & UseNumberOption) != 0 {
460 return json.Number(literal), nil
461 }
462 f64, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&literal)), 64)
463 if err != nil {
464 // a number out of the range of float64, which is read: a type error of the value, which Token
465 // returns after it
466 return nil, &errors.UnmarshalTypeError{Value: "number " + string(literal), Type: float64Type, Offset: s.TotalOffset()}
467 }
468 return f64, nil
469 case 't', 'f', 'n':
470 end, err := s.scanValue()
471 if err != nil {
472 return nil, err
473 }
474 var v any
475 lit := "null"
476 switch c {
477 case 't':
478 v, lit = true, "true"
479 case 'f':
480 v, lit = false, "false"
481 }
482 // the literal ends after its bytes: what follows is the next token
483 if !bytes.HasPrefix(s.buf[s.cursor:end], []byte(lit)) {
484 return nil, s.valueSyntaxError()
485 }
486 s.cursor += int64(len(lit))
487 return v, nil
488 }
489 return nil, s.tokenError(c)
490 }