Debian Codegraph @

scanner.go

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