Debian Codegraph @

scanner.go

raw symbols SCIP
1 // Copyright 2016 Richard Gibson. All rights reserved.
2 // Copyright 2010 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package canonicaljson
7
8 // JSON value parser state machine.
9 // Just about at the limit of what is reasonable to write by hand.
10 // Some parts are a bit tedious, but overall it nicely factors out the
11 // otherwise common code from the multiple scanning functions
12 // in this package (checkValid, nextValue, etc).
13 //
14 // This file starts with two simple examples using the scanner
15 // before diving into the scanner itself.
16
17 import (
18 "fmt"
19 "strconv"
20 )
21
22 // checkValid verifies that data is valid JSON-encoded data.
23 // scan is passed in for use by checkValid to avoid an allocation.
24 func checkValid(data []byte, scan *scanner) error {
25 scan.reset()
26 for _, c := range data {
27 scan.bytes++
28 if scan.step(scan, c) == scanError {
29 return scan.err
30 }
31 }
32 if scan.eof() == scanError {
33 return scan.err
34 }
35 return nil
36 }
37
38 // nextValue splits data after the next whole JSON value,
39 // returning that value and the bytes that follow it as separate slices.
40 // scan is passed in for use by nextValue to avoid an allocation.
41 func nextValue(data []byte, scan *scanner) (value, rest []byte, err error) {
42 scan.reset()
43 for i, c := range data {
44 v := scan.step(scan, c)
45 if v >= scanEndObject {
46 switch v {
47 // probe the scanner with a space to determine whether we will
48 // get scanEnd on the next character. Otherwise, if the next character
49 // is not a space, scanEndTop allocates a needless error.
50 case scanEndObject, scanEndArray:
51 if scan.step(scan, ' ') == scanEnd {
52 return data[:i+1], data[i+1:], nil
53 }
54 case scanError:
55 return nil, nil, scan.err
56 case scanEnd:
57 return data[:i], data[i:], nil
58 }
59 }
60 }
61 if scan.eof() == scanError {
62 return nil, nil, scan.err
63 }
64 return data, nil, nil
65 }
66
67 // A SyntaxError is a description of a JSON syntax error.
68 type SyntaxError struct {
69 msg string // description of error
70 Offset int64 // error occurred after reading Offset bytes
71 }
72
73 func (e *SyntaxError) Error() string { return e.msg }
74
75 // A scanner is a JSON scanning state machine.
76 // Callers call scan.reset() and then pass bytes in one at a time
77 // by calling scan.step(&scan, c) for each byte.
78 // The return value, referred to as an opcode, tells the
79 // caller about significant parsing events like beginning
80 // and ending literals, objects, and arrays, so that the
81 // caller can follow along if it wishes.
82 // The return value scanEnd indicates that a single top-level
83 // JSON value has been completed, *before* the byte that
84 // just got passed in. (The indication must be delayed in order
85 // to recognize the end of numbers: is 123 a whole value or
86 // the beginning of 12345e+6?).
87 type scanner struct {
88 // The step is a func to be called to execute the next transition.
89 // Also tried using an integer constant and a single func
90 // with a switch, but using the func directly was 10% faster
91 // on a 64-bit Mac Mini, and it's nicer to read.
92 step func(*scanner, byte) int
93
94 // Reached end of top-level value.
95 endTop bool
96
97 // Stack of what we're in the middle of - array values, object keys, object values.
98 parseState []int
99
100 // Error that happened, if any.
101 err error
102
103 // 1-byte redo (see undo method)
104 redo bool
105 redoCode int
106 redoState func(*scanner, byte) int
107
108 // total bytes consumed, updated by decoder.Decode
109 bytes int64
110 }
111
112 // These values are returned by the state transition functions
113 // assigned to scanner.state and the method scanner.eof.
114 // They give details about the current state of the scan that
115 // callers might be interested to know about.
116 // It is okay to ignore the return value of any particular
117 // call to scanner.state: if one call returns scanError,
118 // every subsequent call will return scanError too.
119 const (
120 // Continue.
121 scanContinue = iota // uninteresting byte
122 scanBeginLiteral // end implied by next result != scanContinue
123 scanBeginObject // begin object
124 scanObjectKey // just finished object key (string)
125 scanObjectValue // just finished non-last object value
126 scanEndObject // end object (implies scanObjectValue if possible)
127 scanBeginArray // begin array
128 scanArrayValue // just finished array value
129 scanEndArray // end array (implies scanArrayValue if possible)
130 scanSkipSpace // space byte; can skip; known to be last "continue" result
131
132 // Stop.
133 scanEnd // top-level value ended *before* this byte; known to be first "stop" result
134 scanError // hit an error, scanner.err.
135 )
136
137 // These values are stored in the parseState stack.
138 // They give the current state of a composite value
139 // being scanned. If the parser is inside a nested value
140 // the parseState describes the nested state, outermost at entry 0.
141 const (
142 parseObjectKey = iota // parsing object key (before colon)
143 parseObjectValue // parsing object value (after colon)
144 parseArrayValue // parsing array value
145 )
146
147 // reset prepares the scanner for use.
148 // It must be called before calling s.step.
149 func (s *scanner) reset() {
150 s.step = stateBeginValue
151 s.parseState = s.parseState[0:0]
152 s.err = nil
153 s.redo = false
154 s.endTop = false
155 }
156
157 // eof tells the scanner that the end of input has been reached.
158 // It returns a scan status just as s.step does.
159 func (s *scanner) eof() int {
160 if s.err != nil {
161 return scanError
162 }
163 if s.endTop {
164 return scanEnd
165 }
166 s.step(s, ' ')
167 if s.endTop {
168 return scanEnd
169 }
170 if s.err == nil {
171 s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
172 }
173 return scanError
174 }
175
176 // pushParseState pushes a new parse state p onto the parse stack.
177 func (s *scanner) pushParseState(p int) {
178 s.parseState = append(s.parseState, p)
179 }
180
181 // popParseState pops a parse state (already obtained) off the stack
182 // and updates s.step accordingly.
183 func (s *scanner) popParseState() {
184 n := len(s.parseState) - 1
185 s.parseState = s.parseState[0:n]
186 s.redo = false
187 if n == 0 {
188 s.step = stateEndTop
189 s.endTop = true
190 } else {
191 s.step = stateEndValue
192 }
193 }
194
195 func isSpace(c byte) bool {
196 return c == ' ' || c == '\t' || c == '\r' || c == '\n'
197 }
198
199 // stateBeginValueOrEmpty is the state after reading `[`.
200 func stateBeginValueOrEmpty(s *scanner, c byte) int {
201 if c <= ' ' && isSpace(c) {
202 return scanSkipSpace
203 }
204 if c == ']' {
205 return stateEndValue(s, c)
206 }
207 return stateBeginValue(s, c)
208 }
209
210 // stateBeginValue is the state at the beginning of the input.
211 func stateBeginValue(s *scanner, c byte) int {
212 if c <= ' ' && isSpace(c) {
213 return scanSkipSpace
214 }
215 switch c {
216 case '{':
217 s.step = stateBeginStringOrEmpty
218 s.pushParseState(parseObjectKey)
219 return scanBeginObject
220 case '[':
221 s.step = stateBeginValueOrEmpty
222 s.pushParseState(parseArrayValue)
223 return scanBeginArray
224 case '"':
225 s.step = stateInString
226 return scanBeginLiteral
227 case '-':
228 s.step = stateNeg
229 return scanBeginLiteral
230 case '0': // beginning of 0.123
231 s.step = state0
232 return scanBeginLiteral
233 case 't': // beginning of true
234 s.step = stateT
235 return scanBeginLiteral
236 case 'f': // beginning of false
237 s.step = stateF
238 return scanBeginLiteral
239 case 'n': // beginning of null
240 s.step = stateN
241 return scanBeginLiteral
242 }
243 if '1' <= c && c <= '9' { // beginning of 1234.5
244 s.step = state1
245 return scanBeginLiteral
246 }
247 return s.error(c, "looking for beginning of value")
248 }
249
250 // stateBeginStringOrEmpty is the state after reading `{`.
251 func stateBeginStringOrEmpty(s *scanner, c byte) int {
252 if c <= ' ' && isSpace(c) {
253 return scanSkipSpace
254 }
255 if c == '}' {
256 n := len(s.parseState)
257 s.parseState[n-1] = parseObjectValue
258 return stateEndValue(s, c)
259 }
260 return stateBeginString(s, c)
261 }
262
263 // stateBeginString is the state after reading `{"key": value,`.
264 func stateBeginString(s *scanner, c byte) int {
265 if c <= ' ' && isSpace(c) {
266 return scanSkipSpace
267 }
268 if c == '"' {
269 s.step = stateInString
270 return scanBeginLiteral
271 }
272 return s.error(c, "looking for beginning of object key string")
273 }
274
275 // stateEndValue is the state after completing a value,
276 // such as after reading `{}` or `true` or `["x"`.
277 func stateEndValue(s *scanner, c byte) int {
278 n := len(s.parseState)
279 if n == 0 {
280 // Completed top-level before the current byte.
281 s.step = stateEndTop
282 s.endTop = true
283 return stateEndTop(s, c)
284 }
285 if c <= ' ' && isSpace(c) {
286 s.step = stateEndValue
287 return scanSkipSpace
288 }
289 ps := s.parseState[n-1]
290 switch ps {
291 case parseObjectKey:
292 if c == ':' {
293 s.parseState[n-1] = parseObjectValue
294 s.step = stateBeginValue
295 return scanObjectKey
296 }
297 return s.error(c, "after object key")
298 case parseObjectValue:
299 if c == ',' {
300 s.parseState[n-1] = parseObjectKey
301 s.step = stateBeginString
302 return scanObjectValue
303 }
304 if c == '}' {
305 s.popParseState()
306 return scanEndObject
307 }
308 return s.error(c, "after object key:value pair")
309 case parseArrayValue:
310 if c == ',' {
311 s.step = stateBeginValue
312 return scanArrayValue
313 }
314 if c == ']' {
315 s.popParseState()
316 return scanEndArray
317 }
318 return s.error(c, "after array element")
319 }
320 return s.error(c, "")
321 }
322
323 // stateEndTop is the state after finishing the top-level value,
324 // such as after reading `{}` or `[1,2,3]`.
325 // Only space characters should be seen now.
326 func stateEndTop(s *scanner, c byte) int {
327 if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
328 // Complain about non-space byte on next call.
329 s.error(c, "after top-level value")
330 }
331 return scanEnd
332 }
333
334 // stateInString is the state after reading `"`.
335 func stateInString(s *scanner, c byte) int {
336 if c == '"' {
337 s.step = stateEndValue
338 return scanContinue
339 }
340 if c == '\\' {
341 s.step = stateInStringEsc
342 return scanContinue
343 }
344 if c < 0x20 {
345 return s.error(c, "in string literal")
346 } else if c >= 0x80 {
347 // Require a well-formed UTF-8 sequence.
348 // See Table 3-7 in http://www.unicode.org/versions/Unicode10.0.0/ch03.pdf#G7404
349 if c >= 0xC2 && c <= 0xDF {
350 s.step = stateInStringContinuation1
351 } else if c == 0xE0 {
352 s.step = stateInStringContinuation2_E0
353 } else if c == 0xED {
354 s.step = stateInStringContinuation2_ED
355 } else if c >= 0xE1 && c <= 0xEF {
356 s.step = stateInStringContinuation2
357 } else if c == 0xF0 {
358 s.step = stateInStringContinuation3_F0
359 } else if c == 0xF4 {
360 s.step = stateInStringContinuation3_F4
361 } else if c >= 0xF1 && c <= 0xF3 {
362 s.step = stateInStringContinuation3
363 } else {
364 return s.error(c, "in string literal (expecting UTF-8 leading byte)")
365 }
366 }
367 return scanContinue
368 }
369
370 // stateInStringContinuation1 is the state after reading all but the
371 // final byte of a UTF-8 multi-byte sequence in a quoted string.
372 func stateInStringContinuation1(s *scanner, c byte) int {
373 if c&0xC0 != 0x80 {
374 return s.error(c, "in UTF-8 multi-byte sequence (expecting UTF-8 continuation byte)")
375 }
376 s.step = stateInString
377 return scanContinue
378 }
379
380 // stateInStringContinuation2 is the state after reading all but the
381 // final two bytes of a UTF-8 multi-byte sequence in a quoted string.
382 func stateInStringContinuation2(s *scanner, c byte) int {
383 if c&0xC0 != 0x80 {
384 return s.error(c, "in UTF-8 multi-byte sequence (expecting UTF-8 continuation byte)")
385 }
386 s.step = stateInStringContinuation1
387 return scanContinue
388 }
389
390 // stateInStringContinuation2_E0 is the state after reading an 0xE0 byte
391 // in a quoted string.
392 func stateInStringContinuation2_E0(s *scanner, c byte) int {
393 if c&0xC0 != 0x80 {
394 return s.error(c, "in UTF-8 three-byte sequence (expecting UTF-8 continuation byte)")
395 } else if c < 0xA0 {
396 return s.error(c, "in UTF-8 three-byte sequence (expecting well-formed UTF-8 continuation byte)")
397 }
398 s.step = stateInStringContinuation1
399 return scanContinue
400 }
401
402 // stateInStringContinuation2_ED is the state after reading an 0xED byte
403 // in a quoted string.
404 func stateInStringContinuation2_ED(s *scanner, c byte) int {
405 if c&0xC0 != 0x80 {
406 return s.error(c, "in UTF-8 three-byte sequence (expecting UTF-8 continuation byte)")
407 } else if c > 0x9F {
408 return s.error(c, "in UTF-8 three-byte sequence (expecting well-formed UTF-8 continuation byte)")
409 }
410 s.step = stateInStringContinuation1
411 return scanContinue
412 }
413
414 // stateInStringContinuation3 is the state after reading all but the
415 // final three bytes of a UTF-8 multi-byte sequence in a quoted string.
416 func stateInStringContinuation3(s *scanner, c byte) int {
417 if c&0xC0 != 0x80 {
418 return s.error(c, "in UTF-8 multi-byte sequence (expecting UTF-8 continuation byte)")
419 }
420 s.step = stateInStringContinuation2
421 return scanContinue
422 }
423
424 // stateInStringContinuation3_F0 is the state after reading an 0xF0 byte
425 // in a quoted string.
426 func stateInStringContinuation3_F0(s *scanner, c byte) int {
427 if c&0xC0 != 0x80 {
428 return s.error(c, "in UTF-8 four-byte sequence (expecting UTF-8 continuation byte)")
429 } else if c < 0x90 {
430 return s.error(c, "in UTF-8 four-byte sequence (expecting well-formed UTF-8 continuation byte)")
431 }
432 s.step = stateInStringContinuation2
433 return scanContinue
434 }
435
436 // stateInStringContinuation3_F4 is the state after reading an 0xF4 byte
437 // in a quoted string.
438 func stateInStringContinuation3_F4(s *scanner, c byte) int {
439 if c&0xC0 != 0x80 {
440 return s.error(c, "in UTF-8 four-byte sequence (expecting UTF-8 continuation byte)")
441 } else if c > 0x8F {
442 return s.error(c, "in UTF-8 four-byte sequence (expecting well-formed UTF-8 continuation byte)")
443 }
444 s.step = stateInStringContinuation2
445 return scanContinue
446 }
447
448 // stateInStringEsc is the state after reading `"\` during a quoted string.
449 func stateInStringEsc(s *scanner, c byte) int {
450 switch c {
451 case 'b', 'f', 'n', 'r', 't', '\\', '/', '"':
452 s.step = stateInString
453 return scanContinue
454 case 'u':
455 s.step = stateInStringEscU
456 return scanContinue
457 }
458 return s.error(c, "in string escape code")
459 }
460
461 // stateInStringEscU is the state after reading `"\u` during a quoted string.
462 func stateInStringEscU(s *scanner, c byte) int {
463 if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
464 s.step = stateInStringEscU1
465 return scanContinue
466 }
467 // numbers
468 return s.error(c, "in \\u hexadecimal character escape")
469 }
470
471 // stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
472 func stateInStringEscU1(s *scanner, c byte) int {
473 if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
474 s.step = stateInStringEscU12
475 return scanContinue
476 }
477 // numbers
478 return s.error(c, "in \\u hexadecimal character escape")
479 }
480
481 // stateInStringEscU12 is the state after reading `"\u12` during a quoted string.
482 func stateInStringEscU12(s *scanner, c byte) int {
483 if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
484 s.step = stateInStringEscU123
485 return scanContinue
486 }
487 // numbers
488 return s.error(c, "in \\u hexadecimal character escape")
489 }
490
491 // stateInStringEscU123 is the state after reading `"\u123` during a quoted string.
492 func stateInStringEscU123(s *scanner, c byte) int {
493 if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
494 s.step = stateInString
495 return scanContinue
496 }
497 // numbers
498 return s.error(c, "in \\u hexadecimal character escape")
499 }
500
501 // stateNeg is the state after reading `-` during a number.
502 func stateNeg(s *scanner, c byte) int {
503 if c == '0' {
504 s.step = state0
505 return scanContinue
506 }
507 if '1' <= c && c <= '9' {
508 s.step = state1
509 return scanContinue
510 }
511 return s.error(c, "in numeric literal")
512 }
513
514 // state1 is the state after reading a non-zero integer during a number,
515 // such as after reading `1` or `100` but not `0`.
516 func state1(s *scanner, c byte) int {
517 if '0' <= c && c <= '9' {
518 s.step = state1
519 return scanContinue
520 }
521 return state0(s, c)
522 }
523
524 // state0 is the state after reading `0` during a number.
525 func state0(s *scanner, c byte) int {
526 if c == '.' {
527 s.step = stateDot
528 return scanContinue
529 }
530 if c == 'e' || c == 'E' {
531 s.step = stateE
532 return scanContinue
533 }
534 return stateEndValue(s, c)
535 }
536
537 // stateDot is the state after reading the integer and decimal point in a number,
538 // such as after reading `1.`.
539 func stateDot(s *scanner, c byte) int {
540 if '0' <= c && c <= '9' {
541 s.step = stateDot0
542 return scanContinue
543 }
544 return s.error(c, "after decimal point in numeric literal")
545 }
546
547 // stateDot0 is the state after reading the integer, decimal point, and subsequent
548 // digits of a number, such as after reading `3.14`.
549 func stateDot0(s *scanner, c byte) int {
550 if '0' <= c && c <= '9' {
551 return scanContinue
552 }
553 if c == 'e' || c == 'E' {
554 s.step = stateE
555 return scanContinue
556 }
557 return stateEndValue(s, c)
558 }
559
560 // stateE is the state after reading the significand and e in a number,
561 // such as after reading `314e` or `0.314e`.
562 func stateE(s *scanner, c byte) int {
563 if c == '+' || c == '-' {
564 s.step = stateESign
565 return scanContinue
566 }
567 return stateESign(s, c)
568 }
569
570 // stateESign is the state after reading the significand, e, and sign in a number,
571 // such as after reading `314e-` or `0.314e+`.
572 func stateESign(s *scanner, c byte) int {
573 if '0' <= c && c <= '9' {
574 s.step = stateE0
575 return scanContinue
576 }
577 return s.error(c, "in exponent of numeric literal")
578 }
579
580 // stateE0 is the state after reading the significand, e, optional sign,
581 // and at least one digit of the exponent in a number,
582 // such as after reading `314e-2` or `0.314e+1` or `3.14e0`.
583 func stateE0(s *scanner, c byte) int {
584 if '0' <= c && c <= '9' {
585 return scanContinue
586 }
587 return stateEndValue(s, c)
588 }
589
590 // stateT is the state after reading `t`.
591 func stateT(s *scanner, c byte) int {
592 if c == 'r' {
593 s.step = stateTr
594 return scanContinue
595 }
596 return s.error(c, "in literal true (expecting 'r')")
597 }
598
599 // stateTr is the state after reading `tr`.
600 func stateTr(s *scanner, c byte) int {
601 if c == 'u' {
602 s.step = stateTru
603 return scanContinue
604 }
605 return s.error(c, "in literal true (expecting 'u')")
606 }
607
608 // stateTru is the state after reading `tru`.
609 func stateTru(s *scanner, c byte) int {
610 if c == 'e' {
611 s.step = stateEndValue
612 return scanContinue
613 }
614 return s.error(c, "in literal true (expecting 'e')")
615 }
616
617 // stateF is the state after reading `f`.
618 func stateF(s *scanner, c byte) int {
619 if c == 'a' {
620 s.step = stateFa
621 return scanContinue
622 }
623 return s.error(c, "in literal false (expecting 'a')")
624 }
625
626 // stateFa is the state after reading `fa`.
627 func stateFa(s *scanner, c byte) int {
628 if c == 'l' {
629 s.step = stateFal
630 return scanContinue
631 }
632 return s.error(c, "in literal false (expecting 'l')")
633 }
634
635 // stateFal is the state after reading `fal`.
636 func stateFal(s *scanner, c byte) int {
637 if c == 's' {
638 s.step = stateFals
639 return scanContinue
640 }
641 return s.error(c, "in literal false (expecting 's')")
642 }
643
644 // stateFals is the state after reading `fals`.
645 func stateFals(s *scanner, c byte) int {
646 if c == 'e' {
647 s.step = stateEndValue
648 return scanContinue
649 }
650 return s.error(c, "in literal false (expecting 'e')")
651 }
652
653 // stateN is the state after reading `n`.
654 func stateN(s *scanner, c byte) int {
655 if c == 'u' {
656 s.step = stateNu
657 return scanContinue
658 }
659 return s.error(c, "in literal null (expecting 'u')")
660 }
661
662 // stateNu is the state after reading `nu`.
663 func stateNu(s *scanner, c byte) int {
664 if c == 'l' {
665 s.step = stateNul
666 return scanContinue
667 }
668 return s.error(c, "in literal null (expecting 'l')")
669 }
670
671 // stateNul is the state after reading `nul`.
672 func stateNul(s *scanner, c byte) int {
673 if c == 'l' {
674 s.step = stateEndValue
675 return scanContinue
676 }
677 return s.error(c, "in literal null (expecting 'l')")
678 }
679
680 // stateError is the state after reaching a syntax error,
681 // such as after reading `[1}` or `5.1.2`.
682 func stateError(s *scanner, c byte) int {
683 return scanError
684 }
685
686 // error records an error and switches to the error state.
687 func (s *scanner) error(c byte, context string) int {
688 s.step = stateError
689 s.err = &SyntaxError{"invalid character " + quoteChar(c) + " " + context, s.bytes}
690 return scanError
691 }
692
693 // quoteChar formats c as a quoted character literal
694 func quoteChar(c byte) string {
695 // Force escapes (where necessary) to use \x.
696 if c < 0x7F {
697 return strconv.QuoteRune(rune(c))
698 }
699 return fmt.Sprintf("'\\x%02x'", c)
700 }
701
702 // undo causes the scanner to return scanCode from the next state transition.
703 // This gives callers a simple 1-byte undo mechanism.
704 func (s *scanner) undo(scanCode int) {
705 if s.redo {
706 panic("canonicaljson: invalid use of scanner")
707 }
708 s.redoCode = scanCode
709 s.redoState = s.step
710 s.step = stateRedo
711 s.redo = true
712 }
713
714 // stateRedo helps implement the scanner's 1-byte undo.
715 func stateRedo(s *scanner, c byte) int {
716 s.redo = false
717 s.step = s.redoState
718 return s.redoCode
719 }