JSONTokenizer.as 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. /*
  2. Copyright (c) 2008, Adobe Systems Incorporated
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. * Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. * Neither the name of Adobe Systems Incorporated nor the names of its
  13. contributors may be used to endorse or promote products derived from
  14. this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  16. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  17. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  19. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  20. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  23. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  24. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package com.adobe.serialization.json {
  28. public class JSONTokenizer {
  29. /**
  30. * Flag indicating if the tokenizer should only recognize
  31. * standard JSON tokens. Setting to <code>false</code> allows
  32. * tokens such as NaN and allows numbers to be formatted as
  33. * hex, etc.
  34. */
  35. private var strict:Boolean;
  36. /** The object that will get parsed from the JSON string */
  37. private var obj:Object;
  38. /** The JSON string to be parsed */
  39. private var jsonString:String;
  40. /** The current parsing location in the JSON string */
  41. private var loc:int;
  42. /** The current character in the JSON string during parsing */
  43. private var ch:String;
  44. /**
  45. * The regular expression used to make sure the string does not
  46. * contain invalid control characters.
  47. */
  48. private var controlCharsRegExp:RegExp = /[\x00-\x1F]/;
  49. /**
  50. * Constructs a new JSONDecoder to parse a JSON string
  51. * into a native object.
  52. *
  53. * @param s The JSON string to be converted
  54. * into a native object
  55. */
  56. public function JSONTokenizer( s:String, strict:Boolean )
  57. {
  58. jsonString = s;
  59. this.strict = strict;
  60. loc = 0;
  61. // prime the pump by getting the first character
  62. nextChar();
  63. }
  64. /**
  65. * Gets the next token in the input sting and advances
  66. * the character to the next character after the token
  67. */
  68. public function getNextToken():JSONToken
  69. {
  70. var token:JSONToken = new JSONToken();
  71. // skip any whitespace / comments since the last
  72. // token was read
  73. skipIgnored();
  74. // examine the new character and see what we have...
  75. switch ( ch )
  76. {
  77. case '{':
  78. token.type = JSONTokenType.LEFT_BRACE;
  79. token.value = '{';
  80. nextChar();
  81. break
  82. case '}':
  83. token.type = JSONTokenType.RIGHT_BRACE;
  84. token.value = '}';
  85. nextChar();
  86. break
  87. case '[':
  88. token.type = JSONTokenType.LEFT_BRACKET;
  89. token.value = '[';
  90. nextChar();
  91. break
  92. case ']':
  93. token.type = JSONTokenType.RIGHT_BRACKET;
  94. token.value = ']';
  95. nextChar();
  96. break
  97. case ',':
  98. token.type = JSONTokenType.COMMA;
  99. token.value = ',';
  100. nextChar();
  101. break
  102. case ':':
  103. token.type = JSONTokenType.COLON;
  104. token.value = ':';
  105. nextChar();
  106. break;
  107. case 't': // attempt to read true
  108. var possibleTrue:String = "t" + nextChar() + nextChar() + nextChar();
  109. if ( possibleTrue == "true" )
  110. {
  111. token.type = JSONTokenType.TRUE;
  112. token.value = true;
  113. nextChar();
  114. }
  115. else
  116. {
  117. parseError( "Expecting 'true' but found " + possibleTrue );
  118. }
  119. break;
  120. case 'f': // attempt to read false
  121. var possibleFalse:String = "f" + nextChar() + nextChar() + nextChar() + nextChar();
  122. if ( possibleFalse == "false" )
  123. {
  124. token.type = JSONTokenType.FALSE;
  125. token.value = false;
  126. nextChar();
  127. }
  128. else
  129. {
  130. parseError( "Expecting 'false' but found " + possibleFalse );
  131. }
  132. break;
  133. case 'n': // attempt to read null
  134. var possibleNull:String = "n" + nextChar() + nextChar() + nextChar();
  135. if ( possibleNull == "null" )
  136. {
  137. token.type = JSONTokenType.NULL;
  138. token.value = null;
  139. nextChar();
  140. }
  141. else
  142. {
  143. parseError( "Expecting 'null' but found " + possibleNull );
  144. }
  145. break;
  146. case 'N': // attempt to read NaN
  147. var possibleNaN:String = "N" + nextChar() + nextChar();
  148. if ( possibleNaN == "NaN" )
  149. {
  150. token.type = JSONTokenType.NAN;
  151. token.value = NaN;
  152. nextChar();
  153. }
  154. else
  155. {
  156. parseError( "Expecting 'NaN' but found " + possibleNaN );
  157. }
  158. break;
  159. case '"': // the start of a string
  160. token = readString();
  161. break;
  162. default:
  163. // see if we can read a number
  164. if ( isDigit( ch ) || ch == '-' )
  165. {
  166. token = readNumber();
  167. }
  168. else if ( ch == '' )
  169. {
  170. // check for reading past the end of the string
  171. return null;
  172. }
  173. else
  174. {
  175. // not sure what was in the input string - it's not
  176. // anything we expected
  177. parseError( "Unexpected " + ch + " encountered" );
  178. }
  179. }
  180. return token;
  181. }
  182. /**
  183. * Attempts to read a string from the input string. Places
  184. * the character location at the first character after the
  185. * string. It is assumed that ch is " before this method is called.
  186. *
  187. * @return the JSONToken with the string value if a string could
  188. * be read. Throws an error otherwise.
  189. */
  190. private function readString():JSONToken
  191. {
  192. // Rather than examine the string character-by-character, it's
  193. // faster to use indexOf to try to and find the closing quote character
  194. // and then replace escape sequences after the fact.
  195. // Start at the current input stream position
  196. var quoteIndex:int = loc;
  197. do
  198. {
  199. // Find the next quote in the input stream
  200. quoteIndex = jsonString.indexOf( "\"", quoteIndex );
  201. if ( quoteIndex >= 0 )
  202. {
  203. // We found the next double quote character in the string, but we need
  204. // to make sure it is not part of an escape sequence.
  205. // Keep looping backwards while the previous character is a backslash
  206. var backspaceCount:int = 0;
  207. var backspaceIndex:int = quoteIndex - 1;
  208. while ( jsonString.charAt( backspaceIndex ) == "\\" )
  209. {
  210. backspaceCount++;
  211. backspaceIndex--;
  212. }
  213. // If we have an even number of backslashes, that means this is the ending quote
  214. if ( backspaceCount % 2 == 0 )
  215. {
  216. break;
  217. }
  218. // At this point, the quote was determined to be part of an escape sequence
  219. // so we need to move past the quote index to look for the next one
  220. quoteIndex++;
  221. }
  222. else // There are no more quotes in the string and we haven't found the end yet
  223. {
  224. parseError( "Unterminated string literal" );
  225. }
  226. } while ( true );
  227. // Unescape the string
  228. // the token for the string we'll try to read
  229. var token:JSONToken = new JSONToken();
  230. token.type = JSONTokenType.STRING;
  231. // Attach resulting string to the token to return it
  232. token.value = unescapeString( jsonString.substr( loc, quoteIndex - loc ) );
  233. // Move past the closing quote in the input string. This updates the next
  234. // character in the input stream to be the character one after the closing quote
  235. loc = quoteIndex + 1;
  236. nextChar();
  237. return token;
  238. }
  239. /**
  240. * Convert all JavaScript escape characters into normal characters
  241. *
  242. * @param input The input string to convert
  243. * @return Original string with escape characters replaced by real characters
  244. */
  245. public function unescapeString( input:String ):String
  246. {
  247. // Issue #104 - If the string contains any unescaped control characters, this
  248. // is an error in strict mode
  249. if ( strict && controlCharsRegExp.test( input ) )
  250. {
  251. parseError( "String contains unescaped control character (0x00-0x1F)" );
  252. }
  253. var result:String = "";
  254. var backslashIndex:int = 0;
  255. var nextSubstringStartPosition:int = 0;
  256. var len:int = input.length;
  257. do
  258. {
  259. // Find the next backslash in the input
  260. backslashIndex = input.indexOf( '\\', nextSubstringStartPosition );
  261. if ( backslashIndex >= 0 )
  262. {
  263. result += input.substr( nextSubstringStartPosition, backslashIndex - nextSubstringStartPosition );
  264. // Move past the backslash and next character (all escape sequences are
  265. // two characters, except for \u, which will advance this further)
  266. nextSubstringStartPosition = backslashIndex + 2;
  267. // Check the next character so we know what to escape
  268. var afterBackslashIndex:int = backslashIndex + 1;
  269. var escapedChar:String = input.charAt( afterBackslashIndex );
  270. switch ( escapedChar )
  271. {
  272. // Try to list the most common expected cases first to improve performance
  273. case '"': result += '"'; break; // quotation mark
  274. case '\\': result += '\\'; break; // reverse solidus
  275. case 'n': result += '\n'; break; // newline
  276. case 'r': result += '\r'; break; // carriage return
  277. case 't': result += '\t'; break; // horizontal tab
  278. // Convert a unicode escape sequence to it's character value
  279. case 'u':
  280. // Save the characters as a string we'll convert to an int
  281. var hexValue:String = "";
  282. // Make sure there are enough characters in the string leftover
  283. if ( nextSubstringStartPosition + 4 > len )
  284. {
  285. parseError( "Unexpected end of input. Expecting 4 hex digits after \\u." );
  286. }
  287. // Try to find 4 hex characters
  288. for ( var i:int = nextSubstringStartPosition; i < nextSubstringStartPosition + 4; i++ )
  289. {
  290. // get the next character and determine
  291. // if it's a valid hex digit or not
  292. var possibleHexChar:String = input.charAt( i );
  293. if ( !isHexDigit( possibleHexChar ) )
  294. {
  295. parseError( "Excepted a hex digit, but found: " + possibleHexChar );
  296. }
  297. // Valid hex digit, add it to the value
  298. hexValue += possibleHexChar;
  299. }
  300. // Convert hexValue to an integer, and use that
  301. // integer value to create a character to add
  302. // to our string.
  303. result += String.fromCharCode( parseInt( hexValue, 16 ) );
  304. // Move past the 4 hex digits that we just read
  305. nextSubstringStartPosition += 4;
  306. break;
  307. case 'f': result += '\f'; break; // form feed
  308. case '/': result += '/'; break; // solidus
  309. case 'b': result += '\b'; break; // bell
  310. default: result += '\\' + escapedChar; // Couldn't unescape the sequence, so just pass it through
  311. }
  312. }
  313. else
  314. {
  315. // No more backslashes to replace, append the rest of the string
  316. result += input.substr( nextSubstringStartPosition );
  317. break;
  318. }
  319. } while ( nextSubstringStartPosition < len );
  320. return result;
  321. }
  322. /**
  323. * Attempts to read a number from the input string. Places
  324. * the character location at the first character after the
  325. * number.
  326. *
  327. * @return The JSONToken with the number value if a number could
  328. * be read. Throws an error otherwise.
  329. */
  330. private function readNumber():JSONToken
  331. {
  332. // the string to accumulate the number characters
  333. // into that we'll convert to a number at the end
  334. var input:String = "";
  335. // check for a negative number
  336. if ( ch == '-' )
  337. {
  338. input += '-';
  339. nextChar();
  340. }
  341. // the number must start with a digit
  342. if ( !isDigit( ch ) )
  343. {
  344. parseError( "Expecting a digit" );
  345. }
  346. // 0 can only be the first digit if it
  347. // is followed by a decimal point
  348. if ( ch == '0' )
  349. {
  350. input += ch;
  351. nextChar();
  352. // make sure no other digits come after 0
  353. if ( isDigit( ch ) )
  354. {
  355. parseError( "A digit cannot immediately follow 0" );
  356. }
  357. // unless we have 0x which starts a hex number, but this
  358. // doesn't match JSON spec so check for not strict mode.
  359. else if ( !strict && ch == 'x' )
  360. {
  361. // include the x in the input
  362. input += ch;
  363. nextChar();
  364. // need at least one hex digit after 0x to
  365. // be valid
  366. if ( isHexDigit( ch ) )
  367. {
  368. input += ch;
  369. nextChar();
  370. }
  371. else
  372. {
  373. parseError( "Number in hex format require at least one hex digit after \"0x\"" );
  374. }
  375. // consume all of the hex values
  376. while ( isHexDigit( ch ) )
  377. {
  378. input += ch;
  379. nextChar();
  380. }
  381. }
  382. }
  383. else
  384. {
  385. // read numbers while we can
  386. while ( isDigit( ch ) )
  387. {
  388. input += ch;
  389. nextChar();
  390. }
  391. }
  392. // check for a decimal value
  393. if ( ch == '.' )
  394. {
  395. input += '.';
  396. nextChar();
  397. // after the decimal there has to be a digit
  398. if ( !isDigit( ch ) )
  399. {
  400. parseError( "Expecting a digit" );
  401. }
  402. // read more numbers to get the decimal value
  403. while ( isDigit( ch ) )
  404. {
  405. input += ch;
  406. nextChar();
  407. }
  408. }
  409. // check for scientific notation
  410. if ( ch == 'e' || ch == 'E' )
  411. {
  412. input += "e"
  413. nextChar();
  414. // check for sign
  415. if ( ch == '+' || ch == '-' )
  416. {
  417. input += ch;
  418. nextChar();
  419. }
  420. // require at least one number for the exponent
  421. // in this case
  422. if ( !isDigit( ch ) )
  423. {
  424. parseError( "Scientific notation number needs exponent value" );
  425. }
  426. // read in the exponent
  427. while ( isDigit( ch ) )
  428. {
  429. input += ch;
  430. nextChar();
  431. }
  432. }
  433. // convert the string to a number value
  434. var num:Number = Number( input );
  435. if ( isFinite( num ) && !isNaN( num ) )
  436. {
  437. // the token for the number that we've read
  438. var token:JSONToken = new JSONToken();
  439. token.type = JSONTokenType.NUMBER;
  440. token.value = num;
  441. return token;
  442. }
  443. else
  444. {
  445. parseError( "Number " + num + " is not valid!" );
  446. }
  447. return null;
  448. }
  449. /**
  450. * Reads the next character in the input
  451. * string and advances the character location.
  452. *
  453. * @return The next character in the input string, or
  454. * null if we've read past the end.
  455. */
  456. private function nextChar():String
  457. {
  458. return ch = jsonString.charAt( loc++ );
  459. }
  460. /**
  461. * Advances the character location past any
  462. * sort of white space and comments
  463. */
  464. private function skipIgnored():void
  465. {
  466. var originalLoc:int;
  467. // keep trying to skip whitespace and comments as long
  468. // as we keep advancing past the original location
  469. do
  470. {
  471. originalLoc = loc;
  472. skipWhite();
  473. skipComments();
  474. }
  475. while ( originalLoc != loc );
  476. }
  477. /**
  478. * Skips comments in the input string, either
  479. * single-line or multi-line. Advances the character
  480. * to the first position after the end of the comment.
  481. */
  482. private function skipComments():void
  483. {
  484. if ( ch == '/' )
  485. {
  486. // Advance past the first / to find out what type of comment
  487. nextChar();
  488. switch ( ch )
  489. {
  490. case '/': // single-line comment, read through end of line
  491. // Loop over the characters until we find
  492. // a newline or until there's no more characters left
  493. do
  494. {
  495. nextChar();
  496. }
  497. while ( ch != '\n' && ch != '' )
  498. // move past the \n
  499. nextChar();
  500. break;
  501. case '*': // multi-line comment, read until closing */
  502. // move past the opening *
  503. nextChar();
  504. // try to find a trailing */
  505. while ( true )
  506. {
  507. if ( ch == '*' )
  508. {
  509. // check to see if we have a closing /
  510. nextChar();
  511. if ( ch == '/')
  512. {
  513. // move past the end of the closing */
  514. nextChar();
  515. break;
  516. }
  517. }
  518. else
  519. {
  520. // move along, looking if the next character is a *
  521. nextChar();
  522. }
  523. // when we're here we've read past the end of
  524. // the string without finding a closing */, so error
  525. if ( ch == '' )
  526. {
  527. parseError( "Multi-line comment not closed" );
  528. }
  529. }
  530. break;
  531. // Can't match a comment after a /, so it's a parsing error
  532. default:
  533. parseError( "Unexpected " + ch + " encountered (expecting '/' or '*' )" );
  534. }
  535. }
  536. }
  537. /**
  538. * Skip any whitespace in the input string and advances
  539. * the character to the first character after any possible
  540. * whitespace.
  541. */
  542. private function skipWhite():void
  543. {
  544. // As long as there are spaces in the input
  545. // stream, advance the current location pointer
  546. // past them
  547. while ( isWhiteSpace( ch ) )
  548. {
  549. nextChar();
  550. }
  551. }
  552. /**
  553. * Determines if a character is whitespace or not.
  554. *
  555. * @return True if the character passed in is a whitespace
  556. * character
  557. */
  558. private function isWhiteSpace( ch:String ):Boolean
  559. {
  560. // Check for the whitespace defined in the spec
  561. if ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' )
  562. {
  563. return true;
  564. }
  565. // If we're not in strict mode, we also accept non-breaking space
  566. else if ( !strict && ch.charCodeAt( 0 ) == 160 )
  567. {
  568. return true;
  569. }
  570. return false;
  571. }
  572. /**
  573. * Determines if a character is a digit [0-9].
  574. *
  575. * @return True if the character passed in is a digit
  576. */
  577. private function isDigit( ch:String ):Boolean
  578. {
  579. return ( ch >= '0' && ch <= '9' );
  580. }
  581. /**
  582. * Determines if a character is a hex digit [0-9A-Fa-f].
  583. *
  584. * @return True if the character passed in is a hex digit
  585. */
  586. private function isHexDigit( ch:String ):Boolean
  587. {
  588. return ( isDigit( ch ) || ( ch >= 'A' && ch <= 'F' ) || ( ch >= 'a' && ch <= 'f' ) );
  589. }
  590. /**
  591. * Raises a parsing error with a specified message, tacking
  592. * on the error location and the original string.
  593. *
  594. * @param message The message indicating why the error occurred
  595. */
  596. public function parseError( message:String ):void
  597. {
  598. throw new JSONParseError( message, loc, jsonString );
  599. }
  600. }
  601. }