jsonparse.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*global Buffer*/
  2. // Named constants with unique integer values
  3. var C = {};
  4. // Tokens
  5. var LEFT_BRACE = C.LEFT_BRACE = 0x1;
  6. var RIGHT_BRACE = C.RIGHT_BRACE = 0x2;
  7. var LEFT_BRACKET = C.LEFT_BRACKET = 0x3;
  8. var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4;
  9. var COLON = C.COLON = 0x5;
  10. var COMMA = C.COMMA = 0x6;
  11. var TRUE = C.TRUE = 0x7;
  12. var FALSE = C.FALSE = 0x8;
  13. var NULL = C.NULL = 0x9;
  14. var STRING = C.STRING = 0xa;
  15. var NUMBER = C.NUMBER = 0xb;
  16. // Tokenizer States
  17. var START = C.START = 0x11;
  18. var STOP = C.STOP = 0x12;
  19. var TRUE1 = C.TRUE1 = 0x21;
  20. var TRUE2 = C.TRUE2 = 0x22;
  21. var TRUE3 = C.TRUE3 = 0x23;
  22. var FALSE1 = C.FALSE1 = 0x31;
  23. var FALSE2 = C.FALSE2 = 0x32;
  24. var FALSE3 = C.FALSE3 = 0x33;
  25. var FALSE4 = C.FALSE4 = 0x34;
  26. var NULL1 = C.NULL1 = 0x41;
  27. var NULL2 = C.NULL2 = 0x42;
  28. var NULL3 = C.NULL3 = 0x43;
  29. var NUMBER1 = C.NUMBER1 = 0x51;
  30. var NUMBER3 = C.NUMBER3 = 0x53;
  31. var STRING1 = C.STRING1 = 0x61;
  32. var STRING2 = C.STRING2 = 0x62;
  33. var STRING3 = C.STRING3 = 0x63;
  34. var STRING4 = C.STRING4 = 0x64;
  35. var STRING5 = C.STRING5 = 0x65;
  36. var STRING6 = C.STRING6 = 0x66;
  37. // Parser States
  38. var VALUE = C.VALUE = 0x71;
  39. var KEY = C.KEY = 0x72;
  40. // Parser Modes
  41. var OBJECT = C.OBJECT = 0x81;
  42. var ARRAY = C.ARRAY = 0x82;
  43. // Character constants
  44. var BACK_SLASH = "\\".charCodeAt(0);
  45. var FORWARD_SLASH = "\/".charCodeAt(0);
  46. var BACKSPACE = "\b".charCodeAt(0);
  47. var FORM_FEED = "\f".charCodeAt(0);
  48. var NEWLINE = "\n".charCodeAt(0);
  49. var CARRIAGE_RETURN = "\r".charCodeAt(0);
  50. var TAB = "\t".charCodeAt(0);
  51. var STRING_BUFFER_SIZE = 64 * 1024;
  52. function Parser() {
  53. this.tState = START;
  54. this.value = undefined;
  55. this.string = undefined; // string data
  56. this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE);
  57. this.stringBufferOffset = 0;
  58. this.unicode = undefined; // unicode escapes
  59. this.highSurrogate = undefined;
  60. this.key = undefined;
  61. this.mode = undefined;
  62. this.stack = [];
  63. this.state = VALUE;
  64. this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary
  65. this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read
  66. this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached
  67. // Stream offset
  68. this.offset = -1;
  69. }
  70. // Slow code to string converter (only used when throwing syntax errors)
  71. Parser.toknam = function (code) {
  72. var keys = Object.keys(C);
  73. for (var i = 0, l = keys.length; i < l; i++) {
  74. var key = keys[i];
  75. if (C[key] === code) { return key; }
  76. }
  77. return code && ("0x" + code.toString(16));
  78. };
  79. var proto = Parser.prototype;
  80. proto.onError = function (err) { throw err; };
  81. proto.charError = function (buffer, i) {
  82. this.tState = STOP;
  83. this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState)));
  84. };
  85. proto.appendStringChar = function (char) {
  86. if (this.stringBufferOffset >= STRING_BUFFER_SIZE) {
  87. this.string += this.stringBuffer.toString('utf8');
  88. this.stringBufferOffset = 0;
  89. }
  90. this.stringBuffer[this.stringBufferOffset++] = char;
  91. };
  92. proto.appendStringBuf = function (buf, start, end) {
  93. var size = buf.length;
  94. if (typeof start === 'number') {
  95. if (typeof end === 'number') {
  96. if (end < 0) {
  97. // adding a negative end decreeses the size
  98. size = buf.length - start + end;
  99. } else {
  100. size = end - start;
  101. }
  102. } else {
  103. size = buf.length - start;
  104. }
  105. }
  106. if (size < 0) {
  107. size = 0;
  108. }
  109. if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) {
  110. this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
  111. this.stringBufferOffset = 0;
  112. }
  113. buf.copy(this.stringBuffer, this.stringBufferOffset, start, end);
  114. this.stringBufferOffset += size;
  115. };
  116. proto.write = function (buffer) {
  117. if (typeof buffer === "string") buffer = new Buffer(buffer);
  118. var n;
  119. for (var i = 0, l = buffer.length; i < l; i++) {
  120. if (this.tState === START){
  121. n = buffer[i];
  122. this.offset++;
  123. if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // {
  124. }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // }
  125. }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [
  126. }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ]
  127. }else if(n === 0x3a){ this.onToken(COLON, ":"); // :
  128. }else if(n === 0x2c){ this.onToken(COMMA, ","); // ,
  129. }else if(n === 0x74){ this.tState = TRUE1; // t
  130. }else if(n === 0x66){ this.tState = FALSE1; // f
  131. }else if(n === 0x6e){ this.tState = NULL1; // n
  132. }else if(n === 0x22){ // "
  133. this.string = "";
  134. this.stringBufferOffset = 0;
  135. this.tState = STRING1;
  136. }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // -
  137. }else{
  138. if (n >= 0x30 && n < 0x40) { // 1-9
  139. this.string = String.fromCharCode(n); this.tState = NUMBER3;
  140. } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) {
  141. // whitespace
  142. } else {
  143. return this.charError(buffer, i);
  144. }
  145. }
  146. }else if (this.tState === STRING1){ // After open quote
  147. n = buffer[i]; // get current byte from buffer
  148. // check for carry over of a multi byte char split between data chunks
  149. // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration
  150. if (this.bytes_remaining > 0) {
  151. for (var j = 0; j < this.bytes_remaining; j++) {
  152. this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];
  153. }
  154. this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]);
  155. this.bytes_in_sequence = this.bytes_remaining = 0;
  156. i = i + j - 1;
  157. } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time
  158. if (n <= 193 || n > 244) {
  159. return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState)));
  160. }
  161. if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;
  162. if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;
  163. if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;
  164. if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split
  165. for (var k = 0; k <= (buffer.length - 1 - i); k++) {
  166. this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk
  167. }
  168. this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;
  169. i = buffer.length - 1;
  170. } else {
  171. this.appendStringBuf(buffer, i, i + this.bytes_in_sequence);
  172. i = i + this.bytes_in_sequence - 1;
  173. }
  174. } else if (n === 0x22) {
  175. this.tState = START;
  176. this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
  177. this.stringBufferOffset = 0;
  178. this.onToken(STRING, this.string);
  179. this.offset += Buffer.byteLength(this.string, 'utf8') + 1;
  180. this.string = undefined;
  181. }
  182. else if (n === 0x5c) {
  183. this.tState = STRING2;
  184. }
  185. else if (n >= 0x20) { this.appendStringChar(n); }
  186. else {
  187. return this.charError(buffer, i);
  188. }
  189. }else if (this.tState === STRING2){ // After backslash
  190. n = buffer[i];
  191. if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1;
  192. }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1;
  193. }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1;
  194. }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1;
  195. }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1;
  196. }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1;
  197. }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1;
  198. }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1;
  199. }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3;
  200. }else{
  201. return this.charError(buffer, i);
  202. }
  203. }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes
  204. n = buffer[i];
  205. // 0-9 A-F a-f
  206. if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {
  207. this.unicode += String.fromCharCode(n);
  208. if (this.tState++ === STRING6) {
  209. var intVal = parseInt(this.unicode, 16);
  210. this.unicode = undefined;
  211. if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate
  212. this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal)));
  213. this.highSurrogate = undefined;
  214. } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate
  215. this.highSurrogate = intVal;
  216. } else {
  217. if (this.highSurrogate !== undefined) {
  218. this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate)));
  219. this.highSurrogate = undefined;
  220. }
  221. this.appendStringBuf(new Buffer(String.fromCharCode(intVal)));
  222. }
  223. this.tState = STRING1;
  224. }
  225. } else {
  226. return this.charError(buffer, i);
  227. }
  228. } else if (this.tState === NUMBER1 || this.tState === NUMBER3) {
  229. n = buffer[i];
  230. switch (n) {
  231. case 0x30: // 0
  232. case 0x31: // 1
  233. case 0x32: // 2
  234. case 0x33: // 3
  235. case 0x34: // 4
  236. case 0x35: // 5
  237. case 0x36: // 6
  238. case 0x37: // 7
  239. case 0x38: // 8
  240. case 0x39: // 9
  241. case 0x2e: // .
  242. case 0x65: // e
  243. case 0x45: // E
  244. case 0x2b: // +
  245. case 0x2d: // -
  246. this.string += String.fromCharCode(n);
  247. this.tState = NUMBER3;
  248. break;
  249. default:
  250. this.tState = START;
  251. var result = Number(this.string);
  252. if (isNaN(result)){
  253. return this.charError(buffer, i);
  254. }
  255. if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) {
  256. // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number
  257. this.onToken(STRING, this.string);
  258. } else {
  259. this.onToken(NUMBER, result);
  260. }
  261. this.offset += this.string.length - 1;
  262. this.string = undefined;
  263. i--;
  264. break;
  265. }
  266. }else if (this.tState === TRUE1){ // r
  267. if (buffer[i] === 0x72) { this.tState = TRUE2; }
  268. else { return this.charError(buffer, i); }
  269. }else if (this.tState === TRUE2){ // u
  270. if (buffer[i] === 0x75) { this.tState = TRUE3; }
  271. else { return this.charError(buffer, i); }
  272. }else if (this.tState === TRUE3){ // e
  273. if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; }
  274. else { return this.charError(buffer, i); }
  275. }else if (this.tState === FALSE1){ // a
  276. if (buffer[i] === 0x61) { this.tState = FALSE2; }
  277. else { return this.charError(buffer, i); }
  278. }else if (this.tState === FALSE2){ // l
  279. if (buffer[i] === 0x6c) { this.tState = FALSE3; }
  280. else { return this.charError(buffer, i); }
  281. }else if (this.tState === FALSE3){ // s
  282. if (buffer[i] === 0x73) { this.tState = FALSE4; }
  283. else { return this.charError(buffer, i); }
  284. }else if (this.tState === FALSE4){ // e
  285. if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; }
  286. else { return this.charError(buffer, i); }
  287. }else if (this.tState === NULL1){ // u
  288. if (buffer[i] === 0x75) { this.tState = NULL2; }
  289. else { return this.charError(buffer, i); }
  290. }else if (this.tState === NULL2){ // l
  291. if (buffer[i] === 0x6c) { this.tState = NULL3; }
  292. else { return this.charError(buffer, i); }
  293. }else if (this.tState === NULL3){ // l
  294. if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; }
  295. else { return this.charError(buffer, i); }
  296. }
  297. }
  298. };
  299. proto.onToken = function (token, value) {
  300. // Override this to get events
  301. };
  302. proto.parseError = function (token, value) {
  303. this.tState = STOP;
  304. this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state)));
  305. };
  306. proto.push = function () {
  307. this.stack.push({value: this.value, key: this.key, mode: this.mode});
  308. };
  309. proto.pop = function () {
  310. var value = this.value;
  311. var parent = this.stack.pop();
  312. this.value = parent.value;
  313. this.key = parent.key;
  314. this.mode = parent.mode;
  315. this.emit(value);
  316. if (!this.mode) { this.state = VALUE; }
  317. };
  318. proto.emit = function (value) {
  319. if (this.mode) { this.state = COMMA; }
  320. this.onValue(value);
  321. };
  322. proto.onValue = function (value) {
  323. // Override me
  324. };
  325. proto.onToken = function (token, value) {
  326. if(this.state === VALUE){
  327. if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){
  328. if (this.value) {
  329. this.value[this.key] = value;
  330. }
  331. this.emit(value);
  332. }else if(token === LEFT_BRACE){
  333. this.push();
  334. if (this.value) {
  335. this.value = this.value[this.key] = {};
  336. } else {
  337. this.value = {};
  338. }
  339. this.key = undefined;
  340. this.state = KEY;
  341. this.mode = OBJECT;
  342. }else if(token === LEFT_BRACKET){
  343. this.push();
  344. if (this.value) {
  345. this.value = this.value[this.key] = [];
  346. } else {
  347. this.value = [];
  348. }
  349. this.key = 0;
  350. this.mode = ARRAY;
  351. this.state = VALUE;
  352. }else if(token === RIGHT_BRACE){
  353. if (this.mode === OBJECT) {
  354. this.pop();
  355. } else {
  356. return this.parseError(token, value);
  357. }
  358. }else if(token === RIGHT_BRACKET){
  359. if (this.mode === ARRAY) {
  360. this.pop();
  361. } else {
  362. return this.parseError(token, value);
  363. }
  364. }else{
  365. return this.parseError(token, value);
  366. }
  367. }else if(this.state === KEY){
  368. if (token === STRING) {
  369. this.key = value;
  370. this.state = COLON;
  371. } else if (token === RIGHT_BRACE) {
  372. this.pop();
  373. } else {
  374. return this.parseError(token, value);
  375. }
  376. }else if(this.state === COLON){
  377. if (token === COLON) { this.state = VALUE; }
  378. else { return this.parseError(token, value); }
  379. }else if(this.state === COMMA){
  380. if (token === COMMA) {
  381. if (this.mode === ARRAY) { this.key++; this.state = VALUE; }
  382. else if (this.mode === OBJECT) { this.state = KEY; }
  383. } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) {
  384. this.pop();
  385. } else {
  386. return this.parseError(token, value);
  387. }
  388. }else{
  389. return this.parseError(token, value);
  390. }
  391. };
  392. Parser.C = C;
  393. module.exports = Parser;