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