PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/com/adobe/serialization/json/JSONTokenizer.as

http://github.com/mintdigital/hemlock
ActionScript | 547 lines | 335 code | 70 blank | 142 comment | 63 complexity | 624151077f7ff9f4c71fb770d7dfc8f0 MD5 | raw file
  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. /** The object that will get parsed from the JSON string */
  30. private var obj:Object;
  31. /** The JSON string to be parsed */
  32. private var jsonString:String;
  33. /** The current parsing location in the JSON string */
  34. private var loc:int;
  35. /** The current character in the JSON string during parsing */
  36. private var ch:String;
  37. /**
  38. * Constructs a new JSONDecoder to parse a JSON string
  39. * into a native object.
  40. *
  41. * @param s The JSON string to be converted
  42. * into a native object
  43. */
  44. public function JSONTokenizer( s:String ) {
  45. jsonString = s;
  46. loc = 0;
  47. // prime the pump by getting the first character
  48. nextChar();
  49. }
  50. /**
  51. * Gets the next token in the input sting and advances
  52. * the character to the next character after the token
  53. */
  54. public function getNextToken():JSONToken {
  55. var token:JSONToken = new JSONToken();
  56. // skip any whitespace / comments since the last
  57. // token was read
  58. skipIgnored();
  59. // examine the new character and see what we have...
  60. switch ( ch ) {
  61. case '{':
  62. token.type = JSONTokenType.LEFT_BRACE;
  63. token.value = '{';
  64. nextChar();
  65. break
  66. case '}':
  67. token.type = JSONTokenType.RIGHT_BRACE;
  68. token.value = '}';
  69. nextChar();
  70. break
  71. case '[':
  72. token.type = JSONTokenType.LEFT_BRACKET;
  73. token.value = '[';
  74. nextChar();
  75. break
  76. case ']':
  77. token.type = JSONTokenType.RIGHT_BRACKET;
  78. token.value = ']';
  79. nextChar();
  80. break
  81. case ',':
  82. token.type = JSONTokenType.COMMA;
  83. token.value = ',';
  84. nextChar();
  85. break
  86. case ':':
  87. token.type = JSONTokenType.COLON;
  88. token.value = ':';
  89. nextChar();
  90. break;
  91. case 't': // attempt to read true
  92. var possibleTrue:String = "t" + nextChar() + nextChar() + nextChar();
  93. if ( possibleTrue == "true" ) {
  94. token.type = JSONTokenType.TRUE;
  95. token.value = true;
  96. nextChar();
  97. } else {
  98. parseError( "Expecting 'true' but found " + possibleTrue );
  99. }
  100. break;
  101. case 'f': // attempt to read false
  102. var possibleFalse:String = "f" + nextChar() + nextChar() + nextChar() + nextChar();
  103. if ( possibleFalse == "false" ) {
  104. token.type = JSONTokenType.FALSE;
  105. token.value = false;
  106. nextChar();
  107. } else {
  108. parseError( "Expecting 'false' but found " + possibleFalse );
  109. }
  110. break;
  111. case 'n': // attempt to read null
  112. var possibleNull:String = "n" + nextChar() + nextChar() + nextChar();
  113. if ( possibleNull == "null" ) {
  114. token.type = JSONTokenType.NULL;
  115. token.value = null;
  116. nextChar();
  117. } else {
  118. parseError( "Expecting 'null' but found " + possibleNull );
  119. }
  120. break;
  121. case '"': // the start of a string
  122. token = readString();
  123. break;
  124. default:
  125. // see if we can read a number
  126. if ( isDigit( ch ) || ch == '-' ) {
  127. token = readNumber();
  128. } else if ( ch == '' ) {
  129. // check for reading past the end of the string
  130. return null;
  131. } else {
  132. // not sure what was in the input string - it's not
  133. // anything we expected
  134. parseError( "Unexpected " + ch + " encountered" );
  135. }
  136. }
  137. return token;
  138. }
  139. /**
  140. * Attempts to read a string from the input string. Places
  141. * the character location at the first character after the
  142. * string. It is assumed that ch is " before this method is called.
  143. *
  144. * @return the JSONToken with the string value if a string could
  145. * be read. Throws an error otherwise.
  146. */
  147. private function readString():JSONToken {
  148. // the token for the string we'll try to read
  149. var token:JSONToken = new JSONToken();
  150. token.type = JSONTokenType.STRING;
  151. // the string to store the string we'll try to read
  152. var string:String = "";
  153. // advance past the first "
  154. nextChar();
  155. while ( ch != '"' && ch != '' ) {
  156. // unescape the escape sequences in the string
  157. if ( ch == '\\' ) {
  158. // get the next character so we know what
  159. // to unescape
  160. nextChar();
  161. switch ( ch ) {
  162. case '"': // quotation mark
  163. string += '"';
  164. break;
  165. case '/': // solidus
  166. string += "/";
  167. break;
  168. case '\\': // reverse solidus
  169. string += '\\';
  170. break;
  171. case 'b': // bell
  172. string += '\b';
  173. break;
  174. case 'f': // form feed
  175. string += '\f';
  176. break;
  177. case 'n': // newline
  178. string += '\n';
  179. break;
  180. case 'r': // carriage return
  181. string += '\r';
  182. break;
  183. case 't': // horizontal tab
  184. string += '\t'
  185. break;
  186. case 'u':
  187. // convert a unicode escape sequence
  188. // to it's character value - expecting
  189. // 4 hex digits
  190. // save the characters as a string we'll convert to an int
  191. var hexValue:String = "";
  192. // try to find 4 hex characters
  193. for ( var i:int = 0; i < 4; i++ ) {
  194. // get the next character and determine
  195. // if it's a valid hex digit or not
  196. if ( !isHexDigit( nextChar() ) ) {
  197. parseError( " Excepted a hex digit, but found: " + ch );
  198. }
  199. // valid, add it to the value
  200. hexValue += ch;
  201. }
  202. // convert hexValue to an integer, and use that
  203. // integrer value to create a character to add
  204. // to our string.
  205. string += String.fromCharCode( parseInt( hexValue, 16 ) );
  206. break;
  207. default:
  208. // couldn't unescape the sequence, so just
  209. // pass it through
  210. string += '\\' + ch;
  211. }
  212. } else {
  213. // didn't have to unescape, so add the character to the string
  214. string += ch;
  215. }
  216. // move to the next character
  217. nextChar();
  218. }
  219. // we read past the end of the string without closing it, which
  220. // is a parse error
  221. if ( ch == '' ) {
  222. parseError( "Unterminated string literal" );
  223. }
  224. // move past the closing " in the input string
  225. nextChar();
  226. // attach to the string to the token so we can return it
  227. token.value = string;
  228. return token;
  229. }
  230. /**
  231. * Attempts to read a number from the input string. Places
  232. * the character location at the first character after the
  233. * number.
  234. *
  235. * @return The JSONToken with the number value if a number could
  236. * be read. Throws an error otherwise.
  237. */
  238. private function readNumber():JSONToken {
  239. // the token for the number we'll try to read
  240. var token:JSONToken = new JSONToken();
  241. token.type = JSONTokenType.NUMBER;
  242. // the string to accumulate the number characters
  243. // into that we'll convert to a number at the end
  244. var input:String = "";
  245. // check for a negative number
  246. if ( ch == '-' ) {
  247. input += '-';
  248. nextChar();
  249. }
  250. // the number must start with a digit
  251. if ( !isDigit( ch ) )
  252. {
  253. parseError( "Expecting a digit" );
  254. }
  255. // 0 can only be the first digit if it
  256. // is followed by a decimal point
  257. if ( ch == '0' )
  258. {
  259. input += ch;
  260. nextChar();
  261. // make sure no other digits come after 0
  262. if ( isDigit( ch ) )
  263. {
  264. parseError( "A digit cannot immediately follow 0" );
  265. }
  266. }
  267. else
  268. {
  269. // read numbers while we can
  270. while ( isDigit( ch ) ) {
  271. input += ch;
  272. nextChar();
  273. }
  274. }
  275. // check for a decimal value
  276. if ( ch == '.' ) {
  277. input += '.';
  278. nextChar();
  279. // after the decimal there has to be a digit
  280. if ( !isDigit( ch ) )
  281. {
  282. parseError( "Expecting a digit" );
  283. }
  284. // read more numbers to get the decimal value
  285. while ( isDigit( ch ) ) {
  286. input += ch;
  287. nextChar();
  288. }
  289. }
  290. // check for scientific notation
  291. if ( ch == 'e' || ch == 'E' )
  292. {
  293. input += "e"
  294. nextChar();
  295. // check for sign
  296. if ( ch == '+' || ch == '-' )
  297. {
  298. input += ch;
  299. nextChar();
  300. }
  301. // require at least one number for the exponent
  302. // in this case
  303. if ( !isDigit( ch ) )
  304. {
  305. parseError( "Scientific notation number needs exponent value" );
  306. }
  307. // read in the exponent
  308. while ( isDigit( ch ) )
  309. {
  310. input += ch;
  311. nextChar();
  312. }
  313. }
  314. // convert the string to a number value
  315. var num:Number = Number( input );
  316. if ( isFinite( num ) && !isNaN( num ) ) {
  317. token.value = num;
  318. return token;
  319. } else {
  320. parseError( "Number " + num + " is not valid!" );
  321. }
  322. return null;
  323. }
  324. /**
  325. * Reads the next character in the input
  326. * string and advances the character location.
  327. *
  328. * @return The next character in the input string, or
  329. * null if we've read past the end.
  330. */
  331. private function nextChar():String {
  332. return ch = jsonString.charAt( loc++ );
  333. }
  334. /**
  335. * Advances the character location past any
  336. * sort of white space and comments
  337. */
  338. private function skipIgnored():void {
  339. skipWhite();
  340. skipComments();
  341. skipWhite();
  342. }
  343. /**
  344. * Skips comments in the input string, either
  345. * single-line or multi-line. Advances the character
  346. * to the first position after the end of the comment.
  347. */
  348. private function skipComments():void {
  349. if ( ch == '/' ) {
  350. // Advance past the first / to find out what type of comment
  351. nextChar();
  352. switch ( ch ) {
  353. case '/': // single-line comment, read through end of line
  354. // Loop over the characters until we find
  355. // a newline or until there's no more characters left
  356. do {
  357. nextChar();
  358. } while ( ch != '\n' && ch != '' )
  359. // move past the \n
  360. nextChar();
  361. break;
  362. case '*': // multi-line comment, read until closing */
  363. // move past the opening *
  364. nextChar();
  365. // try to find a trailing */
  366. while ( true ) {
  367. if ( ch == '*' ) {
  368. // check to see if we have a closing /
  369. nextChar();
  370. if ( ch == '/') {
  371. // move past the end of the closing */
  372. nextChar();
  373. break;
  374. }
  375. } else {
  376. // move along, looking if the next character is a *
  377. nextChar();
  378. }
  379. // when we're here we've read past the end of
  380. // the string without finding a closing */, so error
  381. if ( ch == '' ) {
  382. parseError( "Multi-line comment not closed" );
  383. }
  384. }
  385. break;
  386. // Can't match a comment after a /, so it's a parsing error
  387. default:
  388. parseError( "Unexpected " + ch + " encountered (expecting '/' or '*' )" );
  389. }
  390. }
  391. }
  392. /**
  393. * Skip any whitespace in the input string and advances
  394. * the character to the first character after any possible
  395. * whitespace.
  396. */
  397. private function skipWhite():void {
  398. // As long as there are spaces in the input
  399. // stream, advance the current location pointer
  400. // past them
  401. while ( isWhiteSpace( ch ) ) {
  402. nextChar();
  403. }
  404. }
  405. /**
  406. * Determines if a character is whitespace or not.
  407. *
  408. * @return True if the character passed in is a whitespace
  409. * character
  410. */
  411. private function isWhiteSpace( ch:String ):Boolean {
  412. return ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' );
  413. }
  414. /**
  415. * Determines if a character is a digit [0-9].
  416. *
  417. * @return True if the character passed in is a digit
  418. */
  419. private function isDigit( ch:String ):Boolean {
  420. return ( ch >= '0' && ch <= '9' );
  421. }
  422. /**
  423. * Determines if a character is a digit [0-9].
  424. *
  425. * @return True if the character passed in is a digit
  426. */
  427. private function isHexDigit( ch:String ):Boolean {
  428. // get the uppercase value of ch so we only have
  429. // to compare the value between 'A' and 'F'
  430. var uc:String = ch.toUpperCase();
  431. // a hex digit is a digit of A-F, inclusive ( using
  432. // our uppercase constraint )
  433. return ( isDigit( ch ) || ( uc >= 'A' && uc <= 'F' ) );
  434. }
  435. /**
  436. * Raises a parsing error with a specified message, tacking
  437. * on the error location and the original string.
  438. *
  439. * @param message The message indicating why the error occurred
  440. */
  441. public function parseError( message:String ):void {
  442. throw new JSONParseError( message, loc, jsonString );
  443. }
  444. }
  445. }