jsep.cjs.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. 'use strict';
  2. /**
  3. * @implements {IHooks}
  4. */
  5. class Hooks {
  6. /**
  7. * @callback HookCallback
  8. * @this {*|Jsep} this
  9. * @param {Jsep} env
  10. * @returns: void
  11. */
  12. /**
  13. * Adds the given callback to the list of callbacks for the given hook.
  14. *
  15. * The callback will be invoked when the hook it is registered for is run.
  16. *
  17. * One callback function can be registered to multiple hooks and the same hook multiple times.
  18. *
  19. * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
  20. * @param {HookCallback|boolean} callback The callback function which is given environment variables.
  21. * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
  22. * @public
  23. */
  24. add(name, callback, first) {
  25. if (typeof arguments[0] != 'string') {
  26. // Multiple hook callbacks, keyed by name
  27. for (let name in arguments[0]) {
  28. this.add(name, arguments[0][name], arguments[1]);
  29. }
  30. }
  31. else {
  32. (Array.isArray(name) ? name : [name]).forEach(function (name) {
  33. this[name] = this[name] || [];
  34. if (callback) {
  35. this[name][first ? 'unshift' : 'push'](callback);
  36. }
  37. }, this);
  38. }
  39. }
  40. /**
  41. * Runs a hook invoking all registered callbacks with the given environment variables.
  42. *
  43. * Callbacks will be invoked synchronously and in the order in which they were registered.
  44. *
  45. * @param {string} name The name of the hook.
  46. * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
  47. * @public
  48. */
  49. run(name, env) {
  50. this[name] = this[name] || [];
  51. this[name].forEach(function (callback) {
  52. callback.call(env && env.context ? env.context : env, env);
  53. });
  54. }
  55. }
  56. /**
  57. * @implements {IPlugins}
  58. */
  59. class Plugins {
  60. constructor(jsep) {
  61. this.jsep = jsep;
  62. this.registered = {};
  63. }
  64. /**
  65. * @callback PluginSetup
  66. * @this {Jsep} jsep
  67. * @returns: void
  68. */
  69. /**
  70. * Adds the given plugin(s) to the registry
  71. *
  72. * @param {object} plugins
  73. * @param {string} plugins.name The name of the plugin
  74. * @param {PluginSetup} plugins.init The init function
  75. * @public
  76. */
  77. register(...plugins) {
  78. plugins.forEach((plugin) => {
  79. if (typeof plugin !== 'object' || !plugin.name || !plugin.init) {
  80. throw new Error('Invalid JSEP plugin format');
  81. }
  82. if (this.registered[plugin.name]) {
  83. // already registered. Ignore.
  84. return;
  85. }
  86. plugin.init(this.jsep);
  87. this.registered[plugin.name] = plugin;
  88. });
  89. }
  90. }
  91. // JavaScript Expression Parser (JSEP) 1.3.8
  92. class Jsep {
  93. /**
  94. * @returns {string}
  95. */
  96. static get version() {
  97. // To be filled in by the template
  98. return '1.3.8';
  99. }
  100. /**
  101. * @returns {string}
  102. */
  103. static toString() {
  104. return 'JavaScript Expression Parser (JSEP) v' + Jsep.version;
  105. };
  106. // ==================== CONFIG ================================
  107. /**
  108. * @method addUnaryOp
  109. * @param {string} op_name The name of the unary op to add
  110. * @returns {Jsep}
  111. */
  112. static addUnaryOp(op_name) {
  113. Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
  114. Jsep.unary_ops[op_name] = 1;
  115. return Jsep;
  116. }
  117. /**
  118. * @method jsep.addBinaryOp
  119. * @param {string} op_name The name of the binary op to add
  120. * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
  121. * @param {boolean} [isRightAssociative=false] whether operator is right-associative
  122. * @returns {Jsep}
  123. */
  124. static addBinaryOp(op_name, precedence, isRightAssociative) {
  125. Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
  126. Jsep.binary_ops[op_name] = precedence;
  127. if (isRightAssociative) {
  128. Jsep.right_associative.add(op_name);
  129. }
  130. else {
  131. Jsep.right_associative.delete(op_name);
  132. }
  133. return Jsep;
  134. }
  135. /**
  136. * @method addIdentifierChar
  137. * @param {string} char The additional character to treat as a valid part of an identifier
  138. * @returns {Jsep}
  139. */
  140. static addIdentifierChar(char) {
  141. Jsep.additional_identifier_chars.add(char);
  142. return Jsep;
  143. }
  144. /**
  145. * @method addLiteral
  146. * @param {string} literal_name The name of the literal to add
  147. * @param {*} literal_value The value of the literal
  148. * @returns {Jsep}
  149. */
  150. static addLiteral(literal_name, literal_value) {
  151. Jsep.literals[literal_name] = literal_value;
  152. return Jsep;
  153. }
  154. /**
  155. * @method removeUnaryOp
  156. * @param {string} op_name The name of the unary op to remove
  157. * @returns {Jsep}
  158. */
  159. static removeUnaryOp(op_name) {
  160. delete Jsep.unary_ops[op_name];
  161. if (op_name.length === Jsep.max_unop_len) {
  162. Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
  163. }
  164. return Jsep;
  165. }
  166. /**
  167. * @method removeAllUnaryOps
  168. * @returns {Jsep}
  169. */
  170. static removeAllUnaryOps() {
  171. Jsep.unary_ops = {};
  172. Jsep.max_unop_len = 0;
  173. return Jsep;
  174. }
  175. /**
  176. * @method removeIdentifierChar
  177. * @param {string} char The additional character to stop treating as a valid part of an identifier
  178. * @returns {Jsep}
  179. */
  180. static removeIdentifierChar(char) {
  181. Jsep.additional_identifier_chars.delete(char);
  182. return Jsep;
  183. }
  184. /**
  185. * @method removeBinaryOp
  186. * @param {string} op_name The name of the binary op to remove
  187. * @returns {Jsep}
  188. */
  189. static removeBinaryOp(op_name) {
  190. delete Jsep.binary_ops[op_name];
  191. if (op_name.length === Jsep.max_binop_len) {
  192. Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
  193. }
  194. Jsep.right_associative.delete(op_name);
  195. return Jsep;
  196. }
  197. /**
  198. * @method removeAllBinaryOps
  199. * @returns {Jsep}
  200. */
  201. static removeAllBinaryOps() {
  202. Jsep.binary_ops = {};
  203. Jsep.max_binop_len = 0;
  204. return Jsep;
  205. }
  206. /**
  207. * @method removeLiteral
  208. * @param {string} literal_name The name of the literal to remove
  209. * @returns {Jsep}
  210. */
  211. static removeLiteral(literal_name) {
  212. delete Jsep.literals[literal_name];
  213. return Jsep;
  214. }
  215. /**
  216. * @method removeAllLiterals
  217. * @returns {Jsep}
  218. */
  219. static removeAllLiterals() {
  220. Jsep.literals = {};
  221. return Jsep;
  222. }
  223. // ==================== END CONFIG ============================
  224. /**
  225. * @returns {string}
  226. */
  227. get char() {
  228. return this.expr.charAt(this.index);
  229. }
  230. /**
  231. * @returns {number}
  232. */
  233. get code() {
  234. return this.expr.charCodeAt(this.index);
  235. };
  236. /**
  237. * @param {string} expr a string with the passed in express
  238. * @returns Jsep
  239. */
  240. constructor(expr) {
  241. // `index` stores the character number we are currently at
  242. // All of the gobbles below will modify `index` as we move along
  243. this.expr = expr;
  244. this.index = 0;
  245. }
  246. /**
  247. * static top-level parser
  248. * @returns {jsep.Expression}
  249. */
  250. static parse(expr) {
  251. return (new Jsep(expr)).parse();
  252. }
  253. /**
  254. * Get the longest key length of any object
  255. * @param {object} obj
  256. * @returns {number}
  257. */
  258. static getMaxKeyLen(obj) {
  259. return Math.max(0, ...Object.keys(obj).map(k => k.length));
  260. }
  261. /**
  262. * `ch` is a character code in the next three functions
  263. * @param {number} ch
  264. * @returns {boolean}
  265. */
  266. static isDecimalDigit(ch) {
  267. return (ch >= 48 && ch <= 57); // 0...9
  268. }
  269. /**
  270. * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
  271. * @param {string} op_val
  272. * @returns {number}
  273. */
  274. static binaryPrecedence(op_val) {
  275. return Jsep.binary_ops[op_val] || 0;
  276. }
  277. /**
  278. * Looks for start of identifier
  279. * @param {number} ch
  280. * @returns {boolean}
  281. */
  282. static isIdentifierStart(ch) {
  283. return (ch >= 65 && ch <= 90) || // A...Z
  284. (ch >= 97 && ch <= 122) || // a...z
  285. (ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)]) || // any non-ASCII that is not an operator
  286. (Jsep.additional_identifier_chars.has(String.fromCharCode(ch))); // additional characters
  287. }
  288. /**
  289. * @param {number} ch
  290. * @returns {boolean}
  291. */
  292. static isIdentifierPart(ch) {
  293. return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
  294. }
  295. /**
  296. * throw error at index of the expression
  297. * @param {string} message
  298. * @throws
  299. */
  300. throwError(message) {
  301. const error = new Error(message + ' at character ' + this.index);
  302. error.index = this.index;
  303. error.description = message;
  304. throw error;
  305. }
  306. /**
  307. * Run a given hook
  308. * @param {string} name
  309. * @param {jsep.Expression|false} [node]
  310. * @returns {?jsep.Expression}
  311. */
  312. runHook(name, node) {
  313. if (Jsep.hooks[name]) {
  314. const env = { context: this, node };
  315. Jsep.hooks.run(name, env);
  316. return env.node;
  317. }
  318. return node;
  319. }
  320. /**
  321. * Runs a given hook until one returns a node
  322. * @param {string} name
  323. * @returns {?jsep.Expression}
  324. */
  325. searchHook(name) {
  326. if (Jsep.hooks[name]) {
  327. const env = { context: this };
  328. Jsep.hooks[name].find(function (callback) {
  329. callback.call(env.context, env);
  330. return env.node;
  331. });
  332. return env.node;
  333. }
  334. }
  335. /**
  336. * Push `index` up to the next non-space character
  337. */
  338. gobbleSpaces() {
  339. let ch = this.code;
  340. // Whitespace
  341. while (ch === Jsep.SPACE_CODE
  342. || ch === Jsep.TAB_CODE
  343. || ch === Jsep.LF_CODE
  344. || ch === Jsep.CR_CODE) {
  345. ch = this.expr.charCodeAt(++this.index);
  346. }
  347. this.runHook('gobble-spaces');
  348. }
  349. /**
  350. * Top-level method to parse all expressions and returns compound or single node
  351. * @returns {jsep.Expression}
  352. */
  353. parse() {
  354. this.runHook('before-all');
  355. const nodes = this.gobbleExpressions();
  356. // If there's only one expression just try returning the expression
  357. const node = nodes.length === 1
  358. ? nodes[0]
  359. : {
  360. type: Jsep.COMPOUND,
  361. body: nodes
  362. };
  363. return this.runHook('after-all', node);
  364. }
  365. /**
  366. * top-level parser (but can be reused within as well)
  367. * @param {number} [untilICode]
  368. * @returns {jsep.Expression[]}
  369. */
  370. gobbleExpressions(untilICode) {
  371. let nodes = [], ch_i, node;
  372. while (this.index < this.expr.length) {
  373. ch_i = this.code;
  374. // Expressions can be separated by semicolons, commas, or just inferred without any
  375. // separators
  376. if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
  377. this.index++; // ignore separators
  378. }
  379. else {
  380. // Try to gobble each expression individually
  381. if (node = this.gobbleExpression()) {
  382. nodes.push(node);
  383. // If we weren't able to find a binary expression and are out of room, then
  384. // the expression passed in probably has too much
  385. }
  386. else if (this.index < this.expr.length) {
  387. if (ch_i === untilICode) {
  388. break;
  389. }
  390. this.throwError('Unexpected "' + this.char + '"');
  391. }
  392. }
  393. }
  394. return nodes;
  395. }
  396. /**
  397. * The main parsing function.
  398. * @returns {?jsep.Expression}
  399. */
  400. gobbleExpression() {
  401. const node = this.searchHook('gobble-expression') || this.gobbleBinaryExpression();
  402. this.gobbleSpaces();
  403. return this.runHook('after-expression', node);
  404. }
  405. /**
  406. * Search for the operation portion of the string (e.g. `+`, `===`)
  407. * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
  408. * and move down from 3 to 2 to 1 character until a matching binary operation is found
  409. * then, return that binary operation
  410. * @returns {string|boolean}
  411. */
  412. gobbleBinaryOp() {
  413. this.gobbleSpaces();
  414. let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
  415. let tc_len = to_check.length;
  416. while (tc_len > 0) {
  417. // Don't accept a binary op when it is an identifier.
  418. // Binary ops that start with a identifier-valid character must be followed
  419. // by a non identifier-part valid character
  420. if (Jsep.binary_ops.hasOwnProperty(to_check) && (
  421. !Jsep.isIdentifierStart(this.code) ||
  422. (this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))
  423. )) {
  424. this.index += tc_len;
  425. return to_check;
  426. }
  427. to_check = to_check.substr(0, --tc_len);
  428. }
  429. return false;
  430. }
  431. /**
  432. * This function is responsible for gobbling an individual expression,
  433. * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
  434. * @returns {?jsep.BinaryExpression}
  435. */
  436. gobbleBinaryExpression() {
  437. let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
  438. // First, try to get the leftmost thing
  439. // Then, check to see if there's a binary operator operating on that leftmost thing
  440. // Don't gobbleBinaryOp without a left-hand-side
  441. left = this.gobbleToken();
  442. if (!left) {
  443. return left;
  444. }
  445. biop = this.gobbleBinaryOp();
  446. // If there wasn't a binary operator, just return the leftmost node
  447. if (!biop) {
  448. return left;
  449. }
  450. // Otherwise, we need to start a stack to properly place the binary operations in their
  451. // precedence structure
  452. biop_info = { value: biop, prec: Jsep.binaryPrecedence(biop), right_a: Jsep.right_associative.has(biop) };
  453. right = this.gobbleToken();
  454. if (!right) {
  455. this.throwError("Expected expression after " + biop);
  456. }
  457. stack = [left, biop_info, right];
  458. // Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
  459. while ((biop = this.gobbleBinaryOp())) {
  460. prec = Jsep.binaryPrecedence(biop);
  461. if (prec === 0) {
  462. this.index -= biop.length;
  463. break;
  464. }
  465. biop_info = { value: biop, prec, right_a: Jsep.right_associative.has(biop) };
  466. cur_biop = biop;
  467. // Reduce: make a binary expression from the three topmost entries.
  468. const comparePrev = prev => biop_info.right_a && prev.right_a
  469. ? prec > prev.prec
  470. : prec <= prev.prec;
  471. while ((stack.length > 2) && comparePrev(stack[stack.length - 2])) {
  472. right = stack.pop();
  473. biop = stack.pop().value;
  474. left = stack.pop();
  475. node = {
  476. type: Jsep.BINARY_EXP,
  477. operator: biop,
  478. left,
  479. right
  480. };
  481. stack.push(node);
  482. }
  483. node = this.gobbleToken();
  484. if (!node) {
  485. this.throwError("Expected expression after " + cur_biop);
  486. }
  487. stack.push(biop_info, node);
  488. }
  489. i = stack.length - 1;
  490. node = stack[i];
  491. while (i > 1) {
  492. node = {
  493. type: Jsep.BINARY_EXP,
  494. operator: stack[i - 1].value,
  495. left: stack[i - 2],
  496. right: node
  497. };
  498. i -= 2;
  499. }
  500. return node;
  501. }
  502. /**
  503. * An individual part of a binary expression:
  504. * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
  505. * @returns {boolean|jsep.Expression}
  506. */
  507. gobbleToken() {
  508. let ch, to_check, tc_len, node;
  509. this.gobbleSpaces();
  510. node = this.searchHook('gobble-token');
  511. if (node) {
  512. return this.runHook('after-token', node);
  513. }
  514. ch = this.code;
  515. if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
  516. // Char code 46 is a dot `.` which can start off a numeric literal
  517. return this.gobbleNumericLiteral();
  518. }
  519. if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
  520. // Single or double quotes
  521. node = this.gobbleStringLiteral();
  522. }
  523. else if (ch === Jsep.OBRACK_CODE) {
  524. node = this.gobbleArray();
  525. }
  526. else {
  527. to_check = this.expr.substr(this.index, Jsep.max_unop_len);
  528. tc_len = to_check.length;
  529. while (tc_len > 0) {
  530. // Don't accept an unary op when it is an identifier.
  531. // Unary ops that start with a identifier-valid character must be followed
  532. // by a non identifier-part valid character
  533. if (Jsep.unary_ops.hasOwnProperty(to_check) && (
  534. !Jsep.isIdentifierStart(this.code) ||
  535. (this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))
  536. )) {
  537. this.index += tc_len;
  538. const argument = this.gobbleToken();
  539. if (!argument) {
  540. this.throwError('missing unaryOp argument');
  541. }
  542. return this.runHook('after-token', {
  543. type: Jsep.UNARY_EXP,
  544. operator: to_check,
  545. argument,
  546. prefix: true
  547. });
  548. }
  549. to_check = to_check.substr(0, --tc_len);
  550. }
  551. if (Jsep.isIdentifierStart(ch)) {
  552. node = this.gobbleIdentifier();
  553. if (Jsep.literals.hasOwnProperty(node.name)) {
  554. node = {
  555. type: Jsep.LITERAL,
  556. value: Jsep.literals[node.name],
  557. raw: node.name,
  558. };
  559. }
  560. else if (node.name === Jsep.this_str) {
  561. node = { type: Jsep.THIS_EXP };
  562. }
  563. }
  564. else if (ch === Jsep.OPAREN_CODE) { // open parenthesis
  565. node = this.gobbleGroup();
  566. }
  567. }
  568. if (!node) {
  569. return this.runHook('after-token', false);
  570. }
  571. node = this.gobbleTokenProperty(node);
  572. return this.runHook('after-token', node);
  573. }
  574. /**
  575. * Gobble properties of of identifiers/strings/arrays/groups.
  576. * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
  577. * It also gobbles function calls:
  578. * e.g. `Math.acos(obj.angle)`
  579. * @param {jsep.Expression} node
  580. * @returns {jsep.Expression}
  581. */
  582. gobbleTokenProperty(node) {
  583. this.gobbleSpaces();
  584. let ch = this.code;
  585. while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
  586. let optional;
  587. if (ch === Jsep.QUMARK_CODE) {
  588. if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
  589. break;
  590. }
  591. optional = true;
  592. this.index += 2;
  593. this.gobbleSpaces();
  594. ch = this.code;
  595. }
  596. this.index++;
  597. if (ch === Jsep.OBRACK_CODE) {
  598. node = {
  599. type: Jsep.MEMBER_EXP,
  600. computed: true,
  601. object: node,
  602. property: this.gobbleExpression()
  603. };
  604. this.gobbleSpaces();
  605. ch = this.code;
  606. if (ch !== Jsep.CBRACK_CODE) {
  607. this.throwError('Unclosed [');
  608. }
  609. this.index++;
  610. }
  611. else if (ch === Jsep.OPAREN_CODE) {
  612. // A function call is being made; gobble all the arguments
  613. node = {
  614. type: Jsep.CALL_EXP,
  615. 'arguments': this.gobbleArguments(Jsep.CPAREN_CODE),
  616. callee: node
  617. };
  618. }
  619. else if (ch === Jsep.PERIOD_CODE || optional) {
  620. if (optional) {
  621. this.index--;
  622. }
  623. this.gobbleSpaces();
  624. node = {
  625. type: Jsep.MEMBER_EXP,
  626. computed: false,
  627. object: node,
  628. property: this.gobbleIdentifier(),
  629. };
  630. }
  631. if (optional) {
  632. node.optional = true;
  633. } // else leave undefined for compatibility with esprima
  634. this.gobbleSpaces();
  635. ch = this.code;
  636. }
  637. return node;
  638. }
  639. /**
  640. * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
  641. * keep track of everything in the numeric literal and then calling `parseFloat` on that string
  642. * @returns {jsep.Literal}
  643. */
  644. gobbleNumericLiteral() {
  645. let number = '', ch, chCode;
  646. while (Jsep.isDecimalDigit(this.code)) {
  647. number += this.expr.charAt(this.index++);
  648. }
  649. if (this.code === Jsep.PERIOD_CODE) { // can start with a decimal marker
  650. number += this.expr.charAt(this.index++);
  651. while (Jsep.isDecimalDigit(this.code)) {
  652. number += this.expr.charAt(this.index++);
  653. }
  654. }
  655. ch = this.char;
  656. if (ch === 'e' || ch === 'E') { // exponent marker
  657. number += this.expr.charAt(this.index++);
  658. ch = this.char;
  659. if (ch === '+' || ch === '-') { // exponent sign
  660. number += this.expr.charAt(this.index++);
  661. }
  662. while (Jsep.isDecimalDigit(this.code)) { // exponent itself
  663. number += this.expr.charAt(this.index++);
  664. }
  665. if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1)) ) {
  666. this.throwError('Expected exponent (' + number + this.char + ')');
  667. }
  668. }
  669. chCode = this.code;
  670. // Check to make sure this isn't a variable name that start with a number (123abc)
  671. if (Jsep.isIdentifierStart(chCode)) {
  672. this.throwError('Variable names cannot start with a number (' +
  673. number + this.char + ')');
  674. }
  675. else if (chCode === Jsep.PERIOD_CODE || (number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE)) {
  676. this.throwError('Unexpected period');
  677. }
  678. return {
  679. type: Jsep.LITERAL,
  680. value: parseFloat(number),
  681. raw: number
  682. };
  683. }
  684. /**
  685. * Parses a string literal, staring with single or double quotes with basic support for escape codes
  686. * e.g. `"hello world"`, `'this is\nJSEP'`
  687. * @returns {jsep.Literal}
  688. */
  689. gobbleStringLiteral() {
  690. let str = '';
  691. const startIndex = this.index;
  692. const quote = this.expr.charAt(this.index++);
  693. let closed = false;
  694. while (this.index < this.expr.length) {
  695. let ch = this.expr.charAt(this.index++);
  696. if (ch === quote) {
  697. closed = true;
  698. break;
  699. }
  700. else if (ch === '\\') {
  701. // Check for all of the common escape codes
  702. ch = this.expr.charAt(this.index++);
  703. switch (ch) {
  704. case 'n': str += '\n'; break;
  705. case 'r': str += '\r'; break;
  706. case 't': str += '\t'; break;
  707. case 'b': str += '\b'; break;
  708. case 'f': str += '\f'; break;
  709. case 'v': str += '\x0B'; break;
  710. default : str += ch;
  711. }
  712. }
  713. else {
  714. str += ch;
  715. }
  716. }
  717. if (!closed) {
  718. this.throwError('Unclosed quote after "' + str + '"');
  719. }
  720. return {
  721. type: Jsep.LITERAL,
  722. value: str,
  723. raw: this.expr.substring(startIndex, this.index),
  724. };
  725. }
  726. /**
  727. * Gobbles only identifiers
  728. * e.g.: `foo`, `_value`, `$x1`
  729. * Also, this function checks if that identifier is a literal:
  730. * (e.g. `true`, `false`, `null`) or `this`
  731. * @returns {jsep.Identifier}
  732. */
  733. gobbleIdentifier() {
  734. let ch = this.code, start = this.index;
  735. if (Jsep.isIdentifierStart(ch)) {
  736. this.index++;
  737. }
  738. else {
  739. this.throwError('Unexpected ' + this.char);
  740. }
  741. while (this.index < this.expr.length) {
  742. ch = this.code;
  743. if (Jsep.isIdentifierPart(ch)) {
  744. this.index++;
  745. }
  746. else {
  747. break;
  748. }
  749. }
  750. return {
  751. type: Jsep.IDENTIFIER,
  752. name: this.expr.slice(start, this.index),
  753. };
  754. }
  755. /**
  756. * Gobbles a list of arguments within the context of a function call
  757. * or array literal. This function also assumes that the opening character
  758. * `(` or `[` has already been gobbled, and gobbles expressions and commas
  759. * until the terminator character `)` or `]` is encountered.
  760. * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
  761. * @param {number} termination
  762. * @returns {jsep.Expression[]}
  763. */
  764. gobbleArguments(termination) {
  765. const args = [];
  766. let closed = false;
  767. let separator_count = 0;
  768. while (this.index < this.expr.length) {
  769. this.gobbleSpaces();
  770. let ch_i = this.code;
  771. if (ch_i === termination) { // done parsing
  772. closed = true;
  773. this.index++;
  774. if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length){
  775. this.throwError('Unexpected token ' + String.fromCharCode(termination));
  776. }
  777. break;
  778. }
  779. else if (ch_i === Jsep.COMMA_CODE) { // between expressions
  780. this.index++;
  781. separator_count++;
  782. if (separator_count !== args.length) { // missing argument
  783. if (termination === Jsep.CPAREN_CODE) {
  784. this.throwError('Unexpected token ,');
  785. }
  786. else if (termination === Jsep.CBRACK_CODE) {
  787. for (let arg = args.length; arg < separator_count; arg++) {
  788. args.push(null);
  789. }
  790. }
  791. }
  792. }
  793. else if (args.length !== separator_count && separator_count !== 0) {
  794. // NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments
  795. this.throwError('Expected comma');
  796. }
  797. else {
  798. const node = this.gobbleExpression();
  799. if (!node || node.type === Jsep.COMPOUND) {
  800. this.throwError('Expected comma');
  801. }
  802. args.push(node);
  803. }
  804. }
  805. if (!closed) {
  806. this.throwError('Expected ' + String.fromCharCode(termination));
  807. }
  808. return args;
  809. }
  810. /**
  811. * Responsible for parsing a group of things within parentheses `()`
  812. * that have no identifier in front (so not a function call)
  813. * This function assumes that it needs to gobble the opening parenthesis
  814. * and then tries to gobble everything within that parenthesis, assuming
  815. * that the next thing it should see is the close parenthesis. If not,
  816. * then the expression probably doesn't have a `)`
  817. * @returns {boolean|jsep.Expression}
  818. */
  819. gobbleGroup() {
  820. this.index++;
  821. let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
  822. if (this.code === Jsep.CPAREN_CODE) {
  823. this.index++;
  824. if (nodes.length === 1) {
  825. return nodes[0];
  826. }
  827. else if (!nodes.length) {
  828. return false;
  829. }
  830. else {
  831. return {
  832. type: Jsep.SEQUENCE_EXP,
  833. expressions: nodes,
  834. };
  835. }
  836. }
  837. else {
  838. this.throwError('Unclosed (');
  839. }
  840. }
  841. /**
  842. * Responsible for parsing Array literals `[1, 2, 3]`
  843. * This function assumes that it needs to gobble the opening bracket
  844. * and then tries to gobble the expressions as arguments.
  845. * @returns {jsep.ArrayExpression}
  846. */
  847. gobbleArray() {
  848. this.index++;
  849. return {
  850. type: Jsep.ARRAY_EXP,
  851. elements: this.gobbleArguments(Jsep.CBRACK_CODE)
  852. };
  853. }
  854. }
  855. // Static fields:
  856. const hooks = new Hooks();
  857. Object.assign(Jsep, {
  858. hooks,
  859. plugins: new Plugins(Jsep),
  860. // Node Types
  861. // ----------
  862. // This is the full set of types that any JSEP node can be.
  863. // Store them here to save space when minified
  864. COMPOUND: 'Compound',
  865. SEQUENCE_EXP: 'SequenceExpression',
  866. IDENTIFIER: 'Identifier',
  867. MEMBER_EXP: 'MemberExpression',
  868. LITERAL: 'Literal',
  869. THIS_EXP: 'ThisExpression',
  870. CALL_EXP: 'CallExpression',
  871. UNARY_EXP: 'UnaryExpression',
  872. BINARY_EXP: 'BinaryExpression',
  873. ARRAY_EXP: 'ArrayExpression',
  874. TAB_CODE: 9,
  875. LF_CODE: 10,
  876. CR_CODE: 13,
  877. SPACE_CODE: 32,
  878. PERIOD_CODE: 46, // '.'
  879. COMMA_CODE: 44, // ','
  880. SQUOTE_CODE: 39, // single quote
  881. DQUOTE_CODE: 34, // double quotes
  882. OPAREN_CODE: 40, // (
  883. CPAREN_CODE: 41, // )
  884. OBRACK_CODE: 91, // [
  885. CBRACK_CODE: 93, // ]
  886. QUMARK_CODE: 63, // ?
  887. SEMCOL_CODE: 59, // ;
  888. COLON_CODE: 58, // :
  889. // Operations
  890. // ----------
  891. // Use a quickly-accessible map to store all of the unary operators
  892. // Values are set to `1` (it really doesn't matter)
  893. unary_ops: {
  894. '-': 1,
  895. '!': 1,
  896. '~': 1,
  897. '+': 1
  898. },
  899. // Also use a map for the binary operations but set their values to their
  900. // binary precedence for quick reference (higher number = higher precedence)
  901. // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
  902. binary_ops: {
  903. '||': 1, '&&': 2, '|': 3, '^': 4, '&': 5,
  904. '==': 6, '!=': 6, '===': 6, '!==': 6,
  905. '<': 7, '>': 7, '<=': 7, '>=': 7,
  906. '<<': 8, '>>': 8, '>>>': 8,
  907. '+': 9, '-': 9,
  908. '*': 10, '/': 10, '%': 10
  909. },
  910. // sets specific binary_ops as right-associative
  911. right_associative: new Set(),
  912. // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
  913. additional_identifier_chars: new Set(['$', '_']),
  914. // Literals
  915. // ----------
  916. // Store the values to return for the various literals we may encounter
  917. literals: {
  918. 'true': true,
  919. 'false': false,
  920. 'null': null
  921. },
  922. // Except for `this`, which is special. This could be changed to something like `'self'` as well
  923. this_str: 'this',
  924. });
  925. Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
  926. Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
  927. // Backward Compatibility:
  928. const jsep = expr => (new Jsep(expr)).parse();
  929. const staticMethods = Object.getOwnPropertyNames(Jsep);
  930. staticMethods
  931. .forEach((m) => {
  932. if (jsep[m] === undefined && m !== 'prototype') {
  933. jsep[m] = Jsep[m];
  934. }
  935. });
  936. jsep.Jsep = Jsep; // allows for const { Jsep } = require('jsep');
  937. const CONDITIONAL_EXP = 'ConditionalExpression';
  938. var ternary = {
  939. name: 'ternary',
  940. init(jsep) {
  941. // Ternary expression: test ? consequent : alternate
  942. jsep.hooks.add('after-expression', function gobbleTernary(env) {
  943. if (env.node && this.code === jsep.QUMARK_CODE) {
  944. this.index++;
  945. const test = env.node;
  946. const consequent = this.gobbleExpression();
  947. if (!consequent) {
  948. this.throwError('Expected expression');
  949. }
  950. this.gobbleSpaces();
  951. if (this.code === jsep.COLON_CODE) {
  952. this.index++;
  953. const alternate = this.gobbleExpression();
  954. if (!alternate) {
  955. this.throwError('Expected expression');
  956. }
  957. env.node = {
  958. type: CONDITIONAL_EXP,
  959. test,
  960. consequent,
  961. alternate,
  962. };
  963. // check for operators of higher priority than ternary (i.e. assignment)
  964. // jsep sets || at 1, and assignment at 0.9, and conditional should be between them
  965. if (test.operator && jsep.binary_ops[test.operator] <= 0.9) {
  966. let newTest = test;
  967. while (newTest.right.operator && jsep.binary_ops[newTest.right.operator] <= 0.9) {
  968. newTest = newTest.right;
  969. }
  970. env.node.test = newTest.right;
  971. newTest.right = env.node;
  972. env.node = test;
  973. }
  974. }
  975. else {
  976. this.throwError('Expected :');
  977. }
  978. }
  979. });
  980. },
  981. };
  982. // Add default plugins:
  983. jsep.plugins.register(ternary);
  984. module.exports = jsep;
  985. //# sourceMappingURL=jsep.cjs.js.map