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