jsonstreamparser.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. // Copyright 2015 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview the default JSON stream parser.
  16. *
  17. * The default JSON parser decodes the input stream (string) under the
  18. * following rules:
  19. * 1. The stream represents a valid JSON array (must start with a "[" and close
  20. * with the corresponding "]"). Each element of this array is assumed to be
  21. * either an array or an object, and will be decoded as a JS object and
  22. * delivered. Compact array format that is not valid JSON is also supported,
  23. * e.g. [1,,2].
  24. * 2. All JSON elements in the buffer will be decoded and delivered in a batch.
  25. * 3. If a high-level API does not support batch delivery (e.g. grpc), then
  26. * a wrapper is expected to deliver individual elements separately
  27. * and in order.
  28. * 4. The parser is expected to drop any data (without breaking the
  29. * specified MIME format) that is not visible to the client: e.g. new lines
  30. * for pretty printing; no-op data for keep-alive support.
  31. * 5. Fail-fast: any invalid content should abort the stream by setting the
  32. * state of the parser to "invalid".
  33. *
  34. * The parser is a streamed JSON parser and is optimized in such a way
  35. * that it only scans the message boundary and the actual decoding of JSON
  36. * strings and construction of JS object are done by JSON.parse (native
  37. * code).
  38. */
  39. goog.provide('goog.net.streams.JsonStreamParser');
  40. goog.provide('goog.net.streams.JsonStreamParser.Options');
  41. goog.require('goog.asserts');
  42. goog.require('goog.json');
  43. goog.require('goog.net.streams.StreamParser');
  44. goog.require('goog.net.streams.utils');
  45. goog.scope(function() {
  46. var utils = goog.module.get('goog.net.streams.utils');
  47. /**
  48. * The default JSON stream parser.
  49. *
  50. * @param {!goog.net.streams.JsonStreamParser.Options=} opt_options
  51. * Configuration for the new JsonStreamParser instance.
  52. * @constructor
  53. * @struct
  54. * @implements {goog.net.streams.StreamParser}
  55. * @final
  56. * @package
  57. */
  58. goog.net.streams.JsonStreamParser = function(opt_options) {
  59. /**
  60. * The current error message, if any.
  61. * @private {?string}
  62. */
  63. this.errorMessage_ = null;
  64. /**
  65. * The currently buffered result (parsed JSON objects).
  66. * @private {!Array<string|!Object>}
  67. */
  68. this.result_ = [];
  69. /**
  70. * The currently buffered input.
  71. * @private {string}
  72. */
  73. this.buffer_ = '';
  74. /**
  75. * The current stack.
  76. * @private {!Array<!Parser.State_>}
  77. */
  78. this.stack_ = [];
  79. /**
  80. * The current depth of the nested JSON structure.
  81. * @private {number}
  82. */
  83. this.depth_ = 0;
  84. /**
  85. * The current position in the streamed data.
  86. * @private {number}
  87. */
  88. this.pos_ = 0;
  89. /**
  90. * The current state of whether the parser is decoding a '\' escaped string.
  91. * @private {boolean}
  92. */
  93. this.slashed_ = false;
  94. /**
  95. * The current unicode char count. 0 means no unicode, 1-4 otherwise.
  96. * @private {number}
  97. */
  98. this.unicodeCount_ = 0;
  99. /**
  100. * The regexp for parsing string input.
  101. * @private {!RegExp}
  102. */
  103. this.stringInputPattern_ = /[\\"]/g;
  104. /**
  105. * The current stream state.
  106. * @private {goog.net.streams.JsonStreamParser.StreamState_}
  107. */
  108. this.streamState_ = Parser.StreamState_.INIT;
  109. /**
  110. * The current parser state.
  111. * @private {goog.net.streams.JsonStreamParser.State_}
  112. */
  113. this.state_ = Parser.State_.INIT;
  114. /**
  115. * Whether allows compact JSON array format, e.g. "[1, ,2]".
  116. * @private {boolean}
  117. */
  118. this.allowCompactJsonArrayFormat_ =
  119. !!(opt_options && opt_options.allowCompactJsonArrayFormat);
  120. /**
  121. * Whether to deliver the raw message string without decoding into JS object.
  122. * @private {boolean}
  123. */
  124. this.deliverMessageAsRawString_ =
  125. !!(opt_options && opt_options.deliverMessageAsRawString);
  126. };
  127. /**
  128. * Configuration spec for newly created JSON stream parser:
  129. *
  130. * allowCompactJsonArrayFormat: whether allows compact JSON array format, where
  131. * null is represented as empty string, e.g. "[1, ,2]".
  132. *
  133. * deliverMessageAsRawString: whether to deliver the raw message string without
  134. * decoding into JS object. Semantically insignificant whitespaces in the
  135. * input may be kept or ignored.
  136. *
  137. * @typedef {{
  138. * allowCompactJsonArrayFormat: (boolean|undefined),
  139. * deliverMessageAsRawString: (boolean|undefined),
  140. * }}
  141. */
  142. goog.net.streams.JsonStreamParser.Options;
  143. var Parser = goog.net.streams.JsonStreamParser;
  144. /**
  145. * The stream state.
  146. * @private @enum {number}
  147. */
  148. Parser.StreamState_ = {
  149. INIT: 0,
  150. ARRAY_OPEN: 1,
  151. ARRAY_END: 2,
  152. INVALID: 3
  153. };
  154. /**
  155. * The parser state.
  156. * @private @enum {number}
  157. */
  158. Parser.State_ = {
  159. INIT: 0,
  160. VALUE: 1,
  161. OBJECT_OPEN: 2,
  162. OBJECT_END: 3,
  163. ARRAY_OPEN: 4,
  164. ARRAY_END: 5,
  165. STRING: 6,
  166. KEY_START: 7,
  167. KEY_END: 8,
  168. TRUE1: 9, // T and expecting RUE ...
  169. TRUE2: 10,
  170. TRUE3: 11,
  171. FALSE1: 12, // F and expecting ALSE ...
  172. FALSE2: 13,
  173. FALSE3: 14,
  174. FALSE4: 15,
  175. NULL1: 16, // N and expecting ULL ...
  176. NULL2: 17,
  177. NULL3: 18,
  178. NUM_DECIMAL_POINT: 19,
  179. NUM_DIGIT: 20
  180. };
  181. /**
  182. * @override
  183. */
  184. Parser.prototype.isInputValid = function() {
  185. return this.streamState_ != Parser.StreamState_.INVALID;
  186. };
  187. /**
  188. * @override
  189. */
  190. Parser.prototype.getErrorMessage = function() {
  191. return this.errorMessage_;
  192. };
  193. /**
  194. * @return {boolean} Whether the parser has reached the end of the stream
  195. *
  196. * TODO(updogliu): move this API to the base type.
  197. */
  198. Parser.prototype.done = function() {
  199. return this.streamState_ === Parser.StreamState_.ARRAY_END;
  200. };
  201. /**
  202. * Get the part of input that is after the end of the stream. Call this only
  203. * when {@code this.done()} is true.
  204. *
  205. * @return {string} The extra input
  206. *
  207. * TODO(updogliu): move this API to the base type.
  208. */
  209. Parser.prototype.getExtraInput = function() {
  210. return this.buffer_;
  211. };
  212. /**
  213. * @param {string|!ArrayBuffer|!Array<number>} input
  214. * The current input string (always)
  215. * @param {number} pos The position in the current input that triggers the error
  216. * @throws {!Error} Throws an error indicating where the stream is broken
  217. * @private
  218. */
  219. Parser.prototype.error_ = function(input, pos) {
  220. this.streamState_ = Parser.StreamState_.INVALID;
  221. this.errorMessage_ = 'The stream is broken @' + this.pos_ + '/' + pos +
  222. '. With input:\n' + input;
  223. throw Error(this.errorMessage_);
  224. };
  225. /**
  226. * @throws {Error} Throws an error message if the input is invalid.
  227. * @override
  228. */
  229. Parser.prototype.parse = function(input) {
  230. goog.asserts.assertString(input);
  231. // captures
  232. var parser = this;
  233. var stack = parser.stack_;
  234. var pattern = parser.stringInputPattern_;
  235. var State = Parser.State_; // enums
  236. var num = input.length;
  237. var streamStart = 0;
  238. var msgStart = -1;
  239. var i = 0;
  240. while (i < num) {
  241. switch (parser.streamState_) {
  242. case Parser.StreamState_.INVALID:
  243. parser.error_(input, i);
  244. return null;
  245. case Parser.StreamState_.ARRAY_END:
  246. if (readMore()) {
  247. parser.error_(input, i);
  248. }
  249. return null;
  250. case Parser.StreamState_.INIT:
  251. if (readMore()) {
  252. var current = input[i++];
  253. parser.pos_++;
  254. if (current === '[') {
  255. parser.streamState_ = Parser.StreamState_.ARRAY_OPEN;
  256. streamStart = i;
  257. parser.state_ = State.ARRAY_OPEN;
  258. continue;
  259. } else {
  260. parser.error_(input, i);
  261. }
  262. }
  263. return null;
  264. case Parser.StreamState_.ARRAY_OPEN:
  265. parseData();
  266. if (parser.depth_ === 0 && parser.state_ == State.ARRAY_END) {
  267. parser.streamState_ = Parser.StreamState_.ARRAY_END;
  268. parser.buffer_ = input.substring(i);
  269. } else {
  270. if (msgStart === -1) {
  271. parser.buffer_ += input.substring(streamStart);
  272. } else {
  273. parser.buffer_ = input.substring(msgStart);
  274. }
  275. }
  276. if (parser.result_.length > 0) {
  277. var msgs = parser.result_;
  278. parser.result_ = [];
  279. return msgs;
  280. }
  281. return null;
  282. }
  283. }
  284. return null;
  285. /**
  286. * @return {boolean} true if the parser needs parse more data
  287. */
  288. function readMore() {
  289. skipWhitespace();
  290. return i < num;
  291. }
  292. /**
  293. * Skip as many whitespaces as possible, and increments current index of
  294. * stream to next available char.
  295. */
  296. function skipWhitespace() {
  297. while (i < input.length) {
  298. if (utils.isJsonWhitespace(input[i])) {
  299. i++;
  300. parser.pos_++;
  301. continue;
  302. }
  303. break;
  304. }
  305. }
  306. /**
  307. * Parse the input JSON elements with a streamed state machine.
  308. */
  309. function parseData() {
  310. var current;
  311. while (true) {
  312. current = input[i++];
  313. if (!current) {
  314. break;
  315. }
  316. parser.pos_++;
  317. switch (parser.state_) {
  318. case State.INIT:
  319. if (current === '{') {
  320. parser.state_ = State.OBJECT_OPEN;
  321. } else if (current === '[') {
  322. parser.state_ = State.ARRAY_OPEN;
  323. } else if (!utils.isJsonWhitespace(current)) {
  324. parser.error_(input, i);
  325. }
  326. continue;
  327. case State.KEY_START:
  328. case State.OBJECT_OPEN:
  329. if (utils.isJsonWhitespace(current)) {
  330. continue;
  331. }
  332. if (parser.state_ === State.KEY_START) {
  333. stack.push(State.KEY_END);
  334. } else {
  335. if (current === '}') {
  336. addMessage('{}');
  337. parser.state_ = nextState();
  338. continue;
  339. } else {
  340. stack.push(State.OBJECT_END);
  341. }
  342. }
  343. if (current === '"') {
  344. parser.state_ = State.STRING;
  345. } else {
  346. parser.error_(input, i);
  347. }
  348. continue;
  349. case State.KEY_END:
  350. case State.OBJECT_END:
  351. if (utils.isJsonWhitespace(current)) {
  352. continue;
  353. }
  354. if (current === ':') {
  355. if (parser.state_ === State.OBJECT_END) {
  356. stack.push(State.OBJECT_END);
  357. parser.depth_++;
  358. }
  359. parser.state_ = State.VALUE;
  360. } else if (current === '}') {
  361. parser.depth_--;
  362. addMessage();
  363. parser.state_ = nextState();
  364. } else if (current === ',') {
  365. if (parser.state_ === State.OBJECT_END) {
  366. stack.push(State.OBJECT_END);
  367. }
  368. parser.state_ = State.KEY_START;
  369. } else {
  370. parser.error_(input, i);
  371. }
  372. continue;
  373. case State.ARRAY_OPEN:
  374. case State.VALUE:
  375. if (utils.isJsonWhitespace(current)) {
  376. continue;
  377. }
  378. if (parser.state_ === State.ARRAY_OPEN) {
  379. parser.depth_++;
  380. parser.state_ = State.VALUE;
  381. if (current === ']') {
  382. parser.depth_--;
  383. if (parser.depth_ === 0) {
  384. parser.state_ = State.ARRAY_END;
  385. return;
  386. }
  387. addMessage('[]');
  388. parser.state_ = nextState();
  389. continue;
  390. } else {
  391. stack.push(State.ARRAY_END);
  392. }
  393. }
  394. if (current === '"')
  395. parser.state_ = State.STRING;
  396. else if (current === '{')
  397. parser.state_ = State.OBJECT_OPEN;
  398. else if (current === '[')
  399. parser.state_ = State.ARRAY_OPEN;
  400. else if (current === 't')
  401. parser.state_ = State.TRUE1;
  402. else if (current === 'f')
  403. parser.state_ = State.FALSE1;
  404. else if (current === 'n')
  405. parser.state_ = State.NULL1;
  406. else if (current === '-') {
  407. // continue
  408. } else if ('0123456789'.indexOf(current) !== -1) {
  409. parser.state_ = State.NUM_DIGIT;
  410. } else if (current === ',' && parser.allowCompactJsonArrayFormat_) {
  411. parser.state_ = State.VALUE;
  412. } else if (current === ']' && parser.allowCompactJsonArrayFormat_) {
  413. i--;
  414. parser.pos_--;
  415. parser.state_ = nextState();
  416. } else {
  417. parser.error_(input, i);
  418. }
  419. continue;
  420. case State.ARRAY_END:
  421. if (current === ',') {
  422. stack.push(State.ARRAY_END);
  423. parser.state_ = State.VALUE;
  424. if (parser.depth_ === 1) {
  425. msgStart = i; // skip ',', including a leading one
  426. }
  427. } else if (current === ']') {
  428. parser.depth_--;
  429. if (parser.depth_ === 0) {
  430. return;
  431. }
  432. addMessage();
  433. parser.state_ = nextState();
  434. } else if (utils.isJsonWhitespace(current)) {
  435. continue;
  436. } else {
  437. parser.error_(input, i);
  438. }
  439. continue;
  440. case State.STRING:
  441. var old = i;
  442. STRING_LOOP: while (true) {
  443. while (parser.unicodeCount_ > 0) {
  444. current = input[i++];
  445. if (parser.unicodeCount_ === 4) {
  446. parser.unicodeCount_ = 0;
  447. } else {
  448. parser.unicodeCount_++;
  449. }
  450. if (!current) {
  451. break STRING_LOOP;
  452. }
  453. }
  454. if (current === '"' && !parser.slashed_) {
  455. parser.state_ = nextState();
  456. break;
  457. }
  458. if (current === '\\' && !parser.slashed_) {
  459. parser.slashed_ = true;
  460. current = input[i++];
  461. if (!current) {
  462. break;
  463. }
  464. }
  465. if (parser.slashed_) {
  466. parser.slashed_ = false;
  467. if (current === 'u') {
  468. parser.unicodeCount_ = 1;
  469. }
  470. current = input[i++];
  471. if (!current) {
  472. break;
  473. } else {
  474. continue;
  475. }
  476. }
  477. pattern.lastIndex = i;
  478. var patternResult = pattern.exec(input);
  479. if (!patternResult) {
  480. i = input.length + 1;
  481. break;
  482. }
  483. i = patternResult.index + 1;
  484. current = input[patternResult.index];
  485. if (!current) {
  486. break;
  487. }
  488. }
  489. parser.pos_ += (i - old);
  490. continue;
  491. case State.TRUE1:
  492. if (!current) {
  493. continue;
  494. }
  495. if (current === 'r') {
  496. parser.state_ = State.TRUE2;
  497. } else {
  498. parser.error_(input, i);
  499. }
  500. continue;
  501. case State.TRUE2:
  502. if (!current) {
  503. continue;
  504. }
  505. if (current === 'u') {
  506. parser.state_ = State.TRUE3;
  507. } else {
  508. parser.error_(input, i);
  509. }
  510. continue;
  511. case State.TRUE3:
  512. if (!current) {
  513. continue;
  514. }
  515. if (current === 'e') {
  516. parser.state_ = nextState();
  517. } else {
  518. parser.error_(input, i);
  519. }
  520. continue;
  521. case State.FALSE1:
  522. if (!current) {
  523. continue;
  524. }
  525. if (current === 'a') {
  526. parser.state_ = State.FALSE2;
  527. } else {
  528. parser.error_(input, i);
  529. }
  530. continue;
  531. case State.FALSE2:
  532. if (!current) {
  533. continue;
  534. }
  535. if (current === 'l') {
  536. parser.state_ = State.FALSE3;
  537. } else {
  538. parser.error_(input, i);
  539. }
  540. continue;
  541. case State.FALSE3:
  542. if (!current) {
  543. continue;
  544. }
  545. if (current === 's') {
  546. parser.state_ = State.FALSE4;
  547. } else {
  548. parser.error_(input, i);
  549. }
  550. continue;
  551. case State.FALSE4:
  552. if (!current) {
  553. continue;
  554. }
  555. if (current === 'e') {
  556. parser.state_ = nextState();
  557. } else {
  558. parser.error_(input, i);
  559. }
  560. continue;
  561. case State.NULL1:
  562. if (!current) {
  563. continue;
  564. }
  565. if (current === 'u') {
  566. parser.state_ = State.NULL2;
  567. } else {
  568. parser.error_(input, i);
  569. }
  570. continue;
  571. case State.NULL2:
  572. if (!current) {
  573. continue;
  574. }
  575. if (current === 'l') {
  576. parser.state_ = State.NULL3;
  577. } else {
  578. parser.error_(input, i);
  579. }
  580. continue;
  581. case State.NULL3:
  582. if (!current) {
  583. continue;
  584. }
  585. if (current === 'l') {
  586. parser.state_ = nextState();
  587. } else {
  588. parser.error_(input, i);
  589. }
  590. continue;
  591. case State.NUM_DECIMAL_POINT:
  592. if (current === '.') {
  593. parser.state_ = State.NUM_DIGIT;
  594. } else {
  595. parser.error_(input, i);
  596. }
  597. continue;
  598. case State.NUM_DIGIT: // no need for a full validation here
  599. if ('0123456789.eE+-'.indexOf(current) !== -1) {
  600. continue;
  601. } else {
  602. i--;
  603. parser.pos_--;
  604. parser.state_ = nextState();
  605. }
  606. continue;
  607. default:
  608. parser.error_(input, i);
  609. }
  610. }
  611. }
  612. /**
  613. * @return {!goog.net.streams.JsonStreamParser.State_} the next state
  614. * from the stack, or the general VALUE state.
  615. */
  616. function nextState() {
  617. var state = stack.pop();
  618. if (state != null) {
  619. return state;
  620. } else {
  621. return State.VALUE;
  622. }
  623. }
  624. /**
  625. * @param {(string)=} opt_data The message to add
  626. */
  627. function addMessage(opt_data) {
  628. if (parser.depth_ > 1) {
  629. return;
  630. }
  631. goog.asserts.assert(opt_data !== ''); // '' not possible
  632. if (!opt_data) {
  633. if (msgStart === -1) {
  634. opt_data = parser.buffer_ + input.substring(streamStart, i);
  635. } else {
  636. opt_data = input.substring(msgStart, i);
  637. }
  638. }
  639. if (parser.deliverMessageAsRawString_) {
  640. parser.result_.push(opt_data);
  641. } else {
  642. parser.result_.push(
  643. goog.asserts.assertInstanceof(goog.json.parse(opt_data), Object));
  644. }
  645. msgStart = i;
  646. }
  647. };
  648. }); // goog.scope